@lunora/codegen 1.0.0-alpha.322 → 1.0.0-alpha.324
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 +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-DXhxbij-.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CXmfa4xx.mjs +11 -0
- package/dist/packem_shared/capabilitiesUsedBy-CF7sUwa8.mjs +1 -0
- package/dist/packem_shared/{emitApp-DphNN43J.mjs → emitApp-DuJW6LKD.mjs} +4 -4
- package/package.json +8 -8
- package/dist/packem_shared/DEFAULT_TARGET-DksDPUdg.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BW62y2zs.mjs +0 -11
- package/dist/packem_shared/capabilitiesUsedBy-D3pvpeAt.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -4149,6 +4149,13 @@ interface EmitAppOptions {
|
|
|
4149
4149
|
hasAccess: boolean;
|
|
4150
4150
|
/** App depends on `@lunora/auth` → emit `.auth()` + the lazy build/migrate dance. */
|
|
4151
4151
|
hasAuth: boolean;
|
|
4152
|
+
/**
|
|
4153
|
+
* `false` withholds the `.deliveryAuthorization(...)` builder method and its
|
|
4154
|
+
* `createShardDO` config plumbing — the verdict of the platform gate for the
|
|
4155
|
+
* target's matrix, not the app's usage. Absent means emitted, as before the
|
|
4156
|
+
* gate existed.
|
|
4157
|
+
*/
|
|
4158
|
+
hasDeliveryAuthorization?: boolean;
|
|
4152
4159
|
/** App depends on a worker-composition framework adapter (`@lunora/astro`/`@lunora/svelte`/`@lunora/vue`), or hand-composes one in `src/worker.ts` → emit `.buildFrameworkWorker(host)`. */
|
|
4153
4160
|
hasFramework: boolean;
|
|
4154
4161
|
/** Schema declares **D1-backed** `.global()` tables → emit `.global()` (D1 ctx-db + studio introspector + cross-shard relations). */
|
package/dist/index.d.ts
CHANGED
|
@@ -4149,6 +4149,13 @@ interface EmitAppOptions {
|
|
|
4149
4149
|
hasAccess: boolean;
|
|
4150
4150
|
/** App depends on `@lunora/auth` → emit `.auth()` + the lazy build/migrate dance. */
|
|
4151
4151
|
hasAuth: boolean;
|
|
4152
|
+
/**
|
|
4153
|
+
* `false` withholds the `.deliveryAuthorization(...)` builder method and its
|
|
4154
|
+
* `createShardDO` config plumbing — the verdict of the platform gate for the
|
|
4155
|
+
* target's matrix, not the app's usage. Absent means emitted, as before the
|
|
4156
|
+
* gate existed.
|
|
4157
|
+
*/
|
|
4158
|
+
hasDeliveryAuthorization?: boolean;
|
|
4152
4159
|
/** App depends on a worker-composition framework adapter (`@lunora/astro`/`@lunora/svelte`/`@lunora/vue`), or hand-composes one in `src/worker.ts` → emit `.buildFrameworkWorker(host)`. */
|
|
4153
4160
|
hasFramework: boolean;
|
|
4154
4161
|
/** Schema declares **D1-backed** `.global()` tables → emit `.global()` (D1 ctx-db + studio introspector + cross-shard relations). */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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 p}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,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 N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs";import{default as P}from"./packem_shared/discoverCrons-DBnCama4.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-
|
|
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 p}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,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 N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs";import{default as P}from"./packem_shared/discoverCrons-DBnCama4.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-CF7sUwa8.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs";import{default as W}from"./packem_shared/discoverFunctions-CZgLhsMn.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-WBAqBcfK.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-DV4IglLE.mjs";import{default as w}from"./packem_shared/discoverInserts-BjxXCACZ.mjs";import{d as Y}from"./packem_shared/index-JnqBWRYO.mjs";import{default as Z}from"./packem_shared/discoverMigrations-C9mLIhGZ.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-Jkk8Zgkb.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-DvhyKM-f.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyChannels as me,discoverNotifyConfig as fe}from"./packem_shared/NOTIFY_FILENAME-bAt7J3cs.mjs";import{default as de}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-C8E7TeRT.mjs";import{QUEUES_FILENAME as xe,discoverQueues as Se}from"./packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs";import{default as ue}from"./packem_shared/discoverR2sqlCalls-DVcfMO6-.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-Du7ITNTQ.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-QRsWRQbM.mjs";import{discoverSandboxUsage as Oe}from"./packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs";import{default as Te}from"./packem_shared/discoverSchema-BtsX-CN9.mjs";import{readServiceBindings as Ie,resolveServiceBindings as _e}from"./packem_shared/readServiceBindings-DvqIThzd.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Fe}from"./packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs";import{default as De}from"./packem_shared/discoverStorageRulesMetadata-ClzKLdCV.mjs";import{WORKFLOWS_FILENAME as ye,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs";import{emitApp as He}from"./packem_shared/emitApp-DuJW6LKD.mjs";import{isD1GlobalTable as Be,isHyperdriveGlobalTable as ke}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DFv-RYZU.mjs";import{OPENRPC_VERSION as qe,buildOpenRpcDocument as we,emitOpenRpc as Je,emitOpenRpcModule as Ye}from"./packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs";import{DEFAULT_TARGET as Ze,platformMatrixIds as $e,readProjectTarget as er,resolveCodegenTarget as rr}from"./packem_shared/DEFAULT_TARGET-DXhxbij-.mjs";import{l as tr,r as sr}from"./packem_shared/project-config-file-BV7RR-l6.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ir,runCodegen as mr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CXmfa4xx.mjs";import{SchemaSnapshotParseError as pr,buildSchemaSnapshot as dr,evaluateSchemaDrift as nr,parseSchemaSnapshot as lr}from"./packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs";import{default as xr}from"./packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Ar,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Nr,SDK_TARGETS as gr,generateSdk as Or}from"./sdk/index.mjs";import{redact as Tr,secretKindOf as hr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-DitcRZ1a.mjs";import{e as Mr}from"./packem_shared/server-DAvi_bv_.mjs";import{e as Pr}from"./packem_shared/shard-ceGu_Fps.mjs";import{G as br}from"./packem_shared/shared-DnCokNcE.mjs";import{MESSAGE_SOLUTIONS as Ur,findSolutionByMessage as Gr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as jr,findProjectConfigFile as Br}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{createCodegenProject as Wr,findTsconfig as Kr,refreshCodegenProject as Vr}from"./packem_shared/createCodegenProject-V51_yBw3.mjs";import{s as Qr,t as qr,u as wr}from"./packem_shared/shard-runtime-BpoCV-aM.mjs";import{emitApi as Yr,emitCollections as Xr,emitInternalApi as Zr}from"./packem_shared/emitApi-CDgIPAG2.mjs";import{emitCrons as eo,emitScheduler as ro,emitVectors as oo,emitWranglerCronTriggers as to}from"./packem_shared/emitCrons-BQW2lviZ.mjs";import{emitDataModel as ao}from"./packem_shared/emitDataModel-BskFt9Wv.mjs";import{emitFunctions as mo}from"./packem_shared/emitFunctions-CuZzKaU4.mjs";import{isTypedSchema as po}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{N as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Ze as DEFAULT_TARGET,j as FLAGS_FILENAME,br as GENERATED_HEADER,Ar as LUNORA_ERROR_CODES,Ur as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,qe as OPENRPC_VERSION,jr as PROJECT_CONFIG_FILENAMES,xe as QUEUES_FILENAME,ir as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Nr as SDK_LANGUAGES,gr as SDK_TARGETS,Me as SHAPES_FILENAME,pr as SchemaSnapshotParseError,e as VERSION,ye as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,we as buildOpenRpcDocument,dr as buildSchemaSnapshot,b as capabilitiesUsedBy,Wr as createCodegenProject,n as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,g as discoverAgents,I 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 discoverNotifyChannels,fe as discoverNotifyConfig,le as discoverQueries,Se as discoverQueues,ue as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Oe as discoverSandboxUsage,Te as discoverSchema,Fe as discoverShapes,De as discoverStorageRulesMetadata,Ue as discoverWorkflows,Qr as emitAgents,Yr as emitApi,He as emitApp,Xr as emitCollections,qr as emitContainers,eo as emitCrons,ao as emitDataModel,_r as emitDrizzleSchema,mo as emitFunctions,Zr as emitInternalApi,Ve as emitOpenApi,ze as emitOpenApiModule,Je as emitOpenRpc,Ye as emitOpenRpcModule,ro as emitScheduler,Mr as emitServer,Pr as emitShard,oo as emitVectors,wr as emitWorkflows,to as emitWranglerCronTriggers,l as errorAdvisoryNames,c as errorPlatformDiagnosticNames,nr as evaluateSchemaDrift,Gr as findLunoraSolution,Br as findProjectConfigFile,Kr as findTsconfig,xr as fingerprintSchemaSources,y as foldCapabilitySignals,m as formatAdvisories,Or as generateSdk,Be as isD1GlobalTable,ke as isHyperdriveGlobalTable,R as isTestPath,po as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,tr as loadProjectConfig,U as mayReadCapabilityContext,lr as parseSchemaSnapshot,$e as platformMatrixIds,de as readPackageDependencies,sr as readProjectConfigLiterals,er as readProjectTarget,Ie as readServiceBindings,Tr as redact,Vr as refreshCodegenProject,rr as resolveCodegenTarget,_e as resolveServiceBindings,mr as runCodegen,Er as schemaFromIr,hr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,p as toAdvisorContext,vr as validatorIrToJsonSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{NODE_CAPABILITIES as h,CLOUDFLARE_CAPABILITIES as b,CELLD_CAPABILITIES as S}from"@lunora/platform";import{r as v}from"./project-config-file-BV7RR-l6.mjs";const m="cloudflare",y=t=>{const{target:e}=v(t);return e!==void 0&&e.length>0?e:void 0},R=(t,e)=>e??y(t)??m,E=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=v(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${m}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${m}" }\`), or pass \`--target\`.`,target:m}]},w={max:1536,min:32},z=(t,e)=>{if(t!=="cloudflare")return[];const{max:a,min:r}=w,i=`${String(r)}-${String(a)}`;return e.filter(({dimensions:o})=>o!==void 0&&(!Number.isInteger(o)||o<r||o>a)).map(({dimensions:o,name:s})=>({level:"warn",message:`Vector index "${s}" declares ${String(o)} dimensions; Cloudflare Vectorize accepts ${i}, so creating a Vectorize index for it fails at deploy.`,name:"platform_vector_dimensions_out_of_range",remediation:`If a Vectorize index backs "${s}", use ${i} dimensions (many embedding models can truncate output to fit). Ignore this if another store, such as pgvector, backs it.`,target:t}))},u={celld:S,cloudflare:b,node:h},O=(t,e)=>{const a=u[t];if(a===void 0)return!0;const r=a.features[e]?.level;return r==="native"||r==="emulated"},P=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),_={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},k=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","deliveryAuthorization","durableStreams","globalTables","liveStreams","queues","relationGraph","secrets","services","topics","typedWebSockets","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],g={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",deliveryAuthorization:"delivery authorization (`.deliveryAuthorization(...)` on the app builder)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",liveContext:"the live publisher (`ctx.live`)",liveStreams:"live topic streams (`defineLiveStream`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",typedWebSockets:"typed WebSocket routes and rooms (`defineWebSocket` / `defineRoom`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},x=(t,e,a)=>({level:"error",message:`${e.name} does not support ${g[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),$=(t,e)=>({level:"error",message:`${t.name} withholds live streams, so ctx.live is not available on the "${e}" target, but this app reads ctx.live.`,name:"platform_unsupported_feature",remediation:'Remove the ctx.live usage, or deploy to a target whose capability matrix marks "liveStreams" as native or emulated.',target:e}),D=t=>({level:"error",message:"This app declares defineLiveStream topics and enables delivery authorization. With delivery authorization on, the shard answers every /_lunora/live/* request with 501, so the live streams cannot be served.",name:"platform_live_stream_delivery_authorization",remediation:"Remove the defineLiveStream declarations, or remove the .deliveryAuthorization(...) call. Live streams and delivery authorization cannot be combined.",target:t}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${g[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),A=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:i,signals:o,target:s}=t;for(const n of k){if(o[n]!==!0)continue;const c=r.features[n]?.level;c!=="unsupported"&&c!==void 0||(a[n]=!1,!i.has(n)&&e.push(c==="unsupported"?x(n,r,s):T(n,r,s)))}},L=(t,e,a,r={})=>{const i={...t},o={...r},s=[],n=new Set;for(const[l,d]of Object.entries(_)){if(d===null||!t[l])continue;const f=e.features[d]?.level;f==="unsupported"?(i[l]=!1,n.add(d),s.push({feature:l,level:"error",message:`${e.name} does not support "${l}" (ctx.${l}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${l} usage, or deploy to a target whose capability matrix marks "${d}" as native or emulated.`,target:a})):f===void 0&&(i[l]=!1,n.add(d),s.push({feature:l,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${l}" (ctx.${l}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${d}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}A({diagnostics:s,gatedSignals:o,matrix:e,reported:n,signals:r,target:a});const c=e.features.liveStreams?.level,p=c===void 0||c==="unsupported";return r.liveContext===!0&&p&&s.push($(e,a)),{diagnostics:s,liveStreamsWithheld:p,signals:o,usage:i}},W=(t,e,a={})=>{const r=u[e];return r===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],liveStreamsWithheld:!1,signals:{...a},usage:{...t}}:L(t,r,e,a)},F=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,i)=>r.localeCompare(i));return{id:e.id,name:e.name,unsupported:a}};export{_ as CAPABILITY_TO_FEATURE,m as DEFAULT_TARGET,L as gateAgainstMatrix,W as gatePlatformFeatures,D as liveStreamsDeliveryAuthorizationDiagnostic,O as platformFeatureAvailable,P as platformMatrixIds,y as readProjectTarget,E as readTargetDiagnostics,R as resolveCodegenTarget,F as studioPlatformFor,z as vectorizeDimensionDiagnostics};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{existsSync as M,mkdirSync as Mt,readFileSync as er,writeFileSync as tr,rmSync as Se,readdirSync as En}from"node:fs";import{dirname as _t,join as v,relative as xn}from"node:path";import{performance as ut}from"node:perf_hooks";import{runAdvisor as sr}from"@lunora/advisor";import{LunoraError as j}from"@lunora/errors";import{serializeSchemaSnapshot as nr}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as ir}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as rr,VariableDeclarationKind as or}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as I,bindingKeyName as oe,collectCallRows as C,findObjectProperty as B,collectSecurityCallRows as ar,propertyInitializer as R,listSecurityScanFiles as je,objectLiteralFromCallbackBody as Sn,limitNameOf as An,optionsObjectLiteral as yn,handlerOf as cr,collectNodeRows as se,chainRootOf as He,outermostValueWrapper as w,isWriteTarget as Ge,isSameNode as A,unwrapExpression as h,isConstDeclaration as ne,memberAccessOf as Kt,returningFunctionOf as At,walkChain as lr,RUN_METHODS as bn,functionReferenceSegments as dr,isTestPath as ur,isFunctionLike as ie,functionKeyOf as Nn}from"./isTestPath-B81lOULB.mjs";import{b as Y,d as q,f as D,g as zt,c as x,a as Pn,w as Bt,k as fr,l as gr,h as pr,m as mr,j as yt,i as hr}from"./attribution-hVBriwzy.mjs";import{a as Ps,r as ft,i as H,b as vr,m as wn,c as Ye,e as $t,E as In,C as Cn,d as Er,f as xr,g as Sr}from"./context-root-BdxINX-T.mjs";import{a as N,i as Ar,c as ee,d as Tn,e as yr,f as br}from"./classify-procedure-call-DVxdUhZt.mjs";import{a as S,r as On,s as Nr,b as Pr}from"./project-config-file-BV7RR-l6.mjs";import{a as wr,b as Qe}from"./module-specifiers-WF8iAydP.mjs";import{r as Xe,s as Ir}from"./parse-validator-IDBKIT7M.mjs";import Cr from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as _,r as kn}from"./database-calls-BKozZUEW.mjs";import Tr from"./discoverHyperdriveCalls-DV4IglLE.mjs";import{diagnosticAt as Ne}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Vt,a as ze,s as Rn,d as Or}from"./index-JnqBWRYO.mjs";import{MUTATORS_FILENAME as kr,isDefineMutatorCallee as Rr,mutatorServerImplOf as Fr,discoverMutators as Dr}from"./MUTATORS_FILENAME-Jkk8Zgkb.mjs";import Lr from"./discoverNondeterministicCalls-DvhyKM-f.mjs";import{discoverNotifyConfig as Mr,discoverNotifyCalls as _r}from"./NOTIFY_FILENAME-bAt7J3cs.mjs";import Kr from"./discoverR2sqlCalls-DVcfMO6-.mjs";import zr from"./discoverRlsProcedures-Du7ITNTQ.mjs";import{s as Ut,n as Br}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as $r,redact as Vr,isHeuristicSecretKind as Ur,isSecretishName as Wr}from"./redact-Cy14LEnc.mjs";import{a as Re,d as qr,r as jr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as Hr,discoverWorkflows as Gr}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as Yr}from"./json-data-Chfs2Cz5.mjs";import{G as Qr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Xr}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as Gv,refreshCodegenProject as Yv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as Jr,usedCapabilities as Zr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Fn,isHyperdriveGlobalTable as Dn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as eo}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as to}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import so from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as no,discoverFeatureUsage as io}from"./capabilitiesUsedBy-CF7sUwa8.mjs";import Ln from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as ro,findProjectConfigFile as oo}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{discoverQueueDeclarations as ao}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as co}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as lo}from"./readServiceBindings-DvqIThzd.mjs";import uo from"./discoverStorageRulesMetadata-ClzKLdCV.mjs";import{resolveCodegenTarget as bt,gatePlatformFeatures as fo,readTargetDiagnostics as go,vectorizeDimensionDiagnostics as po,liveStreamsDeliveryAuthorizationDiagnostic as mo,studioPlatformFor as ho,platformFeatureAvailable as vo}from"./DEFAULT_TARGET-DXhxbij-.mjs";import{i as Eo}from"./schema-BgM8A3XV.mjs";import{b as Mn,e as xo}from"./shard-ceGu_Fps.mjs";import{e as So,a as Ao}from"./server-DAvi_bv_.mjs";import{emitDataModel as yo}from"./emitDataModel-BskFt9Wv.mjs";import{i as bo,a as No,e as Po,b as wo,d as Io,c as Co}from"./unwrap-handler-return-CeaOifqX.mjs";import To from"./discoverFunctions-CZgLhsMn.mjs";import Oo from"./discoverHttpRoutes-WBAqBcfK.mjs";import ko from"./discoverInserts-BjxXCACZ.mjs";import{e as _n}from"./exported-procedure-chains-BNBUkXui.mjs";import Ro from"./discoverMigrations-C9mLIhGZ.mjs";import Fo from"./discoverQueries-C8E7TeRT.mjs";import Do from"./discoverRlsMetadata-QRsWRQbM.mjs";import Lo from"./discoverSchema-BtsX-CN9.mjs";import{discoverShapes as Mo}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as _o}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as Ko}from"./emitApp-DuJW6LKD.mjs";import{readJsonSync as zo}from"@visulima/fs";import{buildSchemaSnapshot as Bo}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as $o,emitOpenApiModule as Vo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Uo,emitOpenRpcModule as Wo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as qo,t as jo,u as Ho,s as Go,w as Yo}from"./shard-runtime-BpoCV-aM.mjs";import{emitCollections as Qo,emitSeed as Xo,emitApi as Jo,emitInternalApi as Zo}from"./emitApi-CDgIPAG2.mjs";import{emitCrons as ea,emitScheduler as ta,emitShardRegistry as sa,emitDurableObjects as na,emitVectors as ia,emitWranglerCronTriggers as ra}from"./emitCrons-BQW2lviZ.mjs";import oa from"./emitDrizzleSchema-DitcRZ1a.mjs";import{LAZY_FUNCTION_DIRECTORY as Kn,emitFunctions as aa,emitLazyFunctionModules as ca}from"./emitFunctions-CuZzKaU4.mjs";const zn=new Set(["delete","get","head","options","patch","post","put"]),la=new Set(["handler","stream"]),da=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ws=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),ua=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!zn.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},fa=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||zn.has(n.getName()))break;s=n.getExpression()}return ua(s)},ga=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(ws.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&ws.has(s.getText()))return!0}return!1},pa=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!la.has(n.getName()))return;const i=fa(s);if(!i||!da.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&ga(o);return{exportName:q(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},ma=(e,t)=>{const s=[];for(const n of Y(e)){const i=pa(n,t);i&&s.push(i)}return s},ha=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ma(i,I(t,n)))}return s},va=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Ea=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?oe(t):void 0}},xa=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Ps(a)}))return!1;const n=D(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Ps(i)},Is=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=va(e);return n!==void 0&&Ea(n)===t?!0:t==="args"&&xa(e)},Bn=(e,t)=>r.isIdentifier(e)?Is(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Is(s,t)),Sa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},Cs=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!zt(t)?t.getInitializer():void 0},Nt=e=>Bn(e,"args"),G=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},W=e=>{if(Nt(e))return!0;const t=G(e);return t!==void 0&&Nt(t)},Aa=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=G(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},ae=e=>{if(ft(e))return!0;const t=Cs(e);if(t!==void 0&&ft(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=Cs(i);return o!==void 0&&ft(o)})},Fe=(e,t)=>Bn(e,t),ya=(e,t)=>{if(Fe(e,t))return!0;const s=G(e);if(s!==void 0&&Fe(s,t))return!0;const n=Sa(e);if(n!==void 0){const i=G(n);return i!==void 0&&Fe(i,t)}return!1},ba=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:H(e.getExpression(),["ai"]),Na=(e,t)=>{if(!ba(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)||ae(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},Pa=(e,t)=>C(e,t,Na),wa=new Set(["generateText","streamText"]),Ia=new Set(["messages","prompt","system"]),Ca=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Ta=(e,t)=>Ca.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),Oa=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[vr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Ta(i,s));return n===void 0?void 0:`${n}.${s}`},ka=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=Oa(t);if(s!==void 0)return s}},Ra=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=oe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Fa=e=>{if(Nt(e))return!0;const t=Ra(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(!r.isPropertyAssignment(t)||!Ia.has(S(t)))continue;const s=t.getInitializer();if(s!==void 0&&Fa(s))return!0}return!1},La=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=N(n.getExpression());if(i===void 0||!wa.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(N(c.getExpression())==="tool"&&(a=ka(c),a!==void 0))break;a!==void 0&&s.push({scope:x(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Da(o)})}return s},Ma=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...La(i,I(t,n)))}return s},_a=e=>H(e,["fetch"]),Ka=(e,t)=>{if(!_a(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},za=(e,t)=>C(e,t,Ka),Wt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=Xe(s.getExpression());return n===void 0||Wt(n,t)})}finally{t.delete(e)}},Ba=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=B(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:Xe(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Wt(i)}},$a=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?Xe(o):void 0;a===void 0?s=!0:(t.push(a),s||=Wt(a))}n=i.getExpression()}return{objects:t,opaque:s}},qt=(e,t)=>t?$a(t):Ba(e),$n=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=Xe(s.getExpression());return n===void 0?[]:$n(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[S(s)]:[]})}finally{t.delete(e)}},Va=e=>e.flatMap(t=>$n(t,new Set)),Ua=new Set(["check","length","max"]),Pt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(Ua.has(s.getName()))return!0;t=n}},wt=e=>wr(e)||e==="@lunora/values",Wa=e=>{const t=new Set(["v"]);for(const s of Ar(e,"v",wt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&wt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},qa=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},ja=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Ha=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&wt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),jt=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return ja(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Ha(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ga=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},Ya=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Qa=e=>r.isReturnStatement(e)?e.getExpression():void 0,Xa=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Ya(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Qa(t);return s?[s]:[]}),Vn=(e,t)=>{if(jt(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Vn(e.getExpression(),t)},Ja=(e,t)=>{const s=Ga(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Pt(e),i=new Set(Xa(s).map(o=>Vn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=jt(o,t);return a===void 0?[]:[{bounded:Pt(o)||n&&i.has(o),factory:a}]})},Za=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=jt(s,t),i=n===void 0?[]:[{bounded:Pt(s),factory:n}];return r.isCallExpression(s)?[...i,...Ja(s,t)]:i}),ec=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Za(a,t),l=S(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},tc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ee(n);if(i?.visibility!=="public")return;const{objects:o}=qt(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=ec(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:q(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},sc=(e,t)=>{const s=[],n=Wa(e),i={destructured:qa(e,n),namespaces:n};for(const o of Y(e)){const a=tc(o,t,i);a&&s.push(a)}return s},nc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sc(i,I(t,n)))}return s},gt=e=>e?.getKind()===d.TrueKeyword,ic=e=>e?.getKind()===d.FalseKeyword,rc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,oc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),ac=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&N(t.getExpression())==="scim"),cc=e=>e!==void 0&&r.isCallExpression(e)&&oc.has(N(e.getExpression())??""),lc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),dc=e=>{const t=R(e,"advanced"),s=R(e,"emailAndPassword"),n=R(e,"session");return{analyzable:!0,disableCsrfCheck:gt(R(t,"disableCSRFCheck")),emailPasswordEnabled:gt(R(s,"enabled")),requireEmailVerification:gt(R(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:ac(R(e,"plugins"))&&cc(R(e,"database")),secureCookiesDisabled:ic(R(t,"useSecureCookies")),sessionFreshAgeZero:rc(R(n,"freshAge")),trustedOriginsWildcard:lc(R(e,"trustedOrigins"))}},uc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),fc=(e,t)=>{if(N(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?dc(s):uc();return{scope:x(e),file:t,line:e.getStartLineNumber(),...i}},gc=(e,t)=>ar(e,t,fc),pc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return wn(e.getExpression(),t.matchReceiver)?s:void 0},mc=(e,t,s)=>{const n=pc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!W(i)||ae(i))&&!(s.requireUnmodifiedReach===!0&&!Aa(i)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:n}},Je=(e,t,s)=>C(e,t,(n,i)=>mc(n,i,s)),hc=new Set(["content","pdf","scrape","screenshot"]),vc=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:hc}),Ec=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),xc=new Set(["RateLimiter"]),Sc=new Set(["extend"]),Ts="lunora",Ac=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Un=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=S(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},It=e=>e&&r.isObjectLiteralExpression(e)?Un(e):{analyzable:!1,presentKeys:[],trueKeys:[]},yc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Sn(t.getBody());return s?Un(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},bc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=N(n.getExpression());i!==void 0&&(Ec.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...It(n.getArguments()[0])}):Sc.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...yc(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=N(n.getExpression());i===void 0||!xc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...It(n.getArguments()[0])})}return s},Nc=(e,t)=>{for(const s of Ac){const n=v(t,s);if(!M(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))N(a.getExpression())===Ts&&o.push({callee:Ts,file:s,line:a.getStartLineNumber(),...It(a.getArguments()[0])});return o}return[]},Pc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of je(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...bc(o,n))}return s.push(...Nc(e,_t(t))),s},Os="ctx.containers.",wc=e=>{if(!e.startsWith(Os))return!1;const t=e.slice(Os.length);return t.length>0&&!t.includes(".")},Ic=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:wc,methods:new Set(["get"])}),Cc=new Set(["allow","deny","setAllowed"]),Tc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=B(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},Oc=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Tc(e)))return{detail:"enableInternet: true",scope:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},kc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Cc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Rc=(e,t)=>Oc(e,t)??kc(e,t),Fc=(e,t)=>C(e,t,Rc),Dc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&_(s.getExpression())?s.getName():void 0},Lc=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&_(s)?1:0]},Mc=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),_c=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>Mc.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Kc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return C(e,t,(i,o)=>{const a=Dc(i);if(a===void 0)return;const c=_c(Lc(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:x(i),table:a}})},zc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Bc=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return zc.has(s)?s:void 0},$c=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=S(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(S(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Vc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of je(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=Bc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?$c(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]]),Wc=new Set(["dbRateLimit","rateLimit"]),qc=e=>{const t=yn(e);if(!t)return!1;const s=B(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},jc=(e,t)=>{const s=N(e.getExpression());if(s===void 0)return;const n=Uc.get(s);if(n!==void 0)return{callee:s,scope:x(e),failOpen:qc(e.getArguments()[n]),file:t,limitName:Wc.has(s)?An(e):"",line:e.getStartLineNumber()}},Hc=(e,t)=>C(e,t,jc),Gc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ee(t);if(s?.kind!=="query")return;const n=cr(t,s.receiver);return n?{exportName:q(e)??e.getName(),handler:n}:void 0},ks=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Yc=e=>{const t=ks(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=ks(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Qc=(e,t)=>{const s=[];for(const n of Ye(e.handler,"flags"))s.push({callee:Yc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Xc=(e,t)=>{const s=[];for(const n of Y(e)){const i=Gc(n);i&&s.push(...Qc(i,t))}return s},Jc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xc(i,I(t,n)))}return s},Zc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:H(e.getExpression(),["flags"]),el=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},tl=(e,t)=>{if(!Zc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=el(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:x(e),file:t,key:i,line:e.getStartLineNumber()}},sl=(e,t)=>C(e,t,tl),nl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},il=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},rl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))nl(a)&&s.push({file:o,indexName:il(a),line:a.getStartLineNumber()})}return s},Ae=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,Wn=e=>{const t=e.getArguments()[0],s=Ae(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=B(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?Ae(n.getInitializer()):void 0},ol=new Set(["delete","get","head","options","patch","post","put"]),al=new Set(["handler","stream"]),cl=new Set(["runAction","runMutation"]),ll=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),ye=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,qn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(oe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Rs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:qn(s,"ctx")},Fs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:qn(s,"request")},Ds=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(cl.has(a)&&ye(c,t))return a;if(ll.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&ye(c.getExpression(),t))return`db.${a}`}},Ls=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&ye(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!ye(n.getInitializer(),t))){for(const o of i.getElements())if(oe(o)==="auth")return!0}}return!1},dl=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ul=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&ye(n.getExpression(),t)},fl=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],jn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:fl(s)},gl=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?jn(t,a.getText()):[]}return[]},pl=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=jn(s,t.getText());return n.length>0?n:gl(t,s)},Ms=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>ul(i,t)&&pl(i).some(o=>dl.test(o)))},ml=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!al.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(ol.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},hl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ae(e.getArguments()[0]),l=c&&Rs(c,!0);if(!c||l===void 0||Ms(c,Fs(c,!0)))return;const u=Ds(c,l);return u===void 0?void 0:{scope:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Ls(c,l),sideEffect:u}}const n=ml(e);if(n===void 0)return;const i=Ae(e.getArguments()[0]),o=i&&Rs(i,!1);if(!i||o===void 0||Ms(i,Fs(i,!1)))return;const a=Ds(i,o);return a===void 0?void 0:{scope:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Ls(i,o),sideEffect:a}},vl=(e,t)=>C(e,t,hl),El=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),xl=new Set(["append","set"]),Hn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",_s=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>El.has(N(n.getExpression())??"")&&Fe(n,t)),Sl=(e,t)=>{if(_s(e,t))return!0;const s=G(e);return s!==void 0&&_s(s,t)},Ct=(e,t)=>ya(e,t)&&!Sl(e,t),Al=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=G(e);return t!==void 0&&r.isNewExpression(t)&&N(t.getExpression())==="Headers"},Be=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=G(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Ht=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Ct(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Hn(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Ct(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:S(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=Be(n.getExpression());i!==void 0&&Ht(i,t,s)}},Gn=(e,t)=>{const s=Be(e);if(s===void 0)return;const n=B(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=Be(n.getInitializer());i!==void 0&&Ht(i,"response-init",t)},yl=(e,t)=>{const s=N(e.getExpression());if(s==="Response")Gn(e.getArguments()[1],t);else if(s==="Headers"){const n=Be(e.getArguments()[0]);n!==void 0&&Ht(n,"headers-ctor",t)}},bl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){Gn(e.getArguments()[1],t);return}if(xl.has(n)&&Al(i)){const o=e.getArguments()[1];o!==void 0&&Ct(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"})}},Nl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))yl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))bl(s,t)},Pl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ae(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return Nl(n,{scope:x(e),relativePath:t,requestName:o.getText(),rows:a}),a},wl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...Pl(n,t));return s},Il=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wl(i,I(t,n)))}return s},Yn="identity.ts",Cl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Qe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Tl=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Qe(n.getModuleSpecifierValue())}return!1},Ol=e=>{if(r.isIdentifier(e))return Cl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Tl(t)}return!1},kl=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Ol(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Ne(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Pn(s,"member");a!==void 0&&t.push({exportName:a})}return t},Rl=(e,t)=>{const s=v(t,Yn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=kl(n);if(i.length!==0){if(i.length>1)throw Ne(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Fl=new Set(["auth","context.auth"]),Dl="userId",Ll=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(S(s))}return t},Ml=(e,t)=>{const s=v(t,Yn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(N(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Ll(o):void 0}},Ks=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Fl.has(t.getText())||H(t,["auth"])?e:void 0},_l=e=>{if(r.isPropertyAccessExpression(e)&&Ks(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Ks(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},zs=(e,t,s)=>{const n=_l(e);return n===void 0?void 0:{declared:n===Dl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:x(e)}},Kl=(e,t)=>{const s=Ml(e,t);return s===void 0?[]:[...se(e,t,d.PropertyAccessExpression,(n,i)=>zs(n,i,s)),...se(e,t,d.ElementAccessExpression,(n,i)=>zs(n,i,s))]},zl=(e,t)=>{if(N(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=R(s,"key");if(!(!n||!W(n)||ae(n)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},Bl=(e,t)=>C(e,t,zl),$l=new Set(["delete","get","getRaw","getWithMetadata","put"]),Vl=(e,t,s=[])=>{const n=Je(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:$l});return Bt(n,s)},Ul=new Set(["queue","send"]),Bs=new Set(["bcc","cc","to"]),Wl=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ul.has(t))return;const s=e.getExpression();return H(s,["mail"])||H(s,["email"])?t:void 0},ql=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Bs.has(S(t))&&W(n)&&!ae(n)}if(!r.isPropertyAssignment(t)||!Bs.has(S(t)))return!1;const s=t.getInitializer();return s!==void 0&&W(s)&&!ae(s)}):!1,jl=(e,t)=>{const s=Wl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!ql(n)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Hl=(e,t)=>C(e,t,jl),Gl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=ze(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=ze(l);if(u===void 0)continue;const f=Rn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Yl=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;return n?.receiver?Vt(n.receiver).flatMap(i=>Gl(i,q(e)??e.getName(),t)):[]},Ql=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Y(i))s.push(...Yl(a,o))}return s},Xl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Jl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=B(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Zl=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Rr(s.getExpression())?s:void 0},ed=e=>{const t=Zl(e),s=t===void 0?void 0:Jl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?q(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Xl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},td=e=>e.getVariableDeclarations().flatMap(t=>ed(t)),sd=(e,t)=>{const s=v(t,kr);if(!M(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return td(n)},nd=new Set(["delete","get","patch"]),id=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),rd=new Set(["auth","identity","session","user"]),od=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),ad=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},cd=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},ld=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),dd=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,ud=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>ld(s.getExpression(),t)&&dd(s.getThenStatement())),fd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!nd.has(i))continue;const o=n.getExpression();if(!(_(o)||r.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},gd=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>$t(He(s))!==void 0)),pd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>od.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),md=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(id.has(t.getText()))return!0;return[...rd].some(t=>Ye(e,t).length>0)?!0:gd(e)||pd(e)},hd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ee(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Wn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Tn(n.receiver,"use","rls"),a=md(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=ad(u);if(f===void 0)continue;const g=cd(u);if(g===void 0||c.has(g)||!ud(i,g))continue;const p=fd(i,g);p!==void 0&&(c.add(g),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:f,usesRls:o,visibility:n.visibility}))}return l},vd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Y(i))s.push(...hd(a,o))}return s},Qn=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Ed=e=>{const t=w(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Ge(s)},xd=e=>{const t=w(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Sd=e=>{const s=w(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Ge(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},$e=e=>{const t=D(e);return t===void 0||gr(t.getSourceFile())},Tt=(e,t)=>{const s=w(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&$e(o);if(Qn(He(o),t))return!(r.isPropertyAccessExpression(o)&&In.has(o.getName()))||r.isExpressionStatement(w(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!$e(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},De={kind:"opaque"},Ad={kind:"unreached"},yd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Ot=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=yd(s);return i===void 0||zt(i)?void 0:i}const n=ne(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Xn=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?De:c===void 0?a.some(l=>l.isRestParameter())?De:Ad:c.isRestParameter()?De:{kind:"parameter",parameter:c}},bd=e=>{const t=w(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Ot(s.getExpression());return n===void 0?De:Xn(n,s,t)},Nd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Pd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Jn=e=>{const t=w(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Pd(s);if(n!==void 0)return A(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},wd=4,Zn=(e,t,s=0)=>{if(fr(e))return!0;if(Ed(e)){const i=w(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!Nd.has(c)}if(xd(e)||Sd(e)||Jn(e)||Tt(e,t))return!0;const n=bd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Id(n.parameter,s+1)},$s=new WeakMap,Id=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=$s.get(e.compilerNode);if(n!==void 0)return n;if(t>wd)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||Zn(a,void 0,t));return(o||t===0)&&$s.set(e.compilerNode,o),o},Vs=new WeakMap,Cd=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=D(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Td=(e,t,s)=>{const{context:n,impl:i}=e,o=Vs.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const p=g.getNameNode();return r.isIdentifier(p)?[p]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?Zn(g,n):!Ge(g),f=!Cd(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const p=g.getText();if(p==="arguments")return!1;const E=l.get(p);return E===void 0||c.includes(g)||D(g)?.compilerNode!==E?!0:u(g)});return Vs.set(i.compilerNode,f),f},Us=new WeakMap,Od=e=>{let t=Us.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Fr(s);return n===void 0?[]:[[n.compilerNode,s]]})),Us.set(e.compilerNode,t)),t},kd=e=>{const t=Od(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:q(n)??n.getName()};return a!==void 0&&Td(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},pt="args",he=e=>{const t=Kt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===pt?t.member:void 0}if(!r.isIdentifier(e))return;const s=D(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ne(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&oe(i)===pt||r.isIdentifier(o)&&o.getText()===pt?oe(s):void 0},Rd=new Set(["auth","identity","user"]),kt=e=>{const t=i=>{const o=$t(i);return o!==void 0&&o.length>0&&Rd.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=G(s);return n!==void 0&&t(n)},ei=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=he(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?G(n):void 0;if(o!==void 0)for(const a of ei(o,t-1))s.add(a)}return s},Le=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Le(n),...Le(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=he(h(u)??u);return g===void 0?[]:Le(f).filter(p=>p===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=he(h(n)??n),c=he(h(i)??i);return a!==void 0&&kt(i)&&o.push(a),c!==void 0&&kt(n)&&o.push(c),o},Fd=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&yr(i.getExpression(),"defineIdentityGuard")},Dd=e=>{if(!Fd(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=he(h(s)??s),o=t.some((a,c)=>c!==n&&kt(a));return i!==void 0&&o?[i]:[]})},Ld=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},Md=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Ws=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},_d=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Kd=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Ws(n,e)&&Ld(n.getThenStatement()))for(const i of Le(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&_d(n)&&Ws(n,e))for(const i of Dd(n))s.add(i);return s},zd=(e,t)=>{const s=ei(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Md);if(n===void 0)return!1;const i=Kd(n,e.getStart());return[...s].every(o=>i.has(o))},Bd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),$d=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Rt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),ti=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Vd=e=>{const t=w(e),s=t.getParent();if(r.isVariableDeclaration(s))return A(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Ud=e=>{const t=Vd(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ne(t)?[t]:void 0:ti(t)},ve=e=>e.isUnion()?e.getUnionTypes().every(t=>ve(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ve(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ve=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Me=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Wd=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&$d.get(s.getText())?.has(t.getName())===!0&&$e(s)},qd=e=>{const t=At(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=w(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ve(n,Cn)?n:void 0},jd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=w(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ve(n,Bd,t)?n:void 0},Hd=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Gd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&A(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},qs=e=>{const t=w(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Wd(s);return jd(s,t)??Hd(s,t)??Gd(s,t)??(n?s:qd(t))},Yd=5e4,si=()=>({inProgress:new Set,verdicts:new Map});class Qd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Yd&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Xd=8,Jd=8;class Zd{budget;scope;taint;verdicts=si();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ve(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?ti(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Xd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(w(l),!0,a,0))&&(t===n||!ve(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let p=qs(o);p!==void 0;p=qs(o)){if(r.isCallExpression(p)&&this.callbackCompromises(p,n))return!0;o=w(p)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ve(o.getType());if(Ge(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Ud(o);if(u!==void 0)return u.some(p=>n(p,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=w(t).getParent();if(n>=Jd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===w(t)?this.valueCompromises(i,!1,s,n+1):!Ve(i,Rt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ne(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=w(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Me(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ve(t,Rt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Ot(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!Tt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(Tt(s,this.scope.context))return!1;const i=Ot(t.getExpression()),o=i===void 0?void 0:Xn(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Jn(t)||A(At(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=At(t);return A(s,this.scope.impl)?void 0:s}}const eu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),tu=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=D(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},su=new Set(["all","allSettled","any","race"]),js=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,mt=8;class nu{budget=new Qd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=si();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Zd(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,mt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>pr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=D(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=w(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Rt.has(g.getName()))return!0;const p=a.getArguments().filter(E=>E!==o);return this.isTaintedValue(g.getExpression(),!0)||p.some(E=>this.isTaintedValue(E,!1))}const c=r.isVariableDeclaration(a)&&ne(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const p=w(g),E=p.getParent();return!r.isCallExpression(E)||E.getExpression()!==p||this.isCallSiteTainted(E,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&$e(i)&&su.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Me(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),i=js(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&In.has(i)?!1:i!==void 0&&Cn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Me(a)!==void 0)&&(i===void 0||!eu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=He(i),c=r.isIdentifier(a)?js(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Me(i);if(o===void 0)return!tu(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=lr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Qn(i,this.scope.context))return!0;const o=r.isIdentifier(i)?D(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ne(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=zt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,mt))return!1;if(this.variableDepth>=mt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Hs=new WeakMap,iu=e=>{const t=Hs.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new nu(e);return Hs.set(e.impl.compilerNode,s),s},ru=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ou=new Set(["insert","insertManyUnsafe","patch","replace"]),au=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return ou.has(t)&&Er(e.getExpression())?t:void 0},cu=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},lu=(e,t)=>{const s=Kt(e);return s?.member===t?h(s.object):void 0},Gs=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,ni=(e,t,s,n=1)=>{const i=lu(e,s);if(i!==void 0)return Gs(i,t);const o=r.isIdentifier(e)?D(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&oe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ne(l)&&Gs(h(l.getInitializer()),t))}const a=ne(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&ni(a,t,s,n-1)},Ft=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ft(t.getWhenTrue()),...Ft(t.getWhenFalse())]:[t]},du=(e,t,s)=>{const n=[],i=s===void 0?void 0:iu(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=S(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=S(o),c=o.getNameNode()),a===void 0||c===void 0||!ru.has(a))continue;const l=Ft(c).filter(f=>i===void 0?W(f)&&!xr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&ni(c,s.parameter,a),g=l.every(p=>zd(t.call,p));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},uu=(e,t,s)=>{const n=au(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=cu(i,n);if(o.length===0)return[];const a=x(e),c=kd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>du(u,l,c))},fu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=C(e,t,(c,l)=>uu(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Bt(o,s).map(c=>mr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},gu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),pu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,mu=e=>{const t=B(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?pu(t.getInitializer()):void 0},hu=(e,t)=>{const s=N(e.getExpression());if(s===void 0||!gu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?mu(n):void 0;return{callee:s,scope:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},vu=(e,t)=>C(e,t,hu),Eu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),xu=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Su=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=B(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},ii=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},ri=(e,t)=>e===t||e.startsWith(`${t}.`),oi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Ys=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},ai=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Ys(s));return r.isIdentifier(e)&&Ys(e)&&t.push(e),t},Au=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},yu=e=>{const t=ii(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},bu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:yu(e),i=new Set,o=a=>oi(a).some(c=>n.some(l=>ri(c.getText(),l)))?!0:ai(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Au(a))i.add(l)}return{names:i,prefixes:n}},Nu=(e,t)=>oi(e).some(s=>t.prefixes.some(n=>ri(s.getText(),n)))?!0:ai(e).some(s=>t.names.has(s.getText())),Pu=e=>{const t=dr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},wu=(e,t,s)=>{const n=ii(e,0);if(n===void 0)return[];const i=bu(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!bn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Nu(u,i))continue;const f=Pu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:x(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Iu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=xu(n),o=i===void 0?void 0:Eu.get(i);if(o===void 0)continue;const a=Su(n,o);a!==void 0&&s.push(...wu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Cu=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Iu(i,I(t,n)))}return s},Qs={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Xs=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()),Ou=e=>{const s=Tu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Xs.has(s)||Xs.has(n)},ku=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}=qt(e,t);return Va(s).some(i=>ku(i))?!0:n?void 0:!1},Fu=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!B(t,"captcha"),usesRateLimit:!!B(t,"rateLimit")}},Du=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},_e={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Lu=e=>{const t=Du(e),s=t?N(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Fu(t);return{..._e,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Qs?{..._e,[Qs[s]]:!0}:_e},Mu=e=>{const t={..._e};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=Lu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},_u=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Ku=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!_u.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:Ou(i.getLiteralText())},zu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Js=new Set(["queues","scheduler","topics","workflows"]),Bu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!zu.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Js.has(s.getName())&&Sr(s.getExpression()))return!0;s=s.getExpression()}const n=$t(s);return n?.length===1&&Js.has(n[0]??"")},$u=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},ci=new Set(["generateObject","generateText","streamObject","streamText"]),Vu=e=>{const t=N(e.getExpression());return t!==void 0&&ci.has(t)},Uu=e=>{const t=N(e.getExpression());if(t===void 0||!ci.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!B(s,"maxOutputTokens")},Wu=new Set(["log","span","trace"]),qu=new Set(["ai"]),ju=new Set(["email","mail"]),Hu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),ht=(e,t)=>[...t].some(s=>Ye(e,s).length>0),li=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Gu=new Set(["every","filter","flatMap","forEach","map","some"]),Yu=new Set(["all","allSettled","race"]),di=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Gu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Yu.has(n))return t},Qu=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(li.has(t.getKind())){const s=di(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Xu=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(li.has(t.getKind())){if(t=di(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Ju=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(p=>{const E=p.getExpression();return r.isIdentifier(E)&&E.getText()===l&&r.isAwaitExpression(p.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Zu=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},ef=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},tf=e=>{let t=!1,s=!0;for(const n of[...Hu].flatMap(i=>Ye(e,i))){const i=ef(n);i&&(t=!0,!Qu(i)&&!Zu(i)&&!Ju(i)&&!Xu(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},sf=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),Zs="lunora-advisor-exempt",nf=/^[\s*/]+/u,rf=/[\w-]/u,of=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
2
|
+
`);for(const n of s.split(`
|
|
3
|
+
`)){const i=n.replace(nf,"");if(!i.startsWith(Zs))continue;const o=i.slice(Zs.length);if(rf.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:""}},af=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=B(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},cf=(e,t)=>{const s=af(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},lf=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(Ku(l)&&(o=!0),Bu(l)&&(t=!0),$u(l)&&(i=!0),Vu(l)&&(s=!0),Uu(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=tf(e);return{callsMail:ht(e,ju),emitsEvent:ht(e,Wu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||ht(e,qu),throwsBareError:sf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},df=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ee(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Mu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=cf(e,s);return{...o?lf(o):{},...of(e),...i,analyzableBody:o!==void 0,exportName:q(e)??e.getName(),file:t,hasEmailArg:Ru(s,n.receiver),kind:n.kind,visibility:n.visibility}},uf=(e,t)=>{const s=[];for(const n of Y(e)){const i=df(n,t);i&&s.push(i)}return s},ff=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...uf(i,I(t,n)))}return s},gf=new Set(["dbRateLimit","rateLimit"]),pf=e=>r.isArrowFunction(e)?e.getBody():e,mf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},ui=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},fi=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},hf=(e,t)=>W(e)||t!==void 0&&fi(e,t).some(s=>ui(s)),vf=(e,t)=>t===void 0?ae(e):fi(e,t).some(s=>!ui(s)),Ef=(e,t)=>{const s=N(e.getExpression());if(s===void 0||!gf.has(s))return;const n=R(yn(e.getArguments()[2]),"key");if(!n)return;const i=pf(n),o=mf(n);if(!(!hf(i,o)||vf(i,o)))return{callee:s,scope:x(e),file:t,limitName:An(e),line:e.getStartLineNumber()}},xf=(e,t)=>C(e,t,Ef),Sf=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Af=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Sf.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},yf=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},bf=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},gi=(e,t=!1)=>{const s=bf(e);if(r.isIdentifier(s)){if(t)return;const n=G(s);return n===void 0?void 0:gi(n,!0)}if(r.isCallExpression(s))return Af(s)??yf(s)},Nf=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},Pf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ee(s);if(n?.kind!=="query")return[];const i=Wn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&br(n.receiver,"output"),a=n.receiver!==void 0&&Tn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Nf(i)){const f=gi(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},wf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Y(i))s.push(...Pf(a,o))}return s},If=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(S(s));return t},Cf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=kn(o);if(a===void 0)continue;const c=If(R(a.options,"with"));c.length!==0&&i.push({exportName:q(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Tf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Y(i))s.push(...Cf(a,o))}return s},U=(e,t)=>`${e}:${t}`,en=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Of=(e,t)=>[...se(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?en(s,n,s.getName(),s.isExported()):void 0),...se(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?en(i,n,s.getName(),i.isExported()):void 0})],kf=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(U(c,a))},Rf=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Ff=(e,t)=>{const s=new Map(e.map(n=>[U(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(U(i.file,i.name))?.set(Rf(n),{fields:n.fields,method:n.method,table:n.table})}return s},Df=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>kf(n,t,s)).filter(n=>n!==void 0),Lf=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(U(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(U(o.file,o.name))?.push(a)}},Mf=(e,t,s)=>{const n=new Map(e.map(a=>[U(a.file,a.name),a])),i=new Map(e.map(a=>[`${Ut(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[U(a.file,a.name),Df(a,n,t)]));return Lf(s,n,i,o),o},_f=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Kf=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(U(i.file,i.name))??[])_f(t.get(U(i.file,i.name)),t.get(U(o.file,o.name)))&&(n=!0)}},zf=(e,t,s,n)=>{const i=Of(e,t),o=Ff(i,s);return Kf(i,o,Mf(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(U(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ue=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ue(e.getLeft()),s=Ue(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Bf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ue(t)!==void 0},$f=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return S(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Vf=(e,t,s)=>Ur(e)?!ur(s)&&Wr($f(t)):!0,Uf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Bf(o))continue;const a=Ue(o);if(a===void 0)continue;const c=$r(a);if(c===void 0||!Vf(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:Vr(a)}))}return s},Wf=(e,t)=>{const s=[];for(const n of y(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Uf(i,I(t,n)))}return s},qf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=kn(o);if(a===void 0)continue;const c=R(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&W(c);!l&&!u||i.push({exportName:q(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},jf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Y(i))s.push(...qf(a,o))}return s},Hf=new Set(["query","unsafe"]),Gf=e=>!r.isPropertyAccessExpression(e)||!Hf.has(e.getName())?!1:H(e.getExpression(),["sql"]),Yf=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Qf=(e,t)=>{if(!Gf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Yf(s)))return{file:t,line:s.getStartLineNumber(),scope:x(e)}},Xf=(e,t)=>C(e,t,Qf),Jf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Zf=e=>{for(const[t,s]of Jf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},eg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Zf(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},tg=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),sg=(e,t,s=[])=>{const n=Je(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:tg,requireUnmodifiedReach:!0});return Bt(n,s)},ng=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),ig=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,rg=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=S(i);t.push(o),o==="expiresInSeconds"&&(s=ig(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},og=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=ng.get(t);return s===void 0?void 0:wn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},ag=(e,t)=>{const s=og(e.getExpression());if(s!==void 0)return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...rg(e.getArguments()[s.optionsIndex])}},cg=(e,t)=>C(e,t,ag),lg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),pi=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:lg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>ie(i)||s(i));if(!(n===void 0||ie(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Gt=(e,t)=>A(e.getFirstAncestor(s=>A(s,t)||ie(s)),t),dg=(e,t)=>A(e,t)||e.getFirstAncestor(s=>A(s,t))!==void 0,mi=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return A(e,t)||Gt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=pi(e);return s!==void 0&&!dg(s,t)}return!1},hi=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],ug=e=>hi(e).some(t=>mi(t,e)),fg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},gg=e=>hi(e).some(t=>mi(t,e)||r.isBreakStatement(t)&&A(pi(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>fg(t)&&Gt(t,e)),pg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Gt(t,e)),mg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),hg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",vt=(e,t)=>{const s=mg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||gg(e)||pg(e))return;const i=x(e);if(!(i.kind==="module"&&e.getFirstAncestor(ie)!==void 0))return{file:t,kind:hg(e),line:e.getStartLineNumber(),scope:i}},vg=(e,t)=>[...se(e,t,d.WhileStatement,vt),...se(e,t,d.ForStatement,vt),...se(e,t,d.DoStatement,vt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),Eg=new Set(["when","where"]),Et=new Set(["definePolicy","defineShape"]),xg=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Et.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return Et.has(i)?i:void 0}const s=t.getText();return Et.has(s)?s:void 0},Sg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,vi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Sg(e))return"empty-object";if(r.isParenthesizedExpression(e))return vi(e.getExpression())}},Yt=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),Ag=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Yt(t)===e),Ei=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>Yt(t)===e),yg=e=>{const t=Ag(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Ei(e).length>0},bg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>Yt(t)===e),Dt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",Ng=(e,t)=>Dt(e)||Dt(t),Pg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),tn=e=>!Dt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),wg=(e,t,s)=>{const n=Pg.get(e);if(n!==void 0)return Ng(t,s)?n==="positive"?"negative":"positive":tn(t)||tn(s)?void 0:n},Ee=e=>{if(r.isParenthesizedExpression(e))return Ee(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=wg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=Ee(e.getLeft()),i=Ee(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},sn=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},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},Cg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Tg=e=>{const t=[];for(const s of Ei(e)){const n=Ee(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of bg(e)){const n=Ee(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?sn(s.getThenStatement()):sn(s.getElseStatement())??Ig(s);i!==void 0&&t.push(Cg(i))}return t},Og=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},kg=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!Eg.has(S(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&yg(a))for(const c of Tg(a)){const l=vi(c);l!==void 0&&i.push({exportName:Og(e),file:s,form:l,key:S(o),line:c.getStartLineNumber(),owner:t})}}return i},Rg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=xg(n);i!==void 0&&s.push(...kg(n,i,t))}return s},Fg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Rg(i,I(t,n)))}return s},Dg=new Set(["query","upsert","upsertMany","upsertNow"]),fe=new Set,Lg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Dg.has(t))return H(e.getExpression(),["vectors"])?t:void 0},Qt=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},xi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Si=e=>xi(e)?.getDeclarations()[0],Mg=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Ai=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},nn=(e,t,s)=>{const n=xi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Ai(Si(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return Xt(o,t,s-1)}return W(e)},Xt=(e,t,s)=>{const n=Qt(e);return ae(n)?!1:r.isIdentifier(n)?nn(n,t,s):W(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>Mg(i)&&nn(i,t,s))},yi=e=>{const t=Ai(Si(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},Z=(e,t)=>{const s=Qt(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...Z(s.getWhenTrue(),t),...Z(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...Z(s.getLeft(),t),...Z(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=yi(s);return n===void 0?[]:Z(n,!1)}return[]},_g=(e,t)=>{const s=Z(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>We(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Kg=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",zg=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),We=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=_g(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Kg(n)&&(s=[zg(n)]);return s},Bg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},$g=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return fe;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return fe;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Lt=(e,t=!0,s=fe)=>{const n=Qt(e);if(r.isIdentifier(n)){const o=t?yi(n):void 0;return o===void 0?[{node:n,parameters:s}]:Lt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Lt(o.getExpression(),t,s):Z(o,!0).flatMap(a=>We(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=Xt(i.getExpression(),fe,1)?$g(o):fe;return Bg(o).flatMap(c=>Z(c,!0).flatMap(l=>We(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Vg=(e,t)=>{const s=Lg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Lt(n):Z(n,!0).flatMap(o=>We(o,!0).map(a=>({node:a,parameters:fe})))).some(({node:o,parameters:a})=>Xt(o,a,1))))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Ug=(e,t)=>C(e,t,Vg),Wg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:p,workflows:E}=s;return ir({adminRoutes:ha(e,t),aiRawRuns:Pa(e,t),aiToolSideEffects:Ma(e,t),argumentDerivedFetches:za(e,t),argumentValidators:nc(e,t),authApiCalls:Cr(e,t),authConfigs:gc(e,t),browserUrlAccesses:vc(e,t),callEdges:n.callEdges,configCalls:Pc(e,t),containerKeyAccesses:Ic(e,t),containerOverrides:Fc(e,t),containers:i,countReads:Kc(e,t,f.tables),cronTargets:o.flatMap(V=>V.functionPath===void 0?[]:[V.functionPath]),exportSinks:Vc(e,t),staleMigrationImports:eg(e,t),failOpenGuards:Hc(e,t),flagReads:Jc(e,t),flagSecurityDefaults:sl(e,t),geoIndexUsages:rl(e,t),httpActionGuards:vl(e,t),httpHeaderWrites:Il(e,t),hyperdriveCalls:Tr(e,t),identityClaimReads:Kl(e,t),imageDeliveryUrlAccesses:Bl(e,t),inserts:n.inserts,kvKeyAccesses:Vl(e,t,a),mailRecipientAccesses:Hl(e,t),maskProcedures:Or(e,t),maskStrategies:Ql(e,t),mutatorWrites:sd(e,t),nondeterministicCalls:Lr(e,t),normalizeIdAuthorizations:vd(e,t),notifyCalls:_r(e,t),notifyConfig:Mr(e,t),mutators:l,ownerFieldWrites:fu(e,t,a,l),unrestrictedWhereBranches:Fg(e,t),paymentWebhooks:vu(e,t),privilegedDispatches:Cu(e,t),procedureProtections:ff(e,t),queries:n.queries,queues:u,r2sqlCalls:Kr(e,t),ratelimitKeySelectors:xf(e,t),rawRowReturns:wf(e,t),relationLoads:Tf(e,t),rlsProcedures:zr(e,t),schema:f,secretLiterals:Wf(e,t),modules:c,shapes:g,softDeleteReads:jf(e,t),sqlInterpolations:Xf(e,t),storageKeyAccesses:sg(e,t,a),storageUploads:cg(e,t),tableWrites:n.tableWrites,rowEffects:zf(e,t,n.tableWrites,n.callEdges),unboundedLoops:vg(e,t),vectorNamespaceAccesses:Ug(e,t),workflowCalls:n.workflowCalls,workflows:E,wranglerVariables:p})},qg=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),jg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>qg(i))]},Hg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Gg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",rn={error:"ERROR",info:"INFO",warn:"WARN"},on={ERROR:2,INFO:0,WARN:1},Yg=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"}),Qg=(e,t)=>{const{advisor:s}=On(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(rn,n)?rn[n]:void 0;return i===void 0?[...t,Yg(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=>Gg(o)||on[o.level]>=on[i])},Xg=(e,t)=>{const{advisor:s}=On(e),n=jg(t,s?.accept??[]);return Qg(e,s?.acceptUnreadable===!0?[...n,Hg()]:n)},Jg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Zg="crons",ep=Hr.replace(/\.ts$/u,""),ue=(e,t)=>`${Ut(e)}:${t}`,xt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},tp=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Jg[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,...xt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...xt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...xt("workflow",t.workflow,"workflow name")}))],sp=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",np=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:sp(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},ip=e=>tp(e).flatMap(t=>np(t)),rp=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:Zg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],op=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),me=(e,t)=>t===void 0?e:{...e,module:t},ap=e=>{const t=new Map,s=new Map,n=op(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(ue(c.file,c.exportName),l)};for(const c of e.functions){const l=ue(c.filePath,c.exportName),u=[...Br(c.filePath),c.exportName].join(".");o(me({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Re(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ue(c.filePath,c.exportName);o(me({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Re(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(me({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(me({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Re(e.modules,c.filePath)),ue(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(me({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Re(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ue(ep,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}},cp=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,lp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ue(e.file,e.exportName))??{reason:cp(e.exportName)},dp=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=lp(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},St=e=>`${e.from}|${e.kind}|${e.to}`,up=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,fp=e=>{const{nodes:t,sites:s}=ap(e),n=new Map,i=new Map;for(const o of[...rp(e),...ip(e)]){const a=dp(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};i.set(up(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:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},gp=e=>`${Qr}export const architecture = ${Yr(e,"Record<string, unknown>")};
|
|
4
|
+
`,an=(e,t="api")=>{const s=new Map;for(const n of e){const i=Ut(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new j("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},pp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Fn(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=>Dn(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:Jr)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)},mp=(e,t,s={})=>{if(t===void 0)return;const n=pp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
5
|
+
`);throw new j("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
6
|
+
${i}
|
|
7
|
+
|
|
8
|
+
Install them with your package manager, then re-run codegen.`)},hp="env.ts",vp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Qe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Ep=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Qe(n.getModuleSpecifierValue())}return!1},xp=e=>{if(r.isIdentifier(e))return vp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Ep(t)}return!1},Sp=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!xp(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Ne(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Pn(s,"member");a!==void 0&&t.push({exportName:a})}return t},Ap=(e,t)=>{const s=v(t,hp);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Sp(n);if(i.length!==0){if(i.length>1)throw Ne(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},yp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"typedWebSockets"},bp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Np=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},Pp=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(S(s));if(!r.isPropertyAssignment(s)||!t.has(S(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),wp=new Set(["durable"]),Ip=new Set(["rollback"]),bi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Cp="defineApp",xe="app",cn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>S(s)===xe&&s.getInitializer()?.getText()===t)||t===xe&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>S(s)===xe),Tp=e=>{if(e===void 0||!ro.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&S(e)===xe;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return S(t)===xe;if(r.isVariableDeclaration(t))return cn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&cn(e.getSourceFile(),s)},Op="AppBuilder",Ni=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},kp=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Op&&s.getDeclarations().some(n=>Ni(n))},Rp=e=>e.getText()===Cp&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Ni(t)),Pi=(e,t,s=new Set)=>{const n=He(t);if(n===void 0||!r.isIdentifier(n))return!1;if(Rp(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return Tp(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Pi(e,a.getInitializer(),s)}}return!1},wi=(e,t)=>{const s=Kt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Pi(e,s.object)||kp(s.object))},Fp=new Map([["defineContainer",{keys:bp,signal:"containerEgressPolicy"}],["defineStep",{keys:Ip,signal:"workflowRollback"}],["stream",{keys:wp,signal:"durableStreams"}]]),Dp=(e,t)=>{const s=Fp.get(bi(t));if(s!==void 0)return t.getArguments().some(n=>Pp(Np(e,n),s.keys))?s.signal:void 0},Lp=(e,t)=>yp[bi(t)]??(wi(e,t)?"deliveryAuthorization":void 0),Mp=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const a=no(o);n.secrets=n.secrets||a.has("secrets"),n.liveContext=n.liveContext||a.has("live")}for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=Dp(o,a)??Lp(o,a);c!==void 0&&(n[c]=!0)}if(Object.values(n).every(Boolean))break}if(!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s);n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>wi(i,o))}return n},_p="createWorker",Kp="extend",ln=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,dn=e=>{const t=[],s=ln(R(e,"backupCron"));s!==void 0&&t.push(s);const n=R(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=ln(i.getNameNode());o!==void 0&&t.push(o)}return t},zp=e=>{const t=N(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===_p)return r.isObjectLiteralExpression(s)?dn(s):[];if(t!==Kp||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Sn(s.getBody());return n===void 0?[]:dn(n)},Bp=(e,t)=>{const s=[];for(const{filePath:n}of je(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression))s.push(...zp(o))}return[...new Set(s)]},Ii=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Ii(e.inner)},$p=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Ii(n);return i!==void 0&&t.has(i)}))},Vp=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new j("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new j("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Up=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Rl(s,t),a=Ap(s,t),c=Gr(s,t),{queues:l,topics:u}=ao(s,t),f=lo(n),g=eo(s,t);Vp(c,g);const p=to(s,t),E=uo(s,t),V=so(s,t,c,g),ce=Bp(s,t),P=Mp(s,t,oo(n)),K=co(s,t),$=io(s,t);$.browser=$.browser||K.usesSandboxBrowser;const F=bt(n,e.target),k=fo($,F,{agents:g.length>0,commitOrderedTables:i.tables.some(L=>L.commitOrdered===!0),cronTriggers:V.length>0,crossShardFanout:i.tables.some(L=>Eo(L)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:p.some(L=>L.schedulingPolicy==="durable_object"),containerSandboxTools:p.some(L=>L.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(L=>L.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:$p(i),secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:K.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(L=>L.schedules!==void 0)}),T=k.usage,Q=Zr(T),X=k.signals.vectorStore!==!1,te=k.signals.services===!1?[]:f,J=Ln(n),le=J??new Set,z=le.has("lunorash");mp(i,J,{hasVectors:X,scheduler:T.scheduler||V.length>0,storage:T.storage||E.rules.length>0||Object.keys(Mn(i)).length>0,usage:T});const b=M(v(t,"flags.ts")),O=M(v(t,"notify.ts"));return{agents:g,capabilities:Q,containers:p,crons:V,dataModelContent:yo(i),declaredDependencies:J,dependencies:le,entryCronTriggers:ce,env:a,featureUsage:T,hasFlags:b,hasNotify:O,identity:o,platformGate:{...k,diagnostics:[...go(n,e.target),...k.diagnostics,...po(F,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[mo(F)]:[]]},queues:l,serverContent:So({agents:g,capabilities:Q,containers:p,env:a,hasVectors:X,hasFlags:b,hasNotify:O,identity:o,queues:l,schema:i,services:te,storageRuleBuckets:E.rules.map(L=>L.bucket),topics:u,useUmbrella:z,workflows:c}),services:te,storageRulesMetadata:E,topics:u,usesSandbox:K.usesSandboxBrowser||K.usesSandboxContainer||K.usesSandboxFs,useUmbrella:z,workflows:c}},Ci=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Wp=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},qp=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),jp=/^[\w$]+:[\w$]+$/u,Hp=(e,t)=>{const s=Nn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},un=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Gp=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return un(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===or.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?un(s):void 0}}},Yp=(e,t,s)=>({schedule:{argKeys:Gp(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Qp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(bn.has(s))return Hp(s,n);if((s==="runAfter"||s==="runAt")&&Wp(t)){const l=Nn(i)??(r.isStringLiteral(i)&&jp.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Yp(s,n,o)}}const a=qp.get(s),c=a===void 0?void 0:Ci(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Xp=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Ti=e=>rr.isOptionalChain(e.compilerNode),Jp=(e,t)=>r.isIfStatement(t)?!A(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?A(e,t.getStatement()):r.isForStatement(t)?A(e,t.getStatement())||A(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ie(t)?t.getFirstAncestor(ie)!==void 0:r.isConditionalExpression(t)?!A(e,t.getCondition()):r.isBinaryExpression(t)?!A(e,t.getLeft())&&Xp.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Ti(t)?!A(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&ug(s)),Zp=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&A(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ie);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&A(o.getFirstAncestor(ie),i))===!0},em=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&A(e,t.getStatement())||r.isForStatement(t)&&(A(e,t.getStatement())||A(t.getIncrementor(),e)),tm=(e,t)=>{if(Ti(e)||t==="schedule"&&Zp(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Jp(s,i)){if(!em(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},fn=(e,t,s)=>{if(s===void 0)return;const n=tm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:x(e)}},sm=(e,t)=>[...C(e,t,(s,n)=>fn(s,n,Qp(s))),...se(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Ci(s,"services");return fn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],nm=new Set(["boolean","number","object","string"]),im=e=>{const t=e.getName();if(!nm.has(t))return;const s=e.getExpression();return H(s,["flags"])||H(s,["flags","details"])?t:void 0},rm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=im(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},om=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=rm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},am=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||bo(o))return;const a=e.getSourceFile().getFilePath();if(No(i,e,a)){const c=Po(i,e,a,0,new Set);return c===void 0&&wo(o),c}return o},cm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Nr(t.getNameNode());return s===void 0||s==="namespace"}),lm=(e,t)=>{for(const{filePath:s}of je(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||cm(a)))return i}}},dm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",um=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Ne(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 (${dm}). 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})},fm=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,gm=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?fm(e):!0,Oi=(e,t=!1)=>{for(const s of e.getProperties()){if(gm(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Oi(n,!0))return!0}return!1},pm=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of _n(n))for(const o of Vt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Oi(a)))return!0}}return!1},mm=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=ze(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=ze(a);c!==void 0&&s.push({column:c,strategy:Rn(a),table:i})}}return s},hm=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of _n(i))for(const a of Vt(o))for(const c of mm(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},vm=["providerSubscriptionId","state"],Em=["providerEventId","processedAt"],gn=(e,t)=>t.every(s=>s in e.shape),xm=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&&gn(t,vm)&&gn(s,Em)},Sm=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Am=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},ym=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},bm="@lunora/privacy",ki="userId",Nm=e=>e.replaceAll("\\","/"),Pm="privacy",wm=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),Ze=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,et=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Jt=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Im=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},tt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Cm=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Im(s,"tables"),i=Ze(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Jt(n).map(a=>et(a)))t.datasets.set(o,i)},Tm=(e,t)=>{const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)?Jt(s):[],i=new Set(n.map(o=>et(o)));for(const o of Sm)i.has(o)||t.datasets.set(o,"authDataset");for(const o of n){const a=r.isPropertyAssignment(o)?Ze(o.getInitializer()):void 0;a!==void 0&&t.datasets.set(a,"authDataset")}},pn=(e,t,s)=>{t.datasets.set(Ze(e.getArguments()[0])??s,s)},Zt=8,be=(e,t=0)=>{if(t>Zt)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return be(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:be(i,t+1)},Om=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[et(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Ri=(e,t=0)=>{const s=be(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Zt)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Ri(i.getExpression(),t+1):[Om(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},km=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Ri(t)},Rm=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:be(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Jt(n):[])t.excluded.set(et(i),r.isPropertyAssignment(i)?Ze(i.getInitializer())??"":"")},Fm=(e,t)=>{switch(tt(e)){case"actionCacheDataset":{pn(e,t,"actionCache");break}case"authDataset":{Tm(e,t);break}case"defineDataset":{Cm(e,t);break}case"documentHistoryDataset":{pn(e,t,"documentHistory");break}}},es=e=>e!==void 0&&r.isCallExpression(e)&&tt(e)==="defineDataset",Fi=e=>e!==void 0&&r.isCallExpression(e)&&wm.has(tt(e)??""),Dm=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(es(i)||Fi(i))?n:void 0},Di=(e,t,s=0)=>{const n=be(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Zt)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Di(i.getExpression(),t,s+1))return!1}else if(!es(i)&&!Fi(i)){const o=r.isIdentifier(i)?Dm(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Lm=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Di(t,s)?s:void 0},Mm=(e,t)=>{const s=[];for(const i of e.getDescendantsOfKind(d.CallExpression))if(Fm(i,t),tt(i)==="definePrivacy"){const o=km(i);Rm(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Lm(o)})}return{declared:e.getDescendantsOfKind(d.VariableDeclaration).filter(i=>es(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},_m=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),...M(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Nm(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Km=(e,t,s)=>{if(s?.has(bm)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[]};const n={datasets:new Map,excluded:new Map},i=[],o=[];for(const f of _m(e,t)){const g=Mm(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:Am(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l}},zm=e=>e.extensionKey!==Pm&&ki in e.shape,Bm=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (it has a "${ki}" column) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,$m=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>zm(o)).map(o=>o.name),[n]=ym(s,t.classifications);if(n!==void 0)throw new j("PRIVACY_COVERAGE",Bm(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new j("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Vm=(e,t)=>{const s=ho(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Um=new Set(["delete","hardDelete","patch","replace","restore"]),Wm=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),qm=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),mn=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},jm=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:mn(i,e)}return mn(s,e)},hn="",Hm=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},Gm=(e,t)=>{if(Wm.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():hn]};if(Um.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:jm(t,e);return{method:e,tables:s.length===0?[hn]:s}}},vn=(e,t)=>e===void 0?void 0:{...e,fields:Hm(t,e.method)},Ym=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(_(n))return vn(Gm(s,e.getArguments()[0]),e);if(qm.has(s)&&r.isPropertyAccessExpression(n)&&_(n.getExpression()))return vn({method:s,tables:[n.getName()]},e)},Qm=(e,t)=>C(e,t,(s,n)=>{const i=Ym(s);if(i===void 0)return;const o=x(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Xm=(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"}),Jm=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||B(s,"args")===void 0)return!1}return qt(e,t).opaque},Zm=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ee(a);c!==void 0&&Jm(a,c.receiver)&&s.push(Xm(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},eh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...Zm(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},th=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."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["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"}]]),qe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Li=e=>!e.isAny(),Mi=e=>{const t=e.getType();if(!Li(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:th.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},sh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},_i={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."},nh=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.`}),ih={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)."},rh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),oh={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)."},ah=(e,t,s)=>{if(!t.some(i=>hr(i)))return ih;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return rh.has(s.typeName)&&!n&&!t.some(i=>_o(i))?oh:_i},Ki=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:nh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},ch=(e,t,s)=>{const n=[];for(const i of Y(e)){const o=r.isIdentifier(i.getNameNode())?yt(i):[i.getName()],c=o.some(u=>qe(s,t,u))||!sh(i)?void 0:Mi(i),[l=i.getName()]=o;c!==void 0&&n.push(Ki(t,l,c,i.getStartLineNumber(),ah(i,o,c)))}return n},lh=(e,t,s)=>{if(qe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=Mi(i.getExpression());o!==void 0&&n.push(Ki(t,"default",o,i.getStartLineNumber(),_i))}return n},dh=(e,t,s)=>[...ch(e,t,s),...lh(e,t,s)],uh=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>yt(n).some(i=>qe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=yt(n).find(o=>qe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),fh=({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"}),gh=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...dh(c,l,s)),i.push(...uh(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Li(a.getType()))&&n.push(fh(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},ph=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},mh=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},hh=(e,t)=>C(e,t,(s,n)=>ph(s)?{file:n,line:s.getStartLineNumber(),scope:x(s),workflow:mh(s)}:void 0),Pe=(e,t)=>{M(e)&&er(e,"utf8")===t||tr(e,t,"utf8")},vh=(e,t)=>{if(t===""){Se(e,{force:!0});return}Pe(e,t)},Eh=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){Se(s,{force:!0,recursive:!0});return}if(M(s))for(const n of En(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[xn(e,i)]===void 0&&Se(i)}for(const[n,i]of Object.entries(t))Mt(_t(v(e,n)),{recursive:!0}),Pe(v(e,n),i)},xh=(e,t,s)=>{const n=v(e,t);if(Object.keys(s).length===0){Se(n,{force:!0,recursive:!0});return}if(M(n))for(const i of En(n,{recursive:!0,withFileTypes:!0})){const o=v(i.parentPath,i.name);i.isFile()&&s[xn(n,o)]===void 0&&Se(o)}for(const[i,o]of Object.entries(s)){const a=v(n,i);Mt(_t(a),{recursive:!0}),Pe(a,o)}},Sh=e=>{try{const t=zo(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ke=(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)},Ah=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,yh=(e,t)=>{M(e)||Mt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Pe(v(e,n.name),n.content),s.push(n.name);break}case"directory":{xh(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{Eh(e,n.files),s.push(...Object.keys(n.files));break}default:vh(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},bh=e=>{const t=Sh(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=$o({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Uo({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
|
|
9
|
+
`,openApiModuleContent:Vo(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
|
|
10
|
+
`,openRpcModuleContent:Wo(i)}},Nh=".lunora-schema.json",Ph=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},wh=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new j("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new j("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 j("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})}},Ih=8,Ch=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:p,workflows:E}=e,V=()=>Co(()=>{const F=To(l,a,{lazyFunctions:o}),k=Dr(l,a);return{functions:F,httpRoutes:Oo(l,a),mutators:k}});let{erased:ce,value:{functions:P,httpRoutes:K,mutators:$}}=V();an([...P,...$].map(F=>F.filePath)),an(K.filter(F=>F.stream).map(F=>F.filePath),"http-stream");for(let F=1;;F+=1){const k=u?P:P.filter(b=>b.channel?.kind!=="room"),T=Jo({agents:t,functions:k,httpRoutes:K,mutators:$,useUmbrella:p,workflows:E}),Q={agents:t,functions:k,lazyFunctions:o,migrations:c,mutators:$,shapes:f,useUmbrella:p,usesSandbox:g},X=aa(Q),te=ca(Q),J=Zo({functions:P,useUmbrella:p}),le=v(a,"_generated",Kn),z=[[s,T],[i,J],[n,X],...Object.entries(te).map(([b,O])=>[v(le,b),O])];if(F>=Ih||z.every(([b,O])=>Ah(l,b,O)))return{apiContent:T,erased:ce,functions:P,functionModulesContent:te,functionsContent:X,httpRoutes:K,internalContent:J,mutators:$};for(const[b,O]of z)Ke(l,b,O);({erased:ce,value:{functions:P,httpRoutes:K,mutators:$}}=V())}},qv=e=>{const t=Ph(),s=t?ut.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=v(n,"schema.ts");if(!M(o))throw new j("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??Xr(n);Ir(am);const c=Lo(a,o,e.projectRoot);$m(c.tables,Km(a,n,Ln(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:p,dependencies:E,entryCronTriggers:V,env:ce,featureUsage:P,hasFlags:K,hasNotify:$,identity:F,platformGate:k,queues:T,serverContent:Q,services:X,storageRulesMetadata:te,topics:J,usesSandbox:le,useUmbrella:z,workflows:b}=Up({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});um(c,c.jurisdiction===void 0?void 0:lm(a,n));const O=v(n,"_generated"),L=v(O,"dataModel.ts"),zi=v(O,"server.ts"),Bi=v(O,"api.ts"),$i=v(O,"internal.ts"),Vi=v(O,"functions.ts");Ke(a,L,p),Ke(a,zi,Q);const ts=Object.fromEntries(X.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(Ao(m,O))));for(const[m,dt]of Object.entries(ts))Ke(a,v(O,m),dt);const we=Ro(a,n),de=Mo(a,n),ss=k.signals.typedWebSockets!==!1,{apiContent:ns,erased:Ui,functions:re,functionModulesContent:is,functionsContent:rs,httpRoutes:st,internalContent:os,mutators:nt}=Ch({agents:l,apiPath:Bi,generatedFunctionsPath:Vi,internalPath:$i,lazyFunctions:i,roomsSupported:ss,lunoraDirectory:n,migrations:we,project:a,shapes:de,useUmbrella:z,usesSandbox:le,workflows:b}),as=qr(a,n),it=jr(as,c,[...re,...st].map(m=>m.filePath)),Ie=as.length>0,Ce=e.lint===!1&&!Ie?void 0:{callEdges:sm(a,n),inserts:ko(a,n),queries:Fo(a,n,re),tableWrites:Qm(a,n),workflowCalls:hh(a,n)},Te=e.lint===!1||Ce===void 0?void 0:Wg(a,n,{callSites:Ce,containers:f,crons:g,functions:re,modules:it,mutators:nt,queues:T,schema:c,shapes:de,workflows:b,wranglerVariables:e.wranglerVariables}),cs=Te===void 0?[]:Xg(e.projectRoot,[...sr(Te,{source:"static"}),...gh(a,n,{byName:new Set([...b,...T,...l,...f].map(m=>m.exportName)),byPath:new Set([...re,...nt,...de,...we].map(m=>`${m.filePath}:${m.exportName}`))}),...eh(a,n),...Io(Ui,n),...qo(T,e.wranglerQueueProducers)]),Wi=Do(a,n),ls=hm(a,n);wh(de,ls,pm(a,n));const qi=K?om(a,n):[],rt=k.signals.vectorStore!==!1,ji=vo(bt(e.projectRoot,e.target),"deliveryAuthorization"),ge=Vm(P,{containerCount:f.length,cronCount:g.length,dependencies:E,hasPaymentTables:xm(c.tables),queueCount:T.length,storageColumnCount:Object.keys(Mn(c)).length,storageRuleCount:te.rules.length,vectorIndexCount:c.vectorIndexes.length,target:bt(e.projectRoot,e.target),vectorStoreSupported:rt,workflowCount:b.length}),ds=t?ut.now():0,ot=Bo(c,we.map(m=>m.id)),us=xo({advisories:cs.filter(m=>m.name!=="procedure_type_check_unavailable"),advisorProcedures:Te?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:ce,flagKeys:qi,hasFlags:K,hasNotify:$,hasRooms:ss&&re.some(m=>m.channel?.kind==="room"),lazyFunctions:i,hasVectors:rt,liveStreams:k.signals.liveStreams===!0,maskMetadata:ls,mutators:nt,queues:T,rlsMetadata:Wi,schema:c,schemaSnapshot:ot,shapes:de,services:X,storageRules:te,studioFeatures:ge,topics:J,useUmbrella:z,workflows:b}),fs=Qo(de,E.has("@lunora/db"),z),gs=jo(f,c.jurisdiction),ps=Ho(b),ms=Go(l),hs=Yo(T,e.wranglerQueueProducers),vs=ea(g),Hi=ta(ge.scheduler),Gi=sa(c.tables,z),Yi=Pr(e.projectRoot)?na(z):"",Es=ia(c.vectorIndexes),Oe=oa(c,z),xs=Xo(E.has("@lunora/seed")),ke=e.apiSpec??"openapi",at=ke==="openapi"||ke==="both",ct=ke==="openrpc"||ke==="both",Ss=Ko({capabilities:u,emailAgents:l.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:E.has("@lunora/cloudflare-access"),hasAuth:E.has("@lunora/auth"),hasFramework:E.has("@lunora/astro")||E.has("@lunora/svelte")||E.has("@lunora/vue")||M(v(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(m=>Fn(m)),hasHyperdriveGlobal:c.tables.some(m=>Dn(m)),hasKvIntrospector:ge.kv,hasNotify:$,hasQueue:T.some(m=>m.mode==="push"),liveStreams:k.signals.liveStreams===!0,liveStreamsWithheld:k.liveStreamsWithheld,hasScheduler:ge.scheduler,hasSourcedTables:c.tables.some(m=>m.externalSource!==void 0),hasStorage:ge.storage,hasDeliveryAuthorization:ji,hasVectors:rt,hasWorkflow:b.length>0,identity:F,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(m=>({name:m.name,shardMode:m.shardMode})),useUmbrella:z,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:Ie,wantsOpenApi:at,wantsOpenRpc:ct}),{openApiContent:As,openApiModuleContent:ys,openRpcContent:bs,openRpcModuleContent:Ns}=bh({functions:re,httpRoutes:st,modules:it,projectRoot:e.projectRoot,wantsArchitecture:Ie}),pe=Ie&&Ce!==void 0?fp({...Ce,crons:g,functions:re,httpRoutes:st,modules:it,queues:T,schema:c,services:X,topics:J,workflows:b}):void 0,lt=v(n,Nh),Qi=M(lt),Xi=e.dryRun?[]:yh(O,[{content:Ss,kind:"always",name:"app.ts"},{content:p,kind:"always",name:"dataModel.ts"},{content:ns,kind:"always",name:"api.ts"},{content:os,kind:"always",name:"internal.ts"},{content:Q,kind:"always",name:"server.ts"},{content:rs,kind:"always",name:"functions.ts"},{files:is,kind:"directory",name:Kn},{content:us,kind:"always",name:"shard.ts"},{content:vs,kind:"always",name:"crons.ts"},{content:Es,kind:"always",name:"vectors.ts"},{content:Oe.global,kind:"always",name:"drizzle.global.ts"},{content:Oe.shard,kind:"always",name:"drizzle.shard.ts"},{content:gs,kind:"optional",name:"containers.ts"},{content:ps,kind:"optional",name:"workflows.ts"},{content:ms,kind:"optional",name:"agents.ts"},{content:hs,kind:"optional",name:"queues.ts"},{content:Hi,kind:"optional",name:"scheduler.ts"},{content:Gi,kind:"optional",name:"shardRegistry.ts"},{content:Yi,kind:"optional",name:"durableObjects.ts"},{content:xs,kind:"optional",name:"seed.ts"},{content:fs,kind:"optional",name:"collections.ts"},{files:ts,kind:"services"},{content:at?As:"",kind:"optional",name:"openapi.json"},{content:at?ys:"",kind:"optional",name:"openapi.ts"},{content:ct?bs:"",kind:"optional",name:"openrpc.json"},{content:ct?Ns:"",kind:"optional",name:"openrpc.ts"},{content:pe===void 0?"":`${JSON.stringify(pe,void 0,2)}
|
|
11
|
+
`,kind:"optional",name:"architecture.json"},{content:pe===void 0?"":gp(pe),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!Qi||e.updateSchemaBaseline===!0)&&Pe(lt,nr(ot)),t){const m=ut.now(),dt=Math.round(m-s),Ji=Math.round(ds-s),Zi=Math.round(m-ds);console.error(`@lunora/codegen: codegen took ${dt.toString()}ms (discovery ${Ji.toString()}ms, emit ${Zi.toString()}ms)`)}return{advisories:cs,advisorContext:Te,agents:l,architecture:pe,containers:f,cronTriggers:[...new Set([...ra(g),...V])],generated:{agents:ms,api:ns,app:Ss,collections:fs,containers:gs,crons:vs,dataModel:p,drizzleGlobal:Oe.global,drizzleShard:Oe.shard,functionModules:is,functions:rs,internal:os,openApi:As,openApiModule:ys,openRpc:bs,openRpcModule:Ns,queues:hs,seed:xs,server:Q,shard:us,vectors:Es,workflows:ps},migrations:we,outputDirectory:O,platformDiagnostics:k.diagnostics,queues:T,schemaSnapshot:ot,schemaSnapshotPath:lt,workflows:b,writtenFiles:Xi}};export{Nh as SCHEMA_SNAPSHOT_FILENAME,Xr as createCodegenProject,Gv as findTsconfig,Yv as refreshCodegenProject,qv as runCodegen};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as d,Node as c}from"ts-morph";import{CAPABILITIES as p}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{bindingKeyName as g,listLunoraSourceFiles as x}from"./isTestPath-B81lOULB.mjs";import{scanImportDeclaration as E,noSandboxUsage as u}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";const f="ctx",N=(e,t,n)=>{for(const s of e.getDescendantsOfKind(d.ElementAccessExpression)){const o=s.getArgumentExpression();t(s.getExpression())&&o!==void 0&&(c.isStringLiteral(o)||c.isNoSubstitutionTemplateLiteral(o))&&n.add(o.getLiteralValue())}},I=e=>{const t=new Set,n=new Set,s=new Set(e.getDescendantsOfKind(d.Parameter).map(a=>a.getName())),o=e.getDescendantsOfKind(d.VariableDeclaration).some(a=>{const r=a.getInitializer();return a.getName()===f&&c.isIdentifier(r)&&s.has(r.getText())});(s.has(f)||o)&&n.add(f);const m=a=>{if(c.isObjectBindingPattern(a))for(const r of a.getElements()){const l=g(r);l&&t.add(l)}};for(const a of e.getDescendantsOfKind(d.BindingElement)){if(g(a)!==f)continue;const r=a.getNameNode();c.isIdentifier(r)?n.add(r.getText()):m(r)}const i=a=>c.isIdentifier(a)&&n.has(a.getText());for(const a of e.getDescendantsOfKind(d.PropertyAccessExpression))i(a.getExpression())&&t.add(a.getName());N(e,i,t);for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const r=a.getInitializer();r!==void 0&&i(r)&&m(a.getNameNode())}return t},y=e=>{if(e.isTypeOnly())return!0;if(c.isExportDeclaration(e)){const n=e.getNamedExports();return!e.isNamespaceExport()&&n.length>0&&n.every(s=>s.isTypeOnly())}const t=e.getNamedImports();return e.getDefaultImport()===void 0&&e.getNamespaceImport()===void 0&&t.length>0&&t.every(n=>n.isTypeOnly())},S=new Map(p.flatMap(({bindingFreeExports:e,moduleSpecifier:t})=>e===void 0?[]:[[t,new Set(e)]])),T=(e,t)=>{const n=S.get(t);if(n===void 0||c.isImportDeclaration(e)&&(e.getDefaultImport()!==void 0||e.getNamespaceImport()!==void 0))return!1;const s=c.isExportDeclaration(e)?e.getNamedExports():e.getNamedImports();return s.length>0&&s.every(o=>o.isTypeOnly()||n.has(o.getName()))},O=e=>{const t=new Set;for(const n of e.getDescendantsOfKind(d.CallExpression)){const[s]=n.getArguments();n.getExpression().getKind()===d.ImportKeyword&&(c.isStringLiteral(s)||c.isNoSubstitutionTemplateLiteral(s))&&t.add(s.getLiteralValue())}return t},b=e=>{const t=e.getImportDeclarations(),n=u();for(const s of t){const o=E(s);for(const m of Object.keys(n))n[m]||=o[m]}return{contextReads:I(e),dynamicImports:O(e),sandboxTools:n,valueImports:new Set([...t,...e.getExportDeclarations()].flatMap(s=>{const o=s.getModuleSpecifierValue();return o===void 0||y(s)||T(s,o)?[]:[o]}))}},v=e=>{const t=new Set,n=new Set,s=u(),o=new Set;for(const m of e){for(const i of m.contextReads)t.add(i);for(const i of m.dynamicImports)n.add(i);for(const i of m.valueImports)o.add(i);for(const i of Object.keys(s))s[i]||=m.sandboxTools[i]}return{contextReads:t,dynamicImports:n,sandboxTools:s,valueImports:o}},w=e=>new Set(p.filter(({contextProperty:t,moduleSpecifier:n})=>e.valueImports.has(n)||t!==void 0&&e.contextReads.has(t)).map(({key:t})=>t)),D=new RegExp(String.raw`\b${f}\b`,"u"),R=new RegExp(String.raw`\b(?:${p.flatMap(({contextProperty:e})=>e===void 0?[]:[e]).join("|")})\b`,"u"),C=e=>D.test(e)&&R.test(e),L=(e,t)=>{const n=v(x(t).map(o=>b(e.getSourceFile(o)??e.addSourceFileAtPath(o)))),s=w(n);return Object.fromEntries(p.map(({key:o})=>[o,s.has(o)]))};export{w as capabilitiesUsedBy,I as contextPropertiesRead,L as discoverFeatureUsage,v as foldCapabilitySignals,C as mayReadCapabilityContext,b as sourceCapabilitySignals};
|
|
@@ -336,7 +336,7 @@ const buildGlobalCdcApplier =
|
|
|
336
336
|
|
|
337
337
|
return request.changes.length;
|
|
338
338
|
};
|
|
339
|
-
`:"",C=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],O=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"
|
|
339
|
+
`:"",C=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],O=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...g(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],T=e=>m(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
|
|
340
340
|
public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
|
|
341
341
|
this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
|
|
342
342
|
|
|
@@ -360,12 +360,12 @@ const buildGlobalCdcApplier =
|
|
|
360
360
|
this.maxRelationKeysLimit = limit;
|
|
361
361
|
|
|
362
362
|
return this;
|
|
363
|
-
}`," /**\n * Route the shard's `ctx.log` lines, `ctx.trace` spans and `ctx.metrics` measurements to a telemetry sink.\n *\n * The DO half of observability: without it every in-handler signal stays in the shard's local ring buffer (the studio Logs panel) and reaches no collector. The worker half — one `onRpc` event per dispatched RPC — is a `createWorker` option; pass the SAME sink to both via `.extend((env) => ({ observability: sink(env) }))` to correlate them.\n */\n public observability(selector: NonNullable<ShardConfig[\"observability\"]>): this {\n this.observabilitySink = selector;\n\n return this;\n }",' /** Resolution policy for a relation-crossing `where` whose child is co-located in this shard: `"auto"` (cost-based, the engine default), `"always"` (inline correlated EXISTS) or `"never"` (universal semijoin). All three return identical rows. */\n public relationExistsPushDown(mode: NonNullable<ShardConfig["relationExistsPushDown"]>): this {\n this.relationExistsPushDownMode = mode;\n\n return this;\n }'
|
|
363
|
+
}`," /**\n * Route the shard's `ctx.log` lines, `ctx.trace` spans and `ctx.metrics` measurements to a telemetry sink.\n *\n * The DO half of observability: without it every in-handler signal stays in the shard's local ring buffer (the studio Logs panel) and reaches no collector. The worker half — one `onRpc` event per dispatched RPC — is a `createWorker` option; pass the SAME sink to both via `.extend((env) => ({ observability: sink(env) }))` to correlate them.\n */\n public observability(selector: NonNullable<ShardConfig[\"observability\"]>): this {\n this.observabilitySink = selector;\n\n return this;\n }",' /** Resolution policy for a relation-crossing `where` whose child is co-located in this shard: `"auto"` (cost-based, the engine default), `"always"` (inline correlated EXISTS) or `"never"` (universal semijoin). All three return identical rows. */\n public relationExistsPushDown(mode: NonNullable<ShardConfig["relationExistsPushDown"]>): this {\n this.relationExistsPushDownMode = mode;\n\n return this;\n }',...e.hasDeliveryAuthorization===!1?[]:[` /** Authorize each RPC/subscription read and fence its eventual delivery against durable authority epochs. */
|
|
364
364
|
public deliveryAuthorization(selector: (env: Env) => ReturnType<NonNullable<ShardConfig["deliveryAuthorization"]>>): this {
|
|
365
365
|
this.deliveryAuthorizationSelector = selector as NonNullable<ShardConfig["deliveryAuthorization"]>;
|
|
366
366
|
|
|
367
367
|
return this;
|
|
368
|
-
}
|
|
368
|
+
}`],...e.hasAuth?[' /** Wire better-auth — the builder lazily builds the instance, runs `ensureMigrated`, and dispatches `/api/auth/*` inside the worker (instrumented for the auth-failure SLO). Pass `d1` for the D1-backed default, or `namespace` + `internalSecret` to host the auth tables in a Durable Object (what `@better-auth/scim` needs). */\n public auth(declaration: AuthDeclaration<Env>): this {\n // Reject the ambiguous and the empty shapes here rather than at the first\n // request: with neither storage set, auth would silently never answer, and\n // with both it is unclear which one owns the tables.\n if (declaration.d1 && declaration.namespace) {\n throw new Error(".auth(): pass either `d1` or `namespace`, not both — they are two different homes for the same tables.");\n }\n\n if (!declaration.d1 && !declaration.namespace) {\n throw new Error(".auth(): needs `d1` (D1-backed) or `namespace` (Durable-Object-backed) to know where the auth tables live.");\n }\n\n if (declaration.namespace && !declaration.internalSecret) {\n throw new Error(\n ".auth(): `namespace` requires `internalSecret` — the auth DO binding is reachable from any worker bound to it, so identity resolution is gated on a shared secret and would otherwise fail closed on every request.",\n );\n }\n\n this.authDeclaration = declaration;\n\n return this;\n }']:[]," /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */\n public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {\n this.extendFns.push(fn);\n\n return this;\n }",...e.hasGlobal?[` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
|
|
369
369
|
public global(declaration: GlobalDeclaration<Env>): this {
|
|
370
370
|
this.globalDeclaration = declaration;
|
|
371
371
|
|
|
@@ -406,7 +406,7 @@ const buildGlobalCdcApplier =
|
|
|
406
406
|
|
|
407
407
|
return this;
|
|
408
408
|
}`]:[],...T(e)],q=e=>{const r=a=>e.hasScheduler?`
|
|
409
|
-
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),"
|
|
409
|
+
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
410
410
|
? {
|
|
411
411
|
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
|
|
412
412
|
const env = rawEnv as Env;
|
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.324",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -50,15 +50,15 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
54
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
55
|
-
"@lunora/container": "1.0.0-alpha.
|
|
53
|
+
"@lunora/advisor": "1.0.0-alpha.232",
|
|
54
|
+
"@lunora/agent": "1.0.0-alpha.224",
|
|
55
|
+
"@lunora/container": "1.0.0-alpha.81",
|
|
56
56
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
57
57
|
"@lunora/platform": "1.0.0-alpha.68",
|
|
58
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
59
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
60
|
-
"@lunora/values": "1.0.0-alpha.
|
|
61
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
58
|
+
"@lunora/queue": "1.0.0-alpha.114",
|
|
59
|
+
"@lunora/scheduler": "1.0.0-alpha.136",
|
|
60
|
+
"@lunora/values": "1.0.0-alpha.71",
|
|
61
|
+
"@lunora/workflow": "1.0.0-alpha.83",
|
|
62
62
|
"@visulima/fs": "6.0.29",
|
|
63
63
|
"jiti": "^2.7.0",
|
|
64
64
|
"quicktype-core": "^26.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{NODE_CAPABILITIES as h,CLOUDFLARE_CAPABILITIES as b,CELLD_CAPABILITIES as S}from"@lunora/platform";import{r as g}from"./project-config-file-BV7RR-l6.mjs";const u="cloudflare",y=t=>{const{target:e}=g(t);return e!==void 0&&e.length>0?e:void 0},R=(t,e)=>e??y(t)??u,E=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=g(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${u}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${u}" }\`), or pass \`--target\`.`,target:u}]},w={max:1536,min:32},O=(t,e)=>{if(t!=="cloudflare")return[];const{max:a,min:r}=w,n=`${String(r)}-${String(a)}`;return e.filter(({dimensions:o})=>o!==void 0&&(!Number.isInteger(o)||o<r||o>a)).map(({dimensions:o,name:s})=>({level:"warn",message:`Vector index "${s}" declares ${String(o)} dimensions; Cloudflare Vectorize accepts ${n}, so creating a Vectorize index for it fails at deploy.`,name:"platform_vector_dimensions_out_of_range",remediation:`If a Vectorize index backs "${s}", use ${n} dimensions (many embedding models can truncate output to fit). Ignore this if another store, such as pgvector, backs it.`,target:t}))},m={celld:S,cloudflare:b,node:h},P=()=>Object.keys(m).toSorted((t,e)=>t.localeCompare(e)),_={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},k=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","durableStreams","globalTables","liveStreams","queues","relationGraph","secrets","services","topics","typedWebSockets","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],v={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",liveContext:"the live publisher (`ctx.live`)",liveStreams:"live topic streams (`defineLiveStream`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",typedWebSockets:"typed WebSocket routes and rooms (`defineWebSocket` / `defineRoom`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},x=(t,e,a)=>({level:"error",message:`${e.name} does not support ${v[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),$=(t,e)=>({level:"error",message:`${t.name} withholds live streams, so ctx.live is not available on the "${e}" target, but this app reads ctx.live.`,name:"platform_unsupported_feature",remediation:'Remove the ctx.live usage, or deploy to a target whose capability matrix marks "liveStreams" as native or emulated.',target:e}),D=t=>({level:"error",message:"This app declares defineLiveStream topics and enables delivery authorization. With delivery authorization on, the shard answers every /_lunora/live/* request with 501, so the live streams cannot be served.",name:"platform_live_stream_delivery_authorization",remediation:"Remove the defineLiveStream declarations, or remove the .deliveryAuthorization(...) call. Live streams and delivery authorization cannot be combined.",target:t}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${v[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),L=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:o,target:s}=t;for(const i of k){if(o[i]!==!0)continue;const c=r.features[i]?.level;c!=="unsupported"&&c!==void 0||(a[i]=!1,!n.has(i)&&e.push(c==="unsupported"?x(i,r,s):T(i,r,s)))}},A=(t,e,a,r={})=>{const n={...t},o={...r},s=[],i=new Set;for(const[l,d]of Object.entries(_)){if(d===null||!t[l])continue;const f=e.features[d]?.level;f==="unsupported"?(n[l]=!1,i.add(d),s.push({feature:l,level:"error",message:`${e.name} does not support "${l}" (ctx.${l}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${l} usage, or deploy to a target whose capability matrix marks "${d}" as native or emulated.`,target:a})):f===void 0&&(n[l]=!1,i.add(d),s.push({feature:l,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${l}" (ctx.${l}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${d}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}L({diagnostics:s,gatedSignals:o,matrix:e,reported:i,signals:r,target:a});const c=e.features.liveStreams?.level,p=c===void 0||c==="unsupported";return r.liveContext===!0&&p&&s.push($(e,a)),{diagnostics:s,liveStreamsWithheld:p,signals:o,usage:n}},W=(t,e,a={})=>{const r=m[e];return r===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(m).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],liveStreamsWithheld:!1,signals:{...a},usage:{...t}}:A(t,r,e,a)},z=t=>{const e=m[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{_ as CAPABILITY_TO_FEATURE,u as DEFAULT_TARGET,A as gateAgainstMatrix,W as gatePlatformFeatures,D as liveStreamsDeliveryAuthorizationDiagnostic,P as platformMatrixIds,y as readProjectTarget,E as readTargetDiagnostics,R as resolveCodegenTarget,z as studioPlatformFor,O as vectorizeDimensionDiagnostics};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{existsSync as M,mkdirSync as Ft,readFileSync as Gi,writeFileSync as Yi,rmSync as xe,readdirSync as pn}from"node:fs";import{dirname as Lt,join as v,relative as mn}from"node:path";import{performance as lt}from"node:perf_hooks";import{runAdvisor as Qi}from"@lunora/advisor";import{LunoraError as j}from"@lunora/errors";import{serializeSchemaSnapshot as Xi}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Ji}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as Zi,VariableDeclarationKind as er}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as w,bindingKeyName as oe,collectCallRows as I,findObjectProperty as z,collectSecurityCallRows as tr,propertyInitializer as R,listSecurityScanFiles as qe,objectLiteralFromCallbackBody as hn,limitNameOf as vn,optionsObjectLiteral as En,handlerOf as sr,collectNodeRows as se,chainRootOf as Dt,outermostValueWrapper as P,isWriteTarget as je,isSameNode as S,unwrapExpression as h,isConstDeclaration as ne,memberAccessOf as xn,returningFunctionOf as xt,walkChain as nr,RUN_METHODS as Sn,functionReferenceSegments as ir,isTestPath as rr,isFunctionLike as ie,functionKeyOf as An}from"./isTestPath-B81lOULB.mjs";import{b as Y,d as q,f as L,g as Mt,c as x,a as yn,w as _t,k as or,l as ar,h as cr,m as lr,j as St,i as dr}from"./attribution-hVBriwzy.mjs";import{a as ys,r as dt,i as H,b as ur,m as bn,c as He,e as Kt,E as Nn,C as Pn,d as fr,f as gr,g as pr}from"./context-root-BdxINX-T.mjs";import{a as N,i as mr,c as ee,d as wn,e as hr,f as vr}from"./classify-procedure-call-DVxdUhZt.mjs";import{a as y,r as In,s as Er,b as xr}from"./project-config-file-BV7RR-l6.mjs";import{a as Sr,b as Ge}from"./module-specifiers-WF8iAydP.mjs";import{r as Ye,s as Ar}from"./parse-validator-IDBKIT7M.mjs";import yr from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as _,r as Cn}from"./database-calls-BKozZUEW.mjs";import br from"./discoverHyperdriveCalls-DV4IglLE.mjs";import{diagnosticAt as be}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Bt,a as Ke,s as Tn,d as Nr}from"./index-JnqBWRYO.mjs";import{MUTATORS_FILENAME as Pr,isDefineMutatorCallee as wr,mutatorServerImplOf as Ir,discoverMutators as Cr}from"./MUTATORS_FILENAME-Jkk8Zgkb.mjs";import Tr from"./discoverNondeterministicCalls-DvhyKM-f.mjs";import{discoverNotifyConfig as Or,discoverNotifyCalls as kr}from"./NOTIFY_FILENAME-bAt7J3cs.mjs";import Rr from"./discoverR2sqlCalls-DVcfMO6-.mjs";import Fr from"./discoverRlsProcedures-Du7ITNTQ.mjs";import{s as zt,n as Lr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Dr,redact as Mr,isHeuristicSecretKind as _r,isSecretishName as Kr}from"./redact-Cy14LEnc.mjs";import{a as ke,d as Br,r as zr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as $r,discoverWorkflows as Vr}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as Ur}from"./json-data-Chfs2Cz5.mjs";import{G as Wr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as qr}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as Rv,refreshCodegenProject as Fv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as jr,usedCapabilities as Hr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as On,isHyperdriveGlobalTable as kn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Gr}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as Yr}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import Qr from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as Xr,discoverFeatureUsage as Jr}from"./capabilitiesUsedBy-D3pvpeAt.mjs";import Rn from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Zr}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as eo}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as to}from"./readServiceBindings-DvqIThzd.mjs";import so from"./discoverStorageRulesMetadata-ClzKLdCV.mjs";import{resolveCodegenTarget as Fn,gatePlatformFeatures as no,readTargetDiagnostics as io,vectorizeDimensionDiagnostics as ro,liveStreamsDeliveryAuthorizationDiagnostic as oo,studioPlatformFor as ao}from"./DEFAULT_TARGET-DksDPUdg.mjs";import{i as co}from"./schema-BgM8A3XV.mjs";import{b as Ln,e as lo}from"./shard-ceGu_Fps.mjs";import{e as uo,a as fo}from"./server-DAvi_bv_.mjs";import{emitDataModel as go}from"./emitDataModel-BskFt9Wv.mjs";import{i as po,a as mo,e as ho,b as vo,d as Eo,c as xo}from"./unwrap-handler-return-CeaOifqX.mjs";import So from"./discoverFunctions-CZgLhsMn.mjs";import Ao from"./discoverHttpRoutes-WBAqBcfK.mjs";import yo from"./discoverInserts-BjxXCACZ.mjs";import{e as Dn}from"./exported-procedure-chains-BNBUkXui.mjs";import bo from"./discoverMigrations-C9mLIhGZ.mjs";import No from"./discoverQueries-C8E7TeRT.mjs";import Po from"./discoverRlsMetadata-QRsWRQbM.mjs";import wo from"./discoverSchema-BtsX-CN9.mjs";import{discoverShapes as Io}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as Co}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as To}from"./emitApp-DphNN43J.mjs";import{readJsonSync as Oo}from"@visulima/fs";import{buildSchemaSnapshot as ko}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as Ro,emitOpenApiModule as Fo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Lo,emitOpenRpcModule as Do}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as Mo,t as _o,u as Ko,s as Bo,w as zo}from"./shard-runtime-BpoCV-aM.mjs";import{emitCollections as $o,emitSeed as Vo,emitApi as Uo,emitInternalApi as Wo}from"./emitApi-CDgIPAG2.mjs";import{emitCrons as qo,emitScheduler as jo,emitShardRegistry as Ho,emitDurableObjects as Go,emitVectors as Yo,emitWranglerCronTriggers as Qo}from"./emitCrons-BQW2lviZ.mjs";import Xo from"./emitDrizzleSchema-DitcRZ1a.mjs";import{LAZY_FUNCTION_DIRECTORY as Mn,emitFunctions as Jo,emitLazyFunctionModules as Zo}from"./emitFunctions-CuZzKaU4.mjs";const _n=new Set(["delete","get","head","options","patch","post","put"]),ea=new Set(["handler","stream"]),ta=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,bs=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),sa=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!_n.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},na=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||_n.has(n.getName()))break;s=n.getExpression()}return sa(s)},ia=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(bs.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&bs.has(s.getText()))return!0}return!1},ra=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!ea.has(n.getName()))return;const i=na(s);if(!i||!ta.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&ia(o);return{exportName:q(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},oa=(e,t)=>{const s=[];for(const n of Y(e)){const i=ra(n,t);i&&s.push(i)}return s},aa=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...oa(i,w(t,n)))}return s},ca=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},la=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?oe(t):void 0}},da=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&ys(a)}))return!1;const n=L(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&ys(i)},Ns=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=ca(e);return n!==void 0&&la(n)===t?!0:t==="args"&&da(e)},Kn=(e,t)=>r.isIdentifier(e)?Ns(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Ns(s,t)),ua=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},Ps=e=>{const t=r.isIdentifier(e)?L(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Mt(t)?t.getInitializer():void 0},At=e=>Kn(e,"args"),G=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},W=e=>{if(At(e))return!0;const t=G(e);return t!==void 0&&At(t)},fa=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=G(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},ae=e=>{if(dt(e))return!0;const t=Ps(e);if(t!==void 0&&dt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=Ps(i);return o!==void 0&&dt(o)})},Re=(e,t)=>Kn(e,t),ga=(e,t)=>{if(Re(e,t))return!0;const s=G(e);if(s!==void 0&&Re(s,t))return!0;const n=ua(e);if(n!==void 0){const i=G(n);return i!==void 0&&Re(i,t)}return!1},pa=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:H(e.getExpression(),["ai"]),ma=(e,t)=>{if(!pa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)||ae(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},ha=(e,t)=>I(e,t,ma),va=new Set(["generateText","streamText"]),Ea=new Set(["messages","prompt","system"]),xa=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Sa=(e,t)=>xa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),Aa=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[ur(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Sa(i,s));return n===void 0?void 0:`${n}.${s}`},ya=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=Aa(t);if(s!==void 0)return s}},ba=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=oe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Na=e=>{if(At(e))return!0;const t=ba(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(!r.isPropertyAssignment(t)||!Ea.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&Na(s))return!0}return!1},wa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=N(n.getExpression());if(i===void 0||!va.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(N(c.getExpression())==="tool"&&(a=ya(c),a!==void 0))break;a!==void 0&&s.push({scope:x(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Pa(o)})}return s},Ia=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wa(i,w(t,n)))}return s},Ca=e=>H(e,["fetch"]),Ta=(e,t)=>{if(!Ca(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},Oa=(e,t)=>I(e,t,Ta),$t=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=Ye(s.getExpression());return n===void 0||$t(n,t)})}finally{t.delete(e)}},ka=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=z(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:Ye(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:$t(i)}},Ra=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?Ye(o):void 0;a===void 0?s=!0:(t.push(a),s||=$t(a))}n=i.getExpression()}return{objects:t,opaque:s}},Vt=(e,t)=>t?Ra(t):ka(e),Bn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=Ye(s.getExpression());return n===void 0?[]:Bn(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Fa=e=>e.flatMap(t=>Bn(t,new Set)),La=new Set(["check","length","max"]),yt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(La.has(s.getName()))return!0;t=n}},bt=e=>Sr(e)||e==="@lunora/values",Da=e=>{const t=new Set(["v"]);for(const s of mr(e,"v",bt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&bt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Ma=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},_a=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Ka=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&bt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Ut=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return _a(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Ka(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ba=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},za=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},$a=e=>r.isReturnStatement(e)?e.getExpression():void 0,Va=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>za(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=$a(t);return s?[s]:[]}),zn=(e,t)=>{if(Ut(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return zn(e.getExpression(),t)},Ua=(e,t)=>{const s=Ba(e.getExpression(),e.getSourceFile());if(!s)return[];const n=yt(e),i=new Set(Va(s).map(o=>zn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Ut(o,t);return a===void 0?[]:[{bounded:yt(o)||n&&i.has(o),factory:a}]})},Wa=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Ut(s,t),i=n===void 0?[]:[{bounded:yt(s),factory:n}];return r.isCallExpression(s)?[...i,...Ua(s,t)]:i}),qa=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Wa(a,t),l=y(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},ja=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ee(n);if(i?.visibility!=="public")return;const{objects:o}=Vt(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=qa(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:q(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Ha=(e,t)=>{const s=[],n=Da(e),i={destructured:Ma(e,n),namespaces:n};for(const o of Y(e)){const a=ja(o,t,i);a&&s.push(a)}return s},Ga=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ha(i,w(t,n)))}return s},ut=e=>e?.getKind()===d.TrueKeyword,Ya=e=>e?.getKind()===d.FalseKeyword,Qa=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Xa=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Ja=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&N(t.getExpression())==="scim"),Za=e=>e!==void 0&&r.isCallExpression(e)&&Xa.has(N(e.getExpression())??""),ec=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),tc=e=>{const t=R(e,"advanced"),s=R(e,"emailAndPassword"),n=R(e,"session");return{analyzable:!0,disableCsrfCheck:ut(R(t,"disableCSRFCheck")),emailPasswordEnabled:ut(R(s,"enabled")),requireEmailVerification:ut(R(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Ja(R(e,"plugins"))&&Za(R(e,"database")),secureCookiesDisabled:Ya(R(t,"useSecureCookies")),sessionFreshAgeZero:Qa(R(n,"freshAge")),trustedOriginsWildcard:ec(R(e,"trustedOrigins"))}},sc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),nc=(e,t)=>{if(N(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?tc(s):sc();return{scope:x(e),file:t,line:e.getStartLineNumber(),...i}},ic=(e,t)=>tr(e,t,nc),rc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return bn(e.getExpression(),t.matchReceiver)?s:void 0},oc=(e,t,s)=>{const n=rc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!W(i)||ae(i))&&!(s.requireUnmodifiedReach===!0&&!fa(i)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:n}},Qe=(e,t,s)=>I(e,t,(n,i)=>oc(n,i,s)),ac=new Set(["content","pdf","scrape","screenshot"]),cc=(e,t)=>Qe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ac}),lc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),dc=new Set(["RateLimiter"]),uc=new Set(["extend"]),ws="lunora",fc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],$n=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Nt=e=>e&&r.isObjectLiteralExpression(e)?$n(e):{analyzable:!1,presentKeys:[],trueKeys:[]},gc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&hn(t.getBody());return s?$n(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},pc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=N(n.getExpression());i!==void 0&&(lc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Nt(n.getArguments()[0])}):uc.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...gc(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=N(n.getExpression());i===void 0||!dc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Nt(n.getArguments()[0])})}return s},mc=(e,t)=>{for(const s of fc){const n=v(t,s);if(!M(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))N(a.getExpression())===ws&&o.push({callee:ws,file:s,line:a.getStartLineNumber(),...Nt(a.getArguments()[0])});return o}return[]},hc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of qe(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...pc(o,n))}return s.push(...mc(e,Lt(t))),s},Is="ctx.containers.",vc=e=>{if(!e.startsWith(Is))return!1;const t=e.slice(Is.length);return t.length>0&&!t.includes(".")},Ec=(e,t)=>Qe(e,t,{argIndex:0,matchReceiver:vc,methods:new Set(["get"])}),xc=new Set(["allow","deny","setAllowed"]),Sc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=z(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},Ac=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Sc(e)))return{detail:"enableInternet: true",scope:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},yc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!xc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},bc=(e,t)=>Ac(e,t)??yc(e,t),Nc=(e,t)=>I(e,t,bc),Pc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&_(s.getExpression())?s.getName():void 0},wc=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&_(s)?1:0]},Ic=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Cc=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>Ic.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Tc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return I(e,t,(i,o)=>{const a=Pc(i);if(a===void 0)return;const c=Cc(wc(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:x(i),table:a}})},Oc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),kc=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Oc.has(s)?s:void 0},Rc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=y(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Fc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of qe(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=kc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Rc(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},Lc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Dc=new Set(["dbRateLimit","rateLimit"]),Mc=e=>{const t=En(e);if(!t)return!1;const s=z(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},_c=(e,t)=>{const s=N(e.getExpression());if(s===void 0)return;const n=Lc.get(s);if(n!==void 0)return{callee:s,scope:x(e),failOpen:Mc(e.getArguments()[n]),file:t,limitName:Dc.has(s)?vn(e):"",line:e.getStartLineNumber()}},Kc=(e,t)=>I(e,t,_c),Bc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ee(t);if(s?.kind!=="query")return;const n=sr(t,s.receiver);return n?{exportName:q(e)??e.getName(),handler:n}:void 0},Cs=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},zc=e=>{const t=Cs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Cs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},$c=(e,t)=>{const s=[];for(const n of He(e.handler,"flags"))s.push({callee:zc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Vc=(e,t)=>{const s=[];for(const n of Y(e)){const i=Bc(n);i&&s.push(...$c(i,t))}return s},Uc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Vc(i,w(t,n)))}return s},Wc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:H(e.getExpression(),["flags"]),qc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},jc=(e,t)=>{if(!Wc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=qc(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:x(e),file:t,key:i,line:e.getStartLineNumber()}},Hc=(e,t)=>I(e,t,jc),Gc=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Yc=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Qc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))Gc(a)&&s.push({file:o,indexName:Yc(a),line:a.getStartLineNumber()})}return s},Se=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,Vn=e=>{const t=e.getArguments()[0],s=Se(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=z(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?Se(n.getInitializer()):void 0},Xc=new Set(["delete","get","head","options","patch","post","put"]),Jc=new Set(["handler","stream"]),Zc=new Set(["runAction","runMutation"]),el=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Ae=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Un=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(oe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Ts=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Un(s,"ctx")},Os=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Un(s,"request")},ks=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Zc.has(a)&&Ae(c,t))return a;if(el.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Ae(c.getExpression(),t))return`db.${a}`}},Rs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Ae(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Ae(n.getInitializer(),t))){for(const o of i.getElements())if(oe(o)==="auth")return!0}}return!1},tl=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,sl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Ae(n.getExpression(),t)},nl=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Wn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:nl(s)},il=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?Wn(t,a.getText()):[]}return[]},rl=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=Wn(s,t.getText());return n.length>0?n:il(t,s)},Fs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>sl(i,t)&&rl(i).some(o=>tl.test(o)))},ol=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Jc.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Xc.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},al=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Se(e.getArguments()[0]),l=c&&Ts(c,!0);if(!c||l===void 0||Fs(c,Os(c,!0)))return;const u=ks(c,l);return u===void 0?void 0:{scope:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Rs(c,l),sideEffect:u}}const n=ol(e);if(n===void 0)return;const i=Se(e.getArguments()[0]),o=i&&Ts(i,!1);if(!i||o===void 0||Fs(i,Os(i,!1)))return;const a=ks(i,o);return a===void 0?void 0:{scope:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Rs(i,o),sideEffect:a}},cl=(e,t)=>I(e,t,al),ll=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),dl=new Set(["append","set"]),qn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Ls=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>ll.has(N(n.getExpression())??"")&&Re(n,t)),ul=(e,t)=>{if(Ls(e,t))return!0;const s=G(e);return s!==void 0&&Ls(s,t)},Pt=(e,t)=>ga(e,t)&&!ul(e,t),fl=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=G(e);return t!==void 0&&r.isNewExpression(t)&&N(t.getExpression())==="Headers"},Be=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=G(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Wt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Pt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:qn(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Pt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=Be(n.getExpression());i!==void 0&&Wt(i,t,s)}},jn=(e,t)=>{const s=Be(e);if(s===void 0)return;const n=z(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=Be(n.getInitializer());i!==void 0&&Wt(i,"response-init",t)},gl=(e,t)=>{const s=N(e.getExpression());if(s==="Response")jn(e.getArguments()[1],t);else if(s==="Headers"){const n=Be(e.getArguments()[0]);n!==void 0&&Wt(n,"headers-ctor",t)}},pl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){jn(e.getArguments()[1],t);return}if(dl.has(n)&&fl(i)){const o=e.getArguments()[1];o!==void 0&&Pt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:qn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},ml=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))gl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))pl(s,t)},hl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Se(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return ml(n,{scope:x(e),relativePath:t,requestName:o.getText(),rows:a}),a},vl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...hl(n,t));return s},El=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vl(i,w(t,n)))}return s},Hn="identity.ts",xl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ge(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Sl=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ge(n.getModuleSpecifierValue())}return!1},Al=e=>{if(r.isIdentifier(e))return xl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Sl(t)}return!1},yl=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Al(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw be(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=yn(s,"member");a!==void 0&&t.push({exportName:a})}return t},bl=(e,t)=>{const s=v(t,Hn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=yl(n);if(i.length!==0){if(i.length>1)throw be(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Nl=new Set(["auth","context.auth"]),Pl="userId",wl=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(y(s))}return t},Il=(e,t)=>{const s=v(t,Hn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(N(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?wl(o):void 0}},Ds=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Nl.has(t.getText())||H(t,["auth"])?e:void 0},Cl=e=>{if(r.isPropertyAccessExpression(e)&&Ds(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Ds(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Ms=(e,t,s)=>{const n=Cl(e);return n===void 0?void 0:{declared:n===Pl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:x(e)}},Tl=(e,t)=>{const s=Il(e,t);return s===void 0?[]:[...se(e,t,d.PropertyAccessExpression,(n,i)=>Ms(n,i,s)),...se(e,t,d.ElementAccessExpression,(n,i)=>Ms(n,i,s))]},Ol=(e,t)=>{if(N(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=R(s,"key");if(!(!n||!W(n)||ae(n)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},kl=(e,t)=>I(e,t,Ol),Rl=new Set(["delete","get","getRaw","getWithMetadata","put"]),Fl=(e,t,s=[])=>{const n=Qe(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Rl});return _t(n,s)},Ll=new Set(["queue","send"]),_s=new Set(["bcc","cc","to"]),Dl=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ll.has(t))return;const s=e.getExpression();return H(s,["mail"])||H(s,["email"])?t:void 0},Ml=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return _s.has(y(t))&&W(n)&&!ae(n)}if(!r.isPropertyAssignment(t)||!_s.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&W(s)&&!ae(s)}):!1,_l=(e,t)=>{const s=Dl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Ml(n)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Kl=(e,t)=>I(e,t,_l),Bl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Ke(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Ke(l);if(u===void 0)continue;const f=Tn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},zl=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;return n?.receiver?Bt(n.receiver).flatMap(i=>Bl(i,q(e)??e.getName(),t)):[]},$l=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of Y(i))s.push(...zl(a,o))}return s},Vl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Ul=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=z(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Wl=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return wr(s.getExpression())?s:void 0},ql=e=>{const t=Wl(e),s=t===void 0?void 0:Ul(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?q(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Vl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},jl=e=>e.getVariableDeclarations().flatMap(t=>ql(t)),Hl=(e,t)=>{const s=v(t,Pr);if(!M(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return jl(n)},Gl=new Set(["delete","get","patch"]),Yl=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Ql=new Set(["auth","identity","session","user"]),Xl=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Jl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Zl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},ed=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),td=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,sd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>ed(s.getExpression(),t)&&td(s.getThenStatement())),nd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Gl.has(i))continue;const o=n.getExpression();if(!(_(o)||r.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},id=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Kt(Dt(s))!==void 0)),rd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Xl.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),od=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Yl.has(t.getText()))return!0;return[...Ql].some(t=>He(e,t).length>0)?!0:id(e)||rd(e)},ad=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ee(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Vn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&wn(n.receiver,"use","rls"),a=od(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=Jl(u);if(f===void 0)continue;const g=Zl(u);if(g===void 0||c.has(g)||!sd(i,g))continue;const p=nd(i,g);p!==void 0&&(c.add(g),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:f,usesRls:o,visibility:n.visibility}))}return l},cd=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of Y(i))s.push(...ad(a,o))}return s},Gn=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?L(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},ld=e=>{const t=P(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!je(s)},dd=e=>{const t=P(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},ud=e=>{const s=P(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!je(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},ze=e=>{const t=L(e);return t===void 0||ar(t.getSourceFile())},wt=(e,t)=>{const s=P(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&ze(o);if(Gn(Dt(o),t))return!(r.isPropertyAccessExpression(o)&&Nn.has(o.getName()))||r.isExpressionStatement(P(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!ze(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},Fe={kind:"opaque"},fd={kind:"unreached"},gd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},It=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?L(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=gd(s);return i===void 0||Mt(i)?void 0:i}const n=ne(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Yn=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?Fe:c===void 0?a.some(l=>l.isRestParameter())?Fe:fd:c.isRestParameter()?Fe:{kind:"parameter",parameter:c}},pd=e=>{const t=P(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=It(s.getExpression());return n===void 0?Fe:Yn(n,s,t)},md=new Set(["__defineGetter__","__defineSetter__","__proto__"]),hd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Qn=e=>{const t=P(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=hd(s);if(n!==void 0)return S(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},vd=4,Xn=(e,t,s=0)=>{if(or(e))return!0;if(ld(e)){const i=P(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!md.has(c)}if(dd(e)||ud(e)||Qn(e)||wt(e,t))return!0;const n=pd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Ed(n.parameter,s+1)},Ks=new WeakMap,Ed=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Ks.get(e.compilerNode);if(n!==void 0)return n;if(t>vd)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||L(a)?.compilerNode!==e.compilerNode||Xn(a,void 0,t));return(o||t===0)&&Ks.set(e.compilerNode,o),o},Bs=new WeakMap,xd=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=L(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Sd=(e,t,s)=>{const{context:n,impl:i}=e,o=Bs.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const p=g.getNameNode();return r.isIdentifier(p)?[p]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?Xn(g,n):!je(g),f=!xd(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const p=g.getText();if(p==="arguments")return!1;const E=l.get(p);return E===void 0||c.includes(g)||L(g)?.compilerNode!==E?!0:u(g)});return Bs.set(i.compilerNode,f),f},zs=new WeakMap,Ad=e=>{let t=zs.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Ir(s);return n===void 0?[]:[[n.compilerNode,s]]})),zs.set(e.compilerNode,t)),t},yd=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[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:q(n)??n.getName()};return a!==void 0&&Sd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},ft="args",he=e=>{const t=xn(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===ft?t.member:void 0}if(!r.isIdentifier(e))return;const s=L(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ne(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&oe(i)===ft||r.isIdentifier(o)&&o.getText()===ft?oe(s):void 0},bd=new Set(["auth","identity","user"]),Ct=e=>{const t=i=>{const o=Kt(i);return o!==void 0&&o.length>0&&bd.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=G(s);return n!==void 0&&t(n)},Jn=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=he(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?G(n):void 0;if(o!==void 0)for(const a of Jn(o,t-1))s.add(a)}return s},Le=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Le(n),...Le(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=he(h(u)??u);return g===void 0?[]:Le(f).filter(p=>p===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=he(h(n)??n),c=he(h(i)??i);return a!==void 0&&Ct(i)&&o.push(a),c!==void 0&&Ct(n)&&o.push(c),o},Nd=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&hr(i.getExpression(),"defineIdentityGuard")},Pd=e=>{if(!Nd(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=he(h(s)??s),o=t.some((a,c)=>c!==n&&Ct(a));return i!==void 0&&o?[i]:[]})},wd=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},Id=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),$s=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Cd=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Td=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&$s(n,e)&&wd(n.getThenStatement()))for(const i of Le(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&Cd(n)&&$s(n,e))for(const i of Pd(n))s.add(i);return s},Od=(e,t)=>{const s=Jn(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Id);if(n===void 0)return!1;const i=Td(n,e.getStart());return[...s].every(o=>i.has(o))},kd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Rd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Tt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Zn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Fd=e=>{const t=P(e),s=t.getParent();if(r.isVariableDeclaration(s))return S(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Ld=e=>{const t=Fd(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ne(t)?[t]:void 0:Zn(t)},ve=e=>e.isUnion()?e.getUnionTypes().every(t=>ve(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ve(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),$e=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},De=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Dd=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&Rd.get(s.getText())?.has(t.getName())===!0&&ze(s)},Md=e=>{const t=xt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=P(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&$e(n,Pn)?n:void 0},_d=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=P(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:$e(n,kd,t)?n:void 0},Kd=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Bd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&S(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Vs=e=>{const t=P(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Dd(s);return _d(s,t)??Kd(s,t)??Bd(s,t)??(n?s:Md(t))},zd=5e4,ei=()=>({inProgress:new Set,verdicts:new Map});class $d{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>zd&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Vd=8,Ud=8;class Wd{budget;scope;taint;verdicts=ei();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ve(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Zn(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Vd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(P(l),!0,a,0))&&(t===n||!ve(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let p=Vs(o);p!==void 0;p=Vs(o)){if(r.isCallExpression(p)&&this.callbackCompromises(p,n))return!0;o=P(p)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ve(o.getType());if(je(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Ld(o);if(u!==void 0)return u.some(p=>n(p,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=P(t).getParent();if(n>=Ud)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===P(t)?this.valueCompromises(i,!1,s,n+1):!$e(i,Tt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ne(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=P(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>De(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=$e(t,Tt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=It(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!wt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(wt(s,this.scope.context))return!1;const i=It(t.getExpression()),o=i===void 0?void 0:Yn(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Qn(t)||S(xt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=xt(t);return S(s,this.scope.impl)?void 0:s}}const qd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),jd=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=L(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Hd=new Set(["all","allSettled","any","race"]),Us=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,gt=8;class Gd{budget=new $d;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=ei();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,gt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>cr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=L(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=P(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Tt.has(g.getName()))return!0;const p=a.getArguments().filter(E=>E!==o);return this.isTaintedValue(g.getExpression(),!0)||p.some(E=>this.isTaintedValue(E,!1))}const c=r.isVariableDeclaration(a)&&ne(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const p=P(g),E=p.getParent();return!r.isCallExpression(E)||E.getExpression()!==p||this.isCallSiteTainted(E,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&ze(i)&&Hd.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:De(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=L(t),i=Us(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Nn.has(i)?!1:i!==void 0&&Pn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>De(a)!==void 0)&&(i===void 0||!qd.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Dt(i),c=r.isIdentifier(a)?Us(L(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=De(i);if(o===void 0)return!jd(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=nr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Gn(i,this.scope.context))return!0;const o=r.isIdentifier(i)?L(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ne(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Mt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,gt))return!1;if(this.variableDepth>=gt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Ws=new WeakMap,Yd=e=>{const t=Ws.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Gd(e);return Ws.set(e.impl.compilerNode,s),s},Qd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Xd=new Set(["insert","insertManyUnsafe","patch","replace"]),Jd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Xd.has(t)&&fr(e.getExpression())?t:void 0},Zd=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},eu=(e,t)=>{const s=xn(e);return s?.member===t?h(s.object):void 0},qs=(e,t)=>r.isIdentifier(e)&&L(e)?.compilerNode===t.compilerNode,ti=(e,t,s,n=1)=>{const i=eu(e,s);if(i!==void 0)return qs(i,t);const o=r.isIdentifier(e)?L(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&oe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ne(l)&&qs(h(l.getInitializer()),t))}const a=ne(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&ti(a,t,s,n-1)},Ot=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ot(t.getWhenTrue()),...Ot(t.getWhenFalse())]:[t]},tu=(e,t,s)=>{const n=[],i=s===void 0?void 0:Yd(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Qd.has(a))continue;const l=Ot(c).filter(f=>i===void 0?W(f)&&!gr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&ti(c,s.parameter,a),g=l.every(p=>Od(t.call,p));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},su=(e,t,s)=>{const n=Jd(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=Zd(i,n);if(o.length===0)return[];const a=x(e),c=yd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>tu(u,l,c))},nu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=I(e,t,(c,l)=>su(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return _t(o,s).map(c=>lr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},iu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ru=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,ou=e=>{const t=z(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?ru(t.getInitializer()):void 0},au=(e,t)=>{const s=N(e.getExpression());if(s===void 0||!iu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?ou(n):void 0;return{callee:s,scope:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},cu=(e,t)=>I(e,t,au),lu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),du=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},uu=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=z(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},si=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},ni=(e,t)=>e===t||e.startsWith(`${t}.`),ii=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},js=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},ri=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>js(s));return r.isIdentifier(e)&&js(e)&&t.push(e),t},fu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},gu=e=>{const t=si(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},pu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:gu(e),i=new Set,o=a=>ii(a).some(c=>n.some(l=>ni(c.getText(),l)))?!0:ri(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of fu(a))i.add(l)}return{names:i,prefixes:n}},mu=(e,t)=>ii(e).some(s=>t.prefixes.some(n=>ni(s.getText(),n)))?!0:ri(e).some(s=>t.names.has(s.getText())),hu=e=>{const t=ir(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},vu=(e,t,s)=>{const n=si(e,0);if(n===void 0)return[];const i=pu(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!Sn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!mu(u,i))continue;const f=hu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:x(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Eu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=du(n),o=i===void 0?void 0:lu.get(i);if(o===void 0)continue;const a=uu(n,o);a!==void 0&&s.push(...vu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},xu=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Eu(i,w(t,n)))}return s},Hs={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Gs=new Set(["account","credential","member","passkey","session","user"]),Su=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Au=e=>{const s=Su(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Gs.has(s)||Gs.has(n)},yu=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},bu=(e,t)=>{const{objects:s,opaque:n}=Vt(e,t);return Fa(s).some(i=>yu(i))?!0:n?void 0:!1},Nu=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!z(t,"captcha"),usesRateLimit:!!z(t,"rateLimit")}},Pu=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Me={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},wu=e=>{const t=Pu(e),s=t?N(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Nu(t);return{...Me,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Hs?{...Me,[Hs[s]]:!0}:Me},Iu=e=>{const t={...Me};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=wu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Cu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Tu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Cu.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:Au(i.getLiteralText())},Ou=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Ys=new Set(["queues","scheduler","topics","workflows"]),ku=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ou.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Ys.has(s.getName())&&pr(s.getExpression()))return!0;s=s.getExpression()}const n=Kt(s);return n?.length===1&&Ys.has(n[0]??"")},Ru=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},oi=new Set(["generateObject","generateText","streamObject","streamText"]),Fu=e=>{const t=N(e.getExpression());return t!==void 0&&oi.has(t)},Lu=e=>{const t=N(e.getExpression());if(t===void 0||!oi.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!z(s,"maxOutputTokens")},Du=new Set(["log","span","trace"]),Mu=new Set(["ai"]),_u=new Set(["email","mail"]),Ku=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),pt=(e,t)=>[...t].some(s=>He(e,s).length>0),ai=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Bu=new Set(["every","filter","flatMap","forEach","map","some"]),zu=new Set(["all","allSettled","race"]),ci=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Bu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&zu.has(n))return t},$u=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ai.has(t.getKind())){const s=ci(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Vu=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(ai.has(t.getKind())){if(t=ci(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Uu=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(p=>{const E=p.getExpression();return r.isIdentifier(E)&&E.getText()===l&&r.isAwaitExpression(p.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Wu=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},qu=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ju=e=>{let t=!1,s=!0;for(const n of[...Ku].flatMap(i=>He(e,i))){const i=qu(n);i&&(t=!0,!$u(i)&&!Wu(i)&&!Uu(i)&&!Vu(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Hu=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),Qs="lunora-advisor-exempt",Gu=/^[\s*/]+/u,Yu=/[\w-]/u,Qu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
2
|
-
`);for(const n of s.split(`
|
|
3
|
-
`)){const i=n.replace(Gu,"");if(!i.startsWith(Qs))continue;const o=i.slice(Qs.length);if(Yu.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:""}},Xu=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=z(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Ju=(e,t)=>{const s=Xu(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},Zu=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(Tu(l)&&(o=!0),ku(l)&&(t=!0),Ru(l)&&(i=!0),Fu(l)&&(s=!0),Lu(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=ju(e);return{callsMail:pt(e,_u),emitsEvent:pt(e,Du),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||pt(e,Mu),throwsBareError:Hu(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},ef=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ee(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Iu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Ju(e,s);return{...o?Zu(o):{},...Qu(e),...i,analyzableBody:o!==void 0,exportName:q(e)??e.getName(),file:t,hasEmailArg:bu(s,n.receiver),kind:n.kind,visibility:n.visibility}},tf=(e,t)=>{const s=[];for(const n of Y(e)){const i=ef(n,t);i&&s.push(i)}return s},sf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tf(i,w(t,n)))}return s},nf=new Set(["dbRateLimit","rateLimit"]),rf=e=>r.isArrowFunction(e)?e.getBody():e,of=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},li=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},di=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},af=(e,t)=>W(e)||t!==void 0&&di(e,t).some(s=>li(s)),cf=(e,t)=>t===void 0?ae(e):di(e,t).some(s=>!li(s)),lf=(e,t)=>{const s=N(e.getExpression());if(s===void 0||!nf.has(s))return;const n=R(En(e.getArguments()[2]),"key");if(!n)return;const i=rf(n),o=of(n);if(!(!af(i,o)||cf(i,o)))return{callee:s,scope:x(e),file:t,limitName:vn(e),line:e.getStartLineNumber()}},df=(e,t)=>I(e,t,lf),uf=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),ff=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!uf.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},gf=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},pf=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},ui=(e,t=!1)=>{const s=pf(e);if(r.isIdentifier(s)){if(t)return;const n=G(s);return n===void 0?void 0:ui(n,!0)}if(r.isCallExpression(s))return ff(s)??gf(s)},mf=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},hf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ee(s);if(n?.kind!=="query")return[];const i=Vn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&vr(n.receiver,"output"),a=n.receiver!==void 0&&wn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of mf(i)){const f=ui(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},vf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of Y(i))s.push(...hf(a,o))}return s},Ef=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(y(s));return t},xf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=Cn(o);if(a===void 0)continue;const c=Ef(R(a.options,"with"));c.length!==0&&i.push({exportName:q(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Sf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of Y(i))s.push(...xf(a,o))}return s},U=(e,t)=>`${e}:${t}`,Xs=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Af=(e,t)=>[...se(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Xs(s,n,s.getName(),s.isExported()):void 0),...se(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Xs(i,n,s.getName(),i.isExported()):void 0})],yf=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=w(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(U(c,a))},bf=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Nf=(e,t)=>{const s=new Map(e.map(n=>[U(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(U(i.file,i.name))?.set(bf(n),{fields:n.fields,method:n.method,table:n.table})}return s},Pf=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>yf(n,t,s)).filter(n=>n!==void 0),wf=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(U(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(U(o.file,o.name))?.push(a)}},If=(e,t,s)=>{const n=new Map(e.map(a=>[U(a.file,a.name),a])),i=new Map(e.map(a=>[`${zt(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[U(a.file,a.name),Pf(a,n,t)]));return wf(s,n,i,o),o},Cf=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Tf=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(U(i.file,i.name))??[])Cf(t.get(U(i.file,i.name)),t.get(U(o.file,o.name)))&&(n=!0)}},Of=(e,t,s,n)=>{const i=Af(e,t),o=Nf(i,s);return Tf(i,o,If(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(U(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ve=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ve(e.getLeft()),s=Ve(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},kf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ve(t)!==void 0},Rf=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return y(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Ff=(e,t,s)=>_r(e)?!rr(s)&&Kr(Rf(t)):!0,Lf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(kf(o))continue;const a=Ve(o);if(a===void 0)continue;const c=Dr(a);if(c===void 0||!Ff(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:Mr(a)}))}return s},Df=(e,t)=>{const s=[];for(const n of A(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Lf(i,w(t,n)))}return s},Mf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=Cn(o);if(a===void 0)continue;const c=R(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&W(c);!l&&!u||i.push({exportName:q(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},_f=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of Y(i))s.push(...Mf(a,o))}return s},Kf=new Set(["query","unsafe"]),Bf=e=>!r.isPropertyAccessExpression(e)||!Kf.has(e.getName())?!1:H(e.getExpression(),["sql"]),zf=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),$f=(e,t)=>{if(!Bf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!zf(s)))return{file:t,line:s.getStartLineNumber(),scope:x(e)}},Vf=(e,t)=>I(e,t,$f),Uf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Wf=e=>{for(const[t,s]of Uf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},qf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Wf(a);c!==void 0&&s.push({file:w(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},jf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Hf=(e,t,s=[])=>{const n=Qe(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:jf,requireUnmodifiedReach:!0});return _t(n,s)},Gf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Yf=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Qf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),o==="expiresInSeconds"&&(s=Yf(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Xf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Gf.get(t);return s===void 0?void 0:bn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Jf=(e,t)=>{const s=Xf(e.getExpression());if(s!==void 0)return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Qf(e.getArguments()[s.optionsIndex])}},Zf=(e,t)=>I(e,t,Jf),eg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),fi=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:eg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>ie(i)||s(i));if(!(n===void 0||ie(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},qt=(e,t)=>S(e.getFirstAncestor(s=>S(s,t)||ie(s)),t),tg=(e,t)=>S(e,t)||e.getFirstAncestor(s=>S(s,t))!==void 0,gi=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return S(e,t)||qt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=fi(e);return s!==void 0&&!tg(s,t)}return!1},pi=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],sg=e=>pi(e).some(t=>gi(t,e)),ng=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},ig=e=>pi(e).some(t=>gi(t,e)||r.isBreakStatement(t)&&S(fi(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>ng(t)&&qt(t,e)),rg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>qt(t,e)),og=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),ag=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",mt=(e,t)=>{const s=og(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||ig(e)||rg(e))return;const i=x(e);if(!(i.kind==="module"&&e.getFirstAncestor(ie)!==void 0))return{file:t,kind:ag(e),line:e.getStartLineNumber(),scope:i}},cg=(e,t)=>[...se(e,t,d.WhileStatement,mt),...se(e,t,d.ForStatement,mt),...se(e,t,d.DoStatement,mt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),lg=new Set(["when","where"]),ht=new Set(["definePolicy","defineShape"]),dg=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return ht.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return ht.has(i)?i:void 0}const s=t.getText();return ht.has(s)?s:void 0},ug=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,mi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(ug(e))return"empty-object";if(r.isParenthesizedExpression(e))return mi(e.getExpression())}},jt=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),fg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>jt(t)===e),hi=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>jt(t)===e),gg=e=>{const t=fg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||hi(e).length>0},pg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>jt(t)===e),kt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",mg=(e,t)=>kt(e)||kt(t),hg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Js=e=>!kt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),vg=(e,t,s)=>{const n=hg.get(e);if(n!==void 0)return mg(t,s)?n==="positive"?"negative":"positive":Js(t)||Js(s)?void 0:n},Ee=e=>{if(r.isParenthesizedExpression(e))return Ee(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=vg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=Ee(e.getLeft()),i=Ee(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Zs=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},Eg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},xg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Sg=e=>{const t=[];for(const s of hi(e)){const n=Ee(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of pg(e)){const n=Ee(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Zs(s.getThenStatement()):Zs(s.getElseStatement())??Eg(s);i!==void 0&&t.push(xg(i))}return t},Ag=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},yg=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!lg.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&gg(a))for(const c of Sg(a)){const l=mi(c);l!==void 0&&i.push({exportName:Ag(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},bg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=dg(n);i!==void 0&&s.push(...yg(n,i,t))}return s},Ng=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...bg(i,w(t,n)))}return s},Pg=new Set(["query","upsert","upsertMany","upsertNow"]),fe=new Set,wg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Pg.has(t))return H(e.getExpression(),["vectors"])?t:void 0},Ht=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},vi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Ei=e=>vi(e)?.getDeclarations()[0],Ig=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},xi=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},en=(e,t,s)=>{const n=vi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=xi(Ei(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return Gt(o,t,s-1)}return W(e)},Gt=(e,t,s)=>{const n=Ht(e);return ae(n)?!1:r.isIdentifier(n)?en(n,t,s):W(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>Ig(i)&&en(i,t,s))},Si=e=>{const t=xi(Ei(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},Z=(e,t)=>{const s=Ht(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...Z(s.getWhenTrue(),t),...Z(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...Z(s.getLeft(),t),...Z(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Si(s);return n===void 0?[]:Z(n,!1)}return[]},Cg=(e,t)=>{const s=Z(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Ue(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Tg=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Og=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Ue=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Cg(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Tg(n)&&(s=[Og(n)]);return s},kg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Rg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return fe;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return fe;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Rt=(e,t=!0,s=fe)=>{const n=Ht(e);if(r.isIdentifier(n)){const o=t?Si(n):void 0;return o===void 0?[{node:n,parameters:s}]:Rt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Rt(o.getExpression(),t,s):Z(o,!0).flatMap(a=>Ue(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=Gt(i.getExpression(),fe,1)?Rg(o):fe;return kg(o).flatMap(c=>Z(c,!0).flatMap(l=>Ue(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Fg=(e,t)=>{const s=wg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Rt(n):Z(n,!0).flatMap(o=>Ue(o,!0).map(a=>({node:a,parameters:fe})))).some(({node:o,parameters:a})=>Gt(o,a,1))))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Lg=(e,t)=>I(e,t,Fg),Dg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:p,workflows:E}=s;return Ji({adminRoutes:aa(e,t),aiRawRuns:ha(e,t),aiToolSideEffects:Ia(e,t),argumentDerivedFetches:Oa(e,t),argumentValidators:Ga(e,t),authApiCalls:yr(e,t),authConfigs:ic(e,t),browserUrlAccesses:cc(e,t),callEdges:n.callEdges,configCalls:hc(e,t),containerKeyAccesses:Ec(e,t),containerOverrides:Nc(e,t),containers:i,countReads:Tc(e,t,f.tables),cronTargets:o.flatMap(V=>V.functionPath===void 0?[]:[V.functionPath]),exportSinks:Fc(e,t),staleMigrationImports:qf(e,t),failOpenGuards:Kc(e,t),flagReads:Uc(e,t),flagSecurityDefaults:Hc(e,t),geoIndexUsages:Qc(e,t),httpActionGuards:cl(e,t),httpHeaderWrites:El(e,t),hyperdriveCalls:br(e,t),identityClaimReads:Tl(e,t),imageDeliveryUrlAccesses:kl(e,t),inserts:n.inserts,kvKeyAccesses:Fl(e,t,a),mailRecipientAccesses:Kl(e,t),maskProcedures:Nr(e,t),maskStrategies:$l(e,t),mutatorWrites:Hl(e,t),nondeterministicCalls:Tr(e,t),normalizeIdAuthorizations:cd(e,t),notifyCalls:kr(e,t),notifyConfig:Or(e,t),mutators:l,ownerFieldWrites:nu(e,t,a,l),unrestrictedWhereBranches:Ng(e,t),paymentWebhooks:cu(e,t),privilegedDispatches:xu(e,t),procedureProtections:sf(e,t),queries:n.queries,queues:u,r2sqlCalls:Rr(e,t),ratelimitKeySelectors:df(e,t),rawRowReturns:vf(e,t),relationLoads:Sf(e,t),rlsProcedures:Fr(e,t),schema:f,secretLiterals:Df(e,t),modules:c,shapes:g,softDeleteReads:_f(e,t),sqlInterpolations:Vf(e,t),storageKeyAccesses:Hf(e,t,a),storageUploads:Zf(e,t),tableWrites:n.tableWrites,rowEffects:Of(e,t,n.tableWrites,n.callEdges),unboundedLoops:cg(e,t),vectorNamespaceAccesses:Lg(e,t),workflowCalls:n.workflowCalls,workflows:E,wranglerVariables:p})},Mg=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),_g=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>Mg(i))]},Kg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Bg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",tn={error:"ERROR",info:"INFO",warn:"WARN"},sn={ERROR:2,INFO:0,WARN:1},zg=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"}),$g=(e,t)=>{const{advisor:s}=In(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(tn,n)?tn[n]:void 0;return i===void 0?[...t,zg(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=>Bg(o)||sn[o.level]>=sn[i])},Vg=(e,t)=>{const{advisor:s}=In(e),n=_g(t,s?.accept??[]);return $g(e,s?.acceptUnreadable===!0?[...n,Kg()]:n)},Ug={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Wg="crons",qg=$r.replace(/\.ts$/u,""),ue=(e,t)=>`${zt(e)}:${t}`,vt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},jg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Ug[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...vt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...vt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...vt("workflow",t.workflow,"workflow name")}))],Hg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Gg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Hg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Yg=e=>jg(e).flatMap(t=>Gg(t)),Qg=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:Wg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Xg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),me=(e,t)=>t===void 0?e:{...e,module:t},Jg=e=>{const t=new Map,s=new Map,n=Xg(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(ue(c.file,c.exportName),l)};for(const c of e.functions){const l=ue(c.filePath,c.exportName),u=[...Lr(c.filePath),c.exportName].join(".");o(me({detail:c.kind,id:`function:${l}`,kind:"function",name:u},ke(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ue(c.filePath,c.exportName);o(me({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},ke(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(me({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(me({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},ke(e.modules,c.filePath)),ue(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(me({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},ke(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ue(qg,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},Zg=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,ep=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ue(e.file,e.exportName))??{reason:Zg(e.exportName)},tp=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=ep(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},Et=e=>`${e.from}|${e.kind}|${e.to}`,sp=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,np=e=>{const{nodes:t,sites:s}=Jg(e),n=new Map,i=new Map;for(const o of[...Qg(e),...Yg(e)]){const a=tp(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(Et(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(sp(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>Et(o).localeCompare(Et(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},ip=e=>`${Wr}export const architecture = ${Ur(e,"Record<string, unknown>")};
|
|
4
|
-
`,nn=(e,t="api")=>{const s=new Map;for(const n of e){const i=zt(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new j("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},rp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>On(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=>kn(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:jr)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)},op=(e,t,s={})=>{if(t===void 0)return;const n=rp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
5
|
-
`);throw new j("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
6
|
-
${i}
|
|
7
|
-
|
|
8
|
-
Install them with your package manager, then re-run codegen.`)},ap="env.ts",cp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ge(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},lp=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ge(n.getModuleSpecifierValue())}return!1},dp=e=>{if(r.isIdentifier(e))return cp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&lp(t)}return!1},up=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!dp(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw be(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=yn(s,"member");a!==void 0&&t.push({exportName:a})}return t},fp=(e,t)=>{const s=v(t,ap);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=up(n);if(i.length!==0){if(i.length>1)throw be(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},gp={deliveryAuthorization:"deliveryAuthorization",defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"typedWebSockets"},pp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),mp=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},hp=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),vp=new Set(["durable"]),Ep=new Set(["rollback"]),Ai=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},xp=new Map([["defineContainer",{keys:pp,signal:"containerEgressPolicy"}],["defineStep",{keys:Ep,signal:"workflowRollback"}],["stream",{keys:vp,signal:"durableStreams"}]]),Sp=(e,t)=>{const s=xp.get(Ai(t));if(s!==void 0)return t.getArguments().some(n=>hp(mp(e,n),s.keys))?s.signal:void 0},Ap=(e,t)=>{const s={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,typedWebSockets:!1,workflowRollback:!1};for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(!s.secrets||!s.liveContext){const o=Xr(i);s.secrets=s.secrets||o.has("secrets"),s.liveContext=s.liveContext||o.has("live")}for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=Sp(i,o);a!==void 0&&(s[a]=!0);const c=gp[Ai(o)];c!==void 0&&(s[c]=!0)}if(Object.values(s).every(Boolean))break}return s},yp="createWorker",bp="extend",rn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,on=e=>{const t=[],s=rn(R(e,"backupCron"));s!==void 0&&t.push(s);const n=R(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=rn(i.getNameNode());o!==void 0&&t.push(o)}return t},Np=e=>{const t=N(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===yp)return r.isObjectLiteralExpression(s)?on(s):[];if(t!==bp||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=hn(s.getBody());return n===void 0?[]:on(n)},Pp=(e,t)=>{const s=[];for(const{filePath:n}of qe(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression))s.push(...Np(o))}return[...new Set(s)]},yi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:yi(e.inner)},wp=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=yi(n);return i!==void 0&&t.has(i)}))},Ip=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new j("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new j("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Cp=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=bl(s,t),a=fp(s,t),c=Vr(s,t),{queues:l,topics:u}=Zr(s,t),f=to(n),g=Gr(s,t);Ip(c,g);const p=Yr(s,t),E=so(s,t),V=Qr(s,t,c,g),ce=Pp(s,t),C=Ap(s,t),K=eo(s,t),$=Jr(s,t);$.browser=$.browser||K.usesSandboxBrowser;const F=Fn(n,e.target),k=no($,F,{agents:g.length>0,commitOrderedTables:i.tables.some(D=>D.commitOrdered===!0),cronTriggers:V.length>0,crossShardFanout:i.tables.some(D=>co(D)),containerEgressPolicy:C.containerEgressPolicy,containerRuntimeScheduling:p.some(D=>D.schedulingPolicy==="durable_object"),containerSandboxTools:p.some(D=>D.sandbox===!0),durableStreams:C.durableStreams,globalTables:i.tables.some(D=>D.shardMode==="global"),liveContext:C.liveContext,liveStreams:C.liveStreams,typedWebSockets:C.typedWebSockets,queues:l.length>0,relationGraph:wp(i),secrets:C.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:K.usesSandboxLoader,workflowRollback:C.workflowRollback,workflowSchedules:c.some(D=>D.schedules!==void 0)}),T=k.usage,Q=Hr(T),X=k.signals.vectorStore!==!1,te=k.signals.services===!1?[]:f,J=Rn(n),le=J??new Set,B=le.has("lunorash");op(i,J,{hasVectors:X,scheduler:T.scheduler||V.length>0,storage:T.storage||E.rules.length>0||Object.keys(Ln(i)).length>0,usage:T});const b=M(v(t,"flags.ts")),O=M(v(t,"notify.ts"));return{agents:g,capabilities:Q,containers:p,crons:V,dataModelContent:go(i),declaredDependencies:J,dependencies:le,entryCronTriggers:ce,env:a,featureUsage:T,hasFlags:b,hasNotify:O,identity:o,platformGate:{...k,diagnostics:[...io(n,e.target),...k.diagnostics,...ro(F,i.vectorIndexes),...C.liveStreams&&C.deliveryAuthorization?[oo(F)]:[]]},queues:l,serverContent:uo({agents:g,capabilities:Q,containers:p,env:a,hasVectors:X,hasFlags:b,hasNotify:O,identity:o,queues:l,schema:i,services:te,storageRuleBuckets:E.rules.map(D=>D.bucket),topics:u,useUmbrella:B,workflows:c}),services:te,storageRulesMetadata:E,topics:u,usesSandbox:K.usesSandboxBrowser||K.usesSandboxContainer||K.usesSandboxFs,useUmbrella:B,workflows:c}},bi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Tp=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},Op=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),kp=/^[\w$]+:[\w$]+$/u,Rp=(e,t)=>{const s=An(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},an=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Fp=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return an(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===er.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?an(s):void 0}}},Lp=(e,t,s)=>({schedule:{argKeys:Fp(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Dp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Sn.has(s))return Rp(s,n);if((s==="runAfter"||s==="runAt")&&Tp(t)){const l=An(i)??(r.isStringLiteral(i)&&kp.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Lp(s,n,o)}}const a=Op.get(s),c=a===void 0?void 0:bi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Mp=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Ni=e=>Zi.isOptionalChain(e.compilerNode),_p=(e,t)=>r.isIfStatement(t)?!S(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?S(e,t.getStatement()):r.isForStatement(t)?S(e,t.getStatement())||S(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ie(t)?t.getFirstAncestor(ie)!==void 0:r.isConditionalExpression(t)?!S(e,t.getCondition()):r.isBinaryExpression(t)?!S(e,t.getLeft())&&Mp.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Ni(t)?!S(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&sg(s)),Kp=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&S(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ie);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&S(o.getFirstAncestor(ie),i))===!0},Bp=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&S(e,t.getStatement())||r.isForStatement(t)&&(S(e,t.getStatement())||S(t.getIncrementor(),e)),zp=(e,t)=>{if(Ni(e)||t==="schedule"&&Kp(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(_p(s,i)){if(!Bp(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},cn=(e,t,s)=>{if(s===void 0)return;const n=zp(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:x(e)}},$p=(e,t)=>[...I(e,t,(s,n)=>cn(s,n,Dp(s))),...se(e,t,d.PropertyAccessExpression,(s,n)=>{const i=bi(s,"services");return cn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Vp=new Set(["boolean","number","object","string"]),Up=e=>{const t=e.getName();if(!Vp.has(t))return;const s=e.getExpression();return H(s,["flags"])||H(s,["flags","details"])?t:void 0},Wp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Up(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},qp=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=Wp(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},jp=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||po(o))return;const a=e.getSourceFile().getFilePath();if(mo(i,e,a)){const c=ho(i,e,a,0,new Set);return c===void 0&&vo(o),c}return o},Hp=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Er(t.getNameNode());return s===void 0||s==="namespace"}),Gp=(e,t)=>{for(const{filePath:s}of qe(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Hp(a)))return i}}},Yp="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Qp=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw be(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 (${Yp}). 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})},Xp=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Jp=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Xp(e):!0,Pi=(e,t=!1)=>{for(const s of e.getProperties()){if(Jp(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Pi(n,!0))return!0}return!1},Zp=(e,t)=>{for(const s of A(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Dn(n))for(const o of Bt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Pi(a)))return!0}}return!1},em=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Ke(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Ke(a);c!==void 0&&s.push({column:c,strategy:Tn(a),table:i})}}return s},tm=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Dn(i))for(const a of Bt(o))for(const c of em(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},sm=["providerSubscriptionId","state"],nm=["providerEventId","processedAt"],ln=(e,t)=>t.every(s=>s in e.shape),im=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&&ln(t,sm)&&ln(s,nm)},rm=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],om=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},am=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},cm="@lunora/privacy",wi="userId",lm=e=>e.replaceAll("\\","/"),dm="privacy",um=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),Xe=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Je=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Yt=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),fm=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},Ze=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},gm=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=fm(s,"tables"),i=Xe(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Yt(n).map(a=>Je(a)))t.datasets.set(o,i)},pm=(e,t)=>{const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)?Yt(s):[],i=new Set(n.map(o=>Je(o)));for(const o of rm)i.has(o)||t.datasets.set(o,"authDataset");for(const o of n){const a=r.isPropertyAssignment(o)?Xe(o.getInitializer()):void 0;a!==void 0&&t.datasets.set(a,"authDataset")}},dn=(e,t,s)=>{t.datasets.set(Xe(e.getArguments()[0])??s,s)},Qt=8,ye=(e,t=0)=>{if(t>Qt)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return ye(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:ye(i,t+1)},mm=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Je(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Ii=(e,t=0)=>{const s=ye(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Qt)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Ii(i.getExpression(),t+1):[mm(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},hm=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Ii(t)},vm=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:ye(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Yt(n):[])t.excluded.set(Je(i),r.isPropertyAssignment(i)?Xe(i.getInitializer())??"":"")},Em=(e,t)=>{switch(Ze(e)){case"actionCacheDataset":{dn(e,t,"actionCache");break}case"authDataset":{pm(e,t);break}case"defineDataset":{gm(e,t);break}case"documentHistoryDataset":{dn(e,t,"documentHistory");break}}},Xt=e=>e!==void 0&&r.isCallExpression(e)&&Ze(e)==="defineDataset",Ci=e=>e!==void 0&&r.isCallExpression(e)&&um.has(Ze(e)??""),xm=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Xt(i)||Ci(i))?n:void 0},Ti=(e,t,s=0)=>{const n=ye(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Qt)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Ti(i.getExpression(),t,s+1))return!1}else if(!Xt(i)&&!Ci(i)){const o=r.isIdentifier(i)?xm(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Sm=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Ti(t,s)?s:void 0},Am=(e,t)=>{const s=[];for(const i of e.getDescendantsOfKind(d.CallExpression))if(Em(i,t),Ze(i)==="definePrivacy"){const o=hm(i);vm(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Sm(o)})}return{declared:e.getDescendantsOfKind(d.VariableDeclaration).filter(i=>Xt(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},ym=(e,t)=>{const s=v(t,"schema.ts"),n=[...A(t),...M(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>lm(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},bm=(e,t,s)=>{if(s?.has(cm)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[]};const n={datasets:new Map,excluded:new Map},i=[],o=[];for(const f of ym(e,t)){const g=Am(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:om(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l}},Nm=e=>e.extensionKey!==dm&&wi in e.shape,Pm=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (it has a "${wi}" column) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,wm=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Nm(o)).map(o=>o.name),[n]=am(s,t.classifications);if(n!==void 0)throw new j("PRIVACY_COVERAGE",Pm(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new j("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Im=(e,t)=>{const s=ao(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Cm=new Set(["delete","hardDelete","patch","replace","restore"]),Tm=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),Om=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),un=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},km=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:un(i,e)}return un(s,e)},fn="",Rm=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},Fm=(e,t)=>{if(Tm.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():fn]};if(Cm.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:km(t,e);return{method:e,tables:s.length===0?[fn]:s}}},gn=(e,t)=>e===void 0?void 0:{...e,fields:Rm(t,e.method)},Lm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(_(n))return gn(Fm(s,e.getArguments()[0]),e);if(Om.has(s)&&r.isPropertyAccessExpression(n)&&_(n.getExpression()))return gn({method:s,tables:[n.getName()]},e)},Dm=(e,t)=>I(e,t,(s,n)=>{const i=Lm(s);if(i===void 0)return;const o=x(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Mm=(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"}),_m=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||z(s,"args")===void 0)return!1}return Vt(e,t).opaque},Km=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ee(a);c!==void 0&&_m(a,c.receiver)&&s.push(Mm(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Bm=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...Km(i,w(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},zm=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."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["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"}]]),We=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Oi=e=>!e.isAny(),ki=e=>{const t=e.getType();if(!Oi(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:zm.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},$m=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},Ri={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."},Vm=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.`}),Um={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)."},Wm=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),qm={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)."},jm=(e,t,s)=>{if(!t.some(i=>dr(i)))return Um;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Wm.has(s.typeName)&&!n&&!t.some(i=>Co(i))?qm:Ri},Fi=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Vm(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},Hm=(e,t,s)=>{const n=[];for(const i of Y(e)){const o=r.isIdentifier(i.getNameNode())?St(i):[i.getName()],c=o.some(u=>We(s,t,u))||!$m(i)?void 0:ki(i),[l=i.getName()]=o;c!==void 0&&n.push(Fi(t,l,c,i.getStartLineNumber(),jm(i,o,c)))}return n},Gm=(e,t,s)=>{if(We(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=ki(i.getExpression());o!==void 0&&n.push(Fi(t,"default",o,i.getStartLineNumber(),Ri))}return n},Ym=(e,t,s)=>[...Hm(e,t,s),...Gm(e,t,s)],Qm=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>St(n).some(i=>We(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=St(n).find(o=>We(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Xm=({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"}),Jm=(e,t,s)=>{const n=[],i=[];for(const a of A(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...Ym(c,l,s)),i.push(...Qm(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Oi(a.getType()))&&n.push(Xm(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Zm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},eh=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},th=(e,t)=>I(e,t,(s,n)=>Zm(s)?{file:n,line:s.getStartLineNumber(),scope:x(s),workflow:eh(s)}:void 0),Ne=(e,t)=>{M(e)&&Gi(e,"utf8")===t||Yi(e,t,"utf8")},sh=(e,t)=>{if(t===""){xe(e,{force:!0});return}Ne(e,t)},nh=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){xe(s,{force:!0,recursive:!0});return}if(M(s))for(const n of pn(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[mn(e,i)]===void 0&&xe(i)}for(const[n,i]of Object.entries(t))Ft(Lt(v(e,n)),{recursive:!0}),Ne(v(e,n),i)},ih=(e,t,s)=>{const n=v(e,t);if(Object.keys(s).length===0){xe(n,{force:!0,recursive:!0});return}if(M(n))for(const i of pn(n,{recursive:!0,withFileTypes:!0})){const o=v(i.parentPath,i.name);i.isFile()&&s[mn(n,o)]===void 0&&xe(o)}for(const[i,o]of Object.entries(s)){const a=v(n,i);Ft(Lt(a),{recursive:!0}),Ne(a,o)}},rh=e=>{try{const t=Oo(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},_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)},oh=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,ah=(e,t)=>{M(e)||Ft(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Ne(v(e,n.name),n.content),s.push(n.name);break}case"directory":{ih(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{nh(e,n.files),s.push(...Object.keys(n.files));break}default:sh(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},ch=e=>{const t=rh(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Ro({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Lo({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
|
|
9
|
-
`,openApiModuleContent:Fo(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
|
|
10
|
-
`,openRpcModuleContent:Do(i)}},lh=".lunora-schema.json",dh=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},uh=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new j("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new j("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 j("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})}},fh=8,gh=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:p,workflows:E}=e,V=()=>xo(()=>{const F=So(l,a,{lazyFunctions:o}),k=Cr(l,a);return{functions:F,httpRoutes:Ao(l,a),mutators:k}});let{erased:ce,value:{functions:C,httpRoutes:K,mutators:$}}=V();nn([...C,...$].map(F=>F.filePath)),nn(K.filter(F=>F.stream).map(F=>F.filePath),"http-stream");for(let F=1;;F+=1){const k=u?C:C.filter(b=>b.channel?.kind!=="room"),T=Uo({agents:t,functions:k,httpRoutes:K,mutators:$,useUmbrella:p,workflows:E}),Q={agents:t,functions:k,lazyFunctions:o,migrations:c,mutators:$,shapes:f,useUmbrella:p,usesSandbox:g},X=Jo(Q),te=Zo(Q),J=Wo({functions:C,useUmbrella:p}),le=v(a,"_generated",Mn),B=[[s,T],[i,J],[n,X],...Object.entries(te).map(([b,O])=>[v(le,b),O])];if(F>=fh||B.every(([b,O])=>oh(l,b,O)))return{apiContent:T,erased:ce,functions:C,functionModulesContent:te,functionsContent:X,httpRoutes:K,internalContent:J,mutators:$};for(const[b,O]of B)_e(l,b,O);({erased:ce,value:{functions:C,httpRoutes:K,mutators:$}}=V())}},Tv=e=>{const t=dh(),s=t?lt.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=v(n,"schema.ts");if(!M(o))throw new j("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??qr(n);Ar(jp);const c=wo(a,o,e.projectRoot);wm(c.tables,bm(a,n,Rn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:p,dependencies:E,entryCronTriggers:V,env:ce,featureUsage:C,hasFlags:K,hasNotify:$,identity:F,platformGate:k,queues:T,serverContent:Q,services:X,storageRulesMetadata:te,topics:J,usesSandbox:le,useUmbrella:B,workflows:b}=Cp({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Qp(c,c.jurisdiction===void 0?void 0:Gp(a,n));const O=v(n,"_generated"),D=v(O,"dataModel.ts"),Li=v(O,"server.ts"),Di=v(O,"api.ts"),Mi=v(O,"internal.ts"),_i=v(O,"functions.ts");_e(a,D,p),_e(a,Li,Q);const Jt=Object.fromEntries(X.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(fo(m,O))));for(const[m,ct]of Object.entries(Jt))_e(a,v(O,m),ct);const Pe=bo(a,n),de=Io(a,n),Zt=k.signals.typedWebSockets!==!1,{apiContent:es,erased:Ki,functions:re,functionModulesContent:ts,functionsContent:ss,httpRoutes:et,internalContent:ns,mutators:tt}=gh({agents:l,apiPath:Di,generatedFunctionsPath:_i,internalPath:Mi,lazyFunctions:i,roomsSupported:Zt,lunoraDirectory:n,migrations:Pe,project:a,shapes:de,useUmbrella:B,usesSandbox:le,workflows:b}),is=Br(a,n),st=zr(is,c,[...re,...et].map(m=>m.filePath)),we=is.length>0,Ie=e.lint===!1&&!we?void 0:{callEdges:$p(a,n),inserts:yo(a,n),queries:No(a,n,re),tableWrites:Dm(a,n),workflowCalls:th(a,n)},Ce=e.lint===!1||Ie===void 0?void 0:Dg(a,n,{callSites:Ie,containers:f,crons:g,functions:re,modules:st,mutators:tt,queues:T,schema:c,shapes:de,workflows:b,wranglerVariables:e.wranglerVariables}),rs=Ce===void 0?[]:Vg(e.projectRoot,[...Qi(Ce,{source:"static"}),...Jm(a,n,{byName:new Set([...b,...T,...l,...f].map(m=>m.exportName)),byPath:new Set([...re,...tt,...de,...Pe].map(m=>`${m.filePath}:${m.exportName}`))}),...Bm(a,n),...Eo(Ki,n),...Mo(T,e.wranglerQueueProducers)]),Bi=Po(a,n),os=tm(a,n);uh(de,os,Zp(a,n));const zi=K?qp(a,n):[],nt=k.signals.vectorStore!==!1,ge=Im(C,{containerCount:f.length,cronCount:g.length,dependencies:E,hasPaymentTables:im(c.tables),queueCount:T.length,storageColumnCount:Object.keys(Ln(c)).length,storageRuleCount:te.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Fn(e.projectRoot,e.target),vectorStoreSupported:nt,workflowCount:b.length}),as=t?lt.now():0,it=ko(c,Pe.map(m=>m.id)),cs=lo({advisories:rs.filter(m=>m.name!=="procedure_type_check_unavailable"),advisorProcedures:Ce?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:ce,flagKeys:zi,hasFlags:K,hasNotify:$,hasRooms:Zt&&re.some(m=>m.channel?.kind==="room"),lazyFunctions:i,hasVectors:nt,liveStreams:k.signals.liveStreams===!0,maskMetadata:os,mutators:tt,queues:T,rlsMetadata:Bi,schema:c,schemaSnapshot:it,shapes:de,services:X,storageRules:te,studioFeatures:ge,topics:J,useUmbrella:B,workflows:b}),ls=$o(de,E.has("@lunora/db"),B),ds=_o(f,c.jurisdiction),us=Ko(b),fs=Bo(l),gs=zo(T,e.wranglerQueueProducers),ps=qo(g),$i=jo(ge.scheduler),Vi=Ho(c.tables,B),Ui=xr(e.projectRoot)?Go(B):"",ms=Yo(c.vectorIndexes),Te=Xo(c,B),hs=Vo(E.has("@lunora/seed")),Oe=e.apiSpec??"openapi",rt=Oe==="openapi"||Oe==="both",ot=Oe==="openrpc"||Oe==="both",vs=To({capabilities:u,emailAgents:l.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:E.has("@lunora/cloudflare-access"),hasAuth:E.has("@lunora/auth"),hasFramework:E.has("@lunora/astro")||E.has("@lunora/svelte")||E.has("@lunora/vue")||M(v(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(m=>On(m)),hasHyperdriveGlobal:c.tables.some(m=>kn(m)),hasKvIntrospector:ge.kv,hasNotify:$,hasQueue:T.some(m=>m.mode==="push"),liveStreams:k.signals.liveStreams===!0,liveStreamsWithheld:k.liveStreamsWithheld,hasScheduler:ge.scheduler,hasSourcedTables:c.tables.some(m=>m.externalSource!==void 0),hasStorage:ge.storage,hasVectors:nt,hasWorkflow:b.length>0,identity:F,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(m=>({name:m.name,shardMode:m.shardMode})),useUmbrella:B,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:we,wantsOpenApi:rt,wantsOpenRpc:ot}),{openApiContent:Es,openApiModuleContent:xs,openRpcContent:Ss,openRpcModuleContent:As}=ch({functions:re,httpRoutes:et,modules:st,projectRoot:e.projectRoot,wantsArchitecture:we}),pe=we&&Ie!==void 0?np({...Ie,crons:g,functions:re,httpRoutes:et,modules:st,queues:T,schema:c,services:X,topics:J,workflows:b}):void 0,at=v(n,lh),Wi=M(at),qi=e.dryRun?[]:ah(O,[{content:vs,kind:"always",name:"app.ts"},{content:p,kind:"always",name:"dataModel.ts"},{content:es,kind:"always",name:"api.ts"},{content:ns,kind:"always",name:"internal.ts"},{content:Q,kind:"always",name:"server.ts"},{content:ss,kind:"always",name:"functions.ts"},{files:ts,kind:"directory",name:Mn},{content:cs,kind:"always",name:"shard.ts"},{content:ps,kind:"always",name:"crons.ts"},{content:ms,kind:"always",name:"vectors.ts"},{content:Te.global,kind:"always",name:"drizzle.global.ts"},{content:Te.shard,kind:"always",name:"drizzle.shard.ts"},{content:ds,kind:"optional",name:"containers.ts"},{content:us,kind:"optional",name:"workflows.ts"},{content:fs,kind:"optional",name:"agents.ts"},{content:gs,kind:"optional",name:"queues.ts"},{content:$i,kind:"optional",name:"scheduler.ts"},{content:Vi,kind:"optional",name:"shardRegistry.ts"},{content:Ui,kind:"optional",name:"durableObjects.ts"},{content:hs,kind:"optional",name:"seed.ts"},{content:ls,kind:"optional",name:"collections.ts"},{files:Jt,kind:"services"},{content:rt?Es:"",kind:"optional",name:"openapi.json"},{content:rt?xs:"",kind:"optional",name:"openapi.ts"},{content:ot?Ss:"",kind:"optional",name:"openrpc.json"},{content:ot?As:"",kind:"optional",name:"openrpc.ts"},{content:pe===void 0?"":`${JSON.stringify(pe,void 0,2)}
|
|
11
|
-
`,kind:"optional",name:"architecture.json"},{content:pe===void 0?"":ip(pe),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!Wi||e.updateSchemaBaseline===!0)&&Ne(at,Xi(it)),t){const m=lt.now(),ct=Math.round(m-s),ji=Math.round(as-s),Hi=Math.round(m-as);console.error(`@lunora/codegen: codegen took ${ct.toString()}ms (discovery ${ji.toString()}ms, emit ${Hi.toString()}ms)`)}return{advisories:rs,advisorContext:Ce,agents:l,architecture:pe,containers:f,cronTriggers:[...new Set([...Qo(g),...V])],generated:{agents:fs,api:es,app:vs,collections:ls,containers:ds,crons:ps,dataModel:p,drizzleGlobal:Te.global,drizzleShard:Te.shard,functionModules:ts,functions:ss,internal:ns,openApi:Es,openApiModule:xs,openRpc:Ss,openRpcModule:As,queues:gs,seed:hs,server:Q,shard:cs,vectors:ms,workflows:us},migrations:Pe,outputDirectory:O,platformDiagnostics:k.diagnostics,queues:T,schemaSnapshot:it,schemaSnapshotPath:at,workflows:b,writtenFiles:qi}};export{lh as SCHEMA_SNAPSHOT_FILENAME,qr as createCodegenProject,Rv as findTsconfig,Fv as refreshCodegenProject,Tv as runCodegen};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{SyntaxKind as c,Node as r}from"ts-morph";import{CAPABILITIES as m}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{bindingKeyName as p,listLunoraSourceFiles as g}from"./isTestPath-B81lOULB.mjs";import{scanImportDeclaration as u,noSandboxUsage as l}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";const d="ctx",E=(e,t,o)=>{for(const n of e.getDescendantsOfKind(c.ElementAccessExpression)){const s=n.getArgumentExpression();t(n.getExpression())&&s!==void 0&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s))&&o.add(s.getLiteralValue())}},x=e=>{const t=new Set,o=new Set([d]),n=i=>{if(r.isObjectBindingPattern(i))for(const a of i.getElements()){const f=p(a);f&&t.add(f)}};for(const i of e.getDescendantsOfKind(c.BindingElement)){if(p(i)!==d)continue;const a=i.getNameNode();r.isIdentifier(a)?o.add(a.getText()):n(a)}const s=i=>r.isIdentifier(i)&&o.has(i.getText());for(const i of e.getDescendantsOfKind(c.PropertyAccessExpression))s(i.getExpression())&&t.add(i.getName());E(e,s,t);for(const i of e.getDescendantsOfKind(c.VariableDeclaration)){const a=i.getInitializer();a!==void 0&&s(a)&&n(i.getNameNode())}return t},y=e=>{if(e.isTypeOnly())return!0;if(r.isExportDeclaration(e)){const o=e.getNamedExports();return!e.isNamespaceExport()&&o.length>0&&o.every(n=>n.isTypeOnly())}const t=e.getNamedImports();return e.getDefaultImport()===void 0&&e.getNamespaceImport()===void 0&&t.length>0&&t.every(o=>o.isTypeOnly())},N=new Map(m.flatMap(({bindingFreeExports:e,moduleSpecifier:t})=>e===void 0?[]:[[t,new Set(e)]])),I=(e,t)=>{const o=N.get(t);if(o===void 0||r.isImportDeclaration(e)&&(e.getDefaultImport()!==void 0||e.getNamespaceImport()!==void 0))return!1;const n=r.isExportDeclaration(e)?e.getNamedExports():e.getNamedImports();return n.length>0&&n.every(s=>s.isTypeOnly()||o.has(s.getName()))},S=e=>{const t=new Set;for(const o of e.getDescendantsOfKind(c.CallExpression)){const[n]=o.getArguments();o.getExpression().getKind()===c.ImportKeyword&&(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n))&&t.add(n.getLiteralValue())}return t},T=e=>{const t=e.getImportDeclarations(),o=l();for(const n of t){const s=u(n);for(const i of Object.keys(o))o[i]||=s[i]}return{contextReads:x(e),dynamicImports:S(e),sandboxTools:o,valueImports:new Set([...t,...e.getExportDeclarations()].flatMap(n=>{const s=n.getModuleSpecifierValue();return s===void 0||y(n)||I(n,s)?[]:[s]}))}},b=e=>{const t=new Set,o=new Set,n=l(),s=new Set;for(const i of e){for(const a of i.contextReads)t.add(a);for(const a of i.dynamicImports)o.add(a);for(const a of i.valueImports)s.add(a);for(const a of Object.keys(n))n[a]||=i.sandboxTools[a]}return{contextReads:t,dynamicImports:o,sandboxTools:n,valueImports:s}},O=e=>new Set(m.filter(({contextProperty:t,moduleSpecifier:o})=>e.valueImports.has(o)||t!==void 0&&e.contextReads.has(t)).map(({key:t})=>t)),v=new RegExp(String.raw`\b${d}\b`,"u"),w=new RegExp(String.raw`\b(?:${m.flatMap(({contextProperty:e})=>e===void 0?[]:[e]).join("|")})\b`,"u"),K=e=>v.test(e)&&w.test(e),L=(e,t)=>{const o=b(g(t).map(s=>T(e.getSourceFile(s)??e.addSourceFileAtPath(s)))),n=O(o);return Object.fromEntries(m.map(({key:s})=>[s,n.has(s)]))};export{O as capabilitiesUsedBy,x as contextPropertiesRead,L as discoverFeatureUsage,b as foldCapabilitySignals,K as mayReadCapabilityContext,T as sourceCapabilitySignals};
|