@lunora/codegen 1.0.0-alpha.93 → 1.0.0-alpha.94

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 CHANGED
@@ -1953,6 +1953,21 @@ interface ProjectIR {
1953
1953
  migrations: ReadonlyArray<MigrationIR>;
1954
1954
  schema: SchemaIR;
1955
1955
  }
1956
+ /**
1957
+ * One import of a migrated-away platform's SDK still present in `lunora/`
1958
+ * source. Structurally identical to the advisor's `AdvisorStaleMigrationImport`
1959
+ * so it passes through the feeder without conversion.
1960
+ */
1961
+ interface StaleMigrationImportIR {
1962
+ /** Source file relative to the lunora dir, no extension. */
1963
+ file: string;
1964
+ /** 1-based line of the import, or `0` when unknown. */
1965
+ line: number;
1966
+ /** The imported module, e.g. `@supabase/supabase-js`. */
1967
+ moduleSpecifier: string;
1968
+ /** Which migration guide covers this platform. */
1969
+ platform: "convex" | "firebase" | "supabase";
1970
+ }
1956
1971
  /**
1957
1972
  * Named inputs for {@link lintSchema}. Every feeder is a discrete key rather than
1958
1973
  * a positional argument: the feeder list grows every few releases and many IR
@@ -2009,6 +2024,7 @@ interface LintSchemaOptions {
2009
2024
  shapes?: ReadonlyArray<ShapeIR>;
2010
2025
  softDeleteReads?: ReadonlyArray<SoftDeleteReadIR>;
2011
2026
  sqlInterpolations?: ReadonlyArray<SqlInterpolationIR>;
2027
+ staleMigrationImports?: ReadonlyArray<StaleMigrationImportIR>;
2012
2028
  storageKeyAccesses?: ReadonlyArray<StorageKeyAccessIR>;
2013
2029
  storageUploads?: ReadonlyArray<StorageUploadIR>;
2014
2030
  unrestrictedWhereBranches?: ReadonlyArray<UnrestrictedWhereBranchIR>;
package/dist/index.d.ts CHANGED
@@ -1953,6 +1953,21 @@ interface ProjectIR {
1953
1953
  migrations: ReadonlyArray<MigrationIR>;
1954
1954
  schema: SchemaIR;
1955
1955
  }
1956
+ /**
1957
+ * One import of a migrated-away platform's SDK still present in `lunora/`
1958
+ * source. Structurally identical to the advisor's `AdvisorStaleMigrationImport`
1959
+ * so it passes through the feeder without conversion.
1960
+ */
1961
+ interface StaleMigrationImportIR {
1962
+ /** Source file relative to the lunora dir, no extension. */
1963
+ file: string;
1964
+ /** 1-based line of the import, or `0` when unknown. */
1965
+ line: number;
1966
+ /** The imported module, e.g. `@supabase/supabase-js`. */
1967
+ moduleSpecifier: string;
1968
+ /** Which migration guide covers this platform. */
1969
+ platform: "convex" | "firebase" | "supabase";
1970
+ }
1956
1971
  /**
1957
1972
  * Named inputs for {@link lintSchema}. Every feeder is a discrete key rather than
1958
1973
  * a positional argument: the feeder list grows every few releases and many IR
@@ -2009,6 +2024,7 @@ interface LintSchemaOptions {
2009
2024
  shapes?: ReadonlyArray<ShapeIR>;
2010
2025
  softDeleteReads?: ReadonlyArray<SoftDeleteReadIR>;
2011
2026
  sqlInterpolations?: ReadonlyArray<SqlInterpolationIR>;
2027
+ staleMigrationImports?: ReadonlyArray<StaleMigrationImportIR>;
2012
2028
  storageKeyAccesses?: ReadonlyArray<StorageKeyAccessIR>;
2013
2029
  storageUploads?: ReadonlyArray<StorageUploadIR>;
2014
2030
  unrestrictedWhereBranches?: ReadonlyArray<UnrestrictedWhereBranchIR>;
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-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as C}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as L,discoverFlags as _}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as T}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as D}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as H}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as y}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as V}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as k,discoverMutators as Q}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as B,discoverNotifyCalls as K,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as X}from"./packem_shared/discover-queries-i4Vd2si7.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as fe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as le}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,P as Re,B as ge,p as Ce,L as Me,R as he,C as Ie,V as Le,Q as _e,$ as Fe,E as Te,m as Pe,F as De}from"./packem_shared/emit-QxfTfRoJ.mjs";import{emitApp as He}from"./packem_shared/emitApp-Bh5Jv_9U.mjs";import{buildOpenApiDocument as ye,emitOpenApi as Ge,emitOpenApiModule as Ve}from"./packem_shared/buildOpenApiDocument-C-oA9yKS.mjs";import{OPENRPC_VERSION as ke,buildOpenRpcDocument as Qe,emitOpenRpc as je,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-5uSsJTUF.mjs";import{DEFAULT_TARGET as Be,platformMatrixIds as Ke,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Be67eKv7.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as fr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{redact as nr,secretKindOf as lr}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as Er,findSolutionByMessage as xr}from"@lunora/errors";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,Be as DEFAULT_TARGET,L as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Er as LUNORA_SOLUTION_RULES,k as MUTATORS_FILENAME,B as NOTIFY_FILENAME,ke as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,Qe as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,C as discoverContainers,h as discoverCrons,_ as discoverFlags,T as discoverFunctions,D as discoverHttpRoutes,H as discoverInserts,y as discoverMaskProcedures,V as discoverMigrations,Q as discoverMutators,z as discoverNondeterministicCalls,K as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,fe as discoverSchema,le as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,He as emitApp,ge as emitCollections,Ce as emitContainers,Me as emitCrons,he as emitDataModel,Ie as emitDrizzleSchema,Le as emitFunctions,Ge as emitOpenApi,Ve as emitOpenApiModule,je as emitOpenRpc,ze as emitOpenRpcModule,_e as emitServer,Fe as emitShard,Te as emitVectors,Pe as emitWorkflows,De as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,xr as findLunoraSolution,m as formatAdvisories,d as lintSchema,ar as parseSchemaSnapshot,Ke as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,nr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,lr as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,fr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as C}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as L,discoverFlags as _}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as T}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as D}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as H}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as y}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as V}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as k,discoverMutators as Q}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as B,discoverNotifyCalls as K,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as X}from"./packem_shared/discover-queries-i4Vd2si7.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as fe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as le}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,P as Re,B as ge,p as Ce,L as Me,R as he,C as Ie,V as Le,Q as _e,$ as Fe,E as Te,m as Pe,F as De}from"./packem_shared/emit-QxfTfRoJ.mjs";import{emitApp as He}from"./packem_shared/emitApp-Fnuxk68h.mjs";import{buildOpenApiDocument as ye,emitOpenApi as Ge,emitOpenApiModule as Ve}from"./packem_shared/buildOpenApiDocument-C-oA9yKS.mjs";import{OPENRPC_VERSION as ke,buildOpenRpcDocument as Qe,emitOpenRpc as je,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-5uSsJTUF.mjs";import{DEFAULT_TARGET as Be,platformMatrixIds as Ke,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BaZ2lWSm.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as fr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{redact as nr,secretKindOf as lr}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as Er,findSolutionByMessage as xr}from"@lunora/errors";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,Be as DEFAULT_TARGET,L as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Er as LUNORA_SOLUTION_RULES,k as MUTATORS_FILENAME,B as NOTIFY_FILENAME,ke as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,Qe as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,C as discoverContainers,h as discoverCrons,_ as discoverFlags,T as discoverFunctions,D as discoverHttpRoutes,H as discoverInserts,y as discoverMaskProcedures,V as discoverMigrations,Q as discoverMutators,z as discoverNondeterministicCalls,K as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,fe as discoverSchema,le as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,He as emitApp,ge as emitCollections,Ce as emitContainers,Me as emitCrons,he as emitDataModel,Ie as emitDrizzleSchema,Le as emitFunctions,Ge as emitOpenApi,Ve as emitOpenApiModule,je as emitOpenRpc,ze as emitOpenRpcModule,_e as emitServer,Fe as emitShard,Te as emitVectors,Pe as emitWorkflows,De as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,xr as findLunoraSolution,m as formatAdvisories,d as lintSchema,ar as parseSchemaSnapshot,Ke as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,nr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,lr as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,fr as validatorIrToJsonSchema};
@@ -0,0 +1,9 @@
1
+ import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,P as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,M as ls,F as us}from"./emit-QxfTfRoJ.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,y as Ss}from"./discover-queries-i4Vd2si7.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Os from"./discoverInserts-D6szWzrV.mjs";import Cs,{discoverMaskStrategies as Fs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-Fnuxk68h.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-C-oA9yKS.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-5uSsJTUF.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
2
+ `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
+ ${r}
4
+
5
+ Install them with your package manager, then re-run codegen.`)},lr="env.ts",ur=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},gr=e=>{if(o.isIdentifier(e))return ur(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&dr(t)}return!1},pr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!gr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},fr=(e,t)=>{const s=g(t,lr);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=pr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},mr=e=>{const t=r=>o.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getInitializer(),n=r.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(n)))for(const a of n.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},hr=(e,t)=>{const s=Object.fromEntries(de.map(r=>[r.key,!1]));for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=mr(i);for(const c of de)if(!s[c.key]){if(n.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(de.every(c=>s[c.key]))break}return s},xr=["providerSubscriptionId","state"],Er=["providerEventId","processedAt"],He=(e,t)=>t.every(s=>s in e.shape),yr=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&He(t,xr)&&He(s,Er)},$r=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),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/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),ht="identity.ts",vr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},br=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},Nr=e=>{if(o.isIdentifier(e))return vr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&br(t)}return!1},Sr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!Nr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Ar=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Sr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},wr=(e,t)=>{const s=new Map,r=new Map,i=new Map;for(const n of e)s.set(n.name,`workflow "${n.exportName}"`),r.set(n.bindingName,`workflow "${n.exportName}"`),i.set(n.className,`workflow "${n.exportName}"`);for(const n of t){const a=s.get(n.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${n.name}": produced by both ${a} and agent "${n.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(n.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${n.bindingName}": produced by both ${c} and agent "${n.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(n.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${n.className}": produced by both ${u} and agent "${n.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Pr=e=>{const{lunoraDirectory:t,project:s,projectRoot:r,schema:i}=e,n=Ar(s,t),a=fr(s,t),c=xs(s,t),u=fs(s,t),d=Gt(s,t);wr(c,d);const y=Ht(s,t),w=hs(s,t),p=Es(hr(s,t),ys(r,e.target)),v=p.usage,C=ms(s,t),j=v.browser||C.usesSandboxBrowser,z=ps(r),U=z??new Set,T=U.has("lunorash");cr(i,z);const F=b(g(t,"flags.ts")),q=b(g(t,"notify.ts"));return{agents:d,containers:y,dataModelContent:Jt(i),declaredDependencies:z,dependencies:U,env:a,featureUsage:v,hasBrowser:j,hasFlags:F,hasNotify:q,identity:n,platformGate:p,queues:u,serverContent:Qt({agents:d,containers:y,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:j,hasFlags:F,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:q,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:n,queues:u,schema:i,storageRuleBuckets:w.rules.map(se=>se.bucket),useUmbrella:T,workflows:c}),storageRulesMetadata:w,usesSandbox:C.usesSandboxBrowser||C.usesSandboxContainer,useUmbrella:T,workflows:c}},xt=new Set(["delete","get","head","options","patch","post","put"]),Ir=new Set(["handler","stream"]),Tr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Qe=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Lr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!o.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},kr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return Lr(s)},Dr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Qe.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&Qe.has(s.getText()))return!0}return!1},Or=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||!Ir.has(r.getName()))return;const i=kr(s);if(!i||!Tr.test(i.path))return;const n=s.getArguments()[0],a=n!==void 0&&(o.isArrowFunction(n)||o.isFunctionExpression(n))&&Dr(n);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Cr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=Or(i,t);n&&s.push(n)}return s},Fr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Cr(i,E(t,r)))}return s},Kr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Rr=(e,t)=>{if(!Kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)||D(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Mr=(e,t)=>N(e,t,Rr),jr=new Set(["generateText","streamText"]),zr=new Set(["messages","prompt","system"]),qr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Br=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const i of qr)if(i.methods.has(s)&&i.prefixes.some(n=>r===n||r.startsWith(`${n}.`)))return`${r}.${s}`},Ur=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Br(t);if(s!==void 0)return s}},Vr=e=>{const t=new Set,s=e.getFirstAncestor(n=>o.isArrowFunction(n)||o.isFunctionExpression(n)||o.isFunctionDeclaration(n)),[r]=s?.getParameters()??[],i=r?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const n of i.getElements()){const a=n.getPropertyNameNode()?.getText()??n.getName(),c=n.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Wr=e=>{if($s(e))return!0;const t=Vr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},_r=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!zr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Wr(s))return!0}return!1},Gr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());if(i===void 0||!jr.has(i))continue;const[n]=r.getArguments();if(n===void 0||!o.isObjectLiteralExpression(n))continue;let a;for(const c of n.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=Ur(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(r),file:t,line:r.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:_r(n)})}return s},Hr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Gr(i,E(t,r)))}return s},Qr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},Jr=(e,t)=>{if(!Qr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Xr=(e,t)=>N(e,t,Jr),Et=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),Zr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!o.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:Et(r)}},Yr=e=>{const t=[];let s=!1,r=e;for(;o.isCallExpression(r);){const i=r.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&o.isObjectLiteralExpression(n)?(t.push(n),s||=Et(n)):s=!0}r=i.getExpression()}return{objects:t,opaque:s}},yt=(e,t)=>t?Yr(t):Zr(e),en=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),tn=/\.check\(|\.meta\(|length|max/iu,sn=/\bv\.any\s*\(/u,rn=/\bv\.string\s*\(/u,nn=e=>sn.test(e),on=e=>rn.test(e)&&!tn.test(e),an=e=>{const t=[],s=[];for(const r of e)for(const i of r.getProperties()){if(!o.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!n)continue;const a=n.getText(),c=i.getName();nn(a)?t.push(c):on(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},cn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(r?.visibility!=="public")return;const{objects:i}=yt(s,r.receiver),{anyArgs:n,unboundedStringArgs:a}=an(i);if(!(n.length===0&&a.length===0))return{anyArgs:n,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},ln=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=cn(i,t);n&&s.push(n)}return s},un=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ln(i,E(t,r)))}return s},ge=e=>e?.getKind()===l.TrueKeyword,dn=e=>e?.getKind()===l.FalseKeyword,gn=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,pn=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),fn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),mn=e=>e!==void 0&&o.isCallExpression(e)&&pn.has(A(e.getExpression())??""),hn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),xn=e=>{const t=$(e,"advanced"),s=$(e,"emailAndPassword"),r=$(e,"session");return{analyzable:!0,disableCsrfCheck:ge($(t,"disableCSRFCheck")),emailPasswordEnabled:ge($(s,"enabled")),requireEmailVerification:ge($(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:fn($(e,"plugins"))&&mn($(e,"database")),secureCookiesDisabled:dn($(t,"useSecureCookies")),sessionFreshAgeZero:gn($(r,"freshAge")),trustedOriginsWildcard:hn($(e,"trustedOrigins"))}},En=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),yn=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(n=>o.isSpreadAssignment(n)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!r?xn(s):En();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...i}},$n=(e,t)=>N(e,t,yn),vn=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},bn=(e,t,s)=>{const r=vn(e.getExpression(),s);if(r===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!I(i)||D(i))&&!(s.requireUnmodifiedReach===!0&&!vs(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:r}},Nn=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const n=bn(i,t,s);n&&r.push(n)}return r},te=(e,t,s)=>{const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...Nn(n,E(t,i),s))}return r},Sn=new Set(["content","pdf","scrape","screenshot"]),An=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Sn}),wn=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Pn=new Set(["RateLimiter"]),In=new Set(["extend"]),$t=e=>{const t=[],s=[];let r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(n);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},Je=e=>e&&o.isObjectLiteralExpression(e)?$t(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Tn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&o.isObjectLiteralExpression(r)?r:void 0},Ln=e=>{if(o.isObjectLiteralExpression(e))return e;if(o.isParenthesizedExpression(e)){const t=e.getExpression();return o.isObjectLiteralExpression(t)?t:void 0}return o.isBlock(e)?Tn(e):void 0},kn=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&Ln(t.getBody());return s?$t(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());i!==void 0&&(wn.has(i)?s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])}):In.has(i)&&s.push({callee:i,file:t,line:r.getStartLineNumber(),...kn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(l.NewExpression)){const i=A(r.getExpression());i===void 0||!Pn.has(i)||s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])})}return s},On=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(i,E(t,r)))}return s},Xe="ctx.containers.",Cn=e=>{if(!e.startsWith(Xe))return!1;const t=e.slice(Xe.length);return t.length>0&&!t.includes(".")},Fn=(e,t)=>te(e,t,{argIndex:0,matchReceiver:Cn,methods:new Set(["get"])}),Kn=new Set(["allow","deny","setAllowed"]),Rn=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Mn=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Rn(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},jn=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Kn.has(s.getName()))return;const r=s.getExpression();if(!(!o.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},zn=(e,t)=>Mn(e,t)??jn(e,t),qn=(e,t)=>N(e,t,zn),Bn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Un=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Bn.has(s)?s:void 0},Vn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(o.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(r)){const i=r.getName();t.push(i);const n=r.getInitializer();n&&o.isStringLiteral(n)&&n.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r)||o.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Wn=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=Un(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?Vn(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},_n=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Gn=new Set(["dbRateLimit","rateLimit"]),Hn=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Qn=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const r=_n.get(s);if(r!==void 0)return{callee:s,exportName:x(e),failOpen:Hn(e.getArguments()[r]),file:t,limitName:Gn.has(s)?gt(e):"",line:e.getStartLineNumber()}},Jn=(e,t)=>N(e,t,Qn),Xn=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ds(t.getExpression())},Zn=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Yn=(e,t)=>{if(!Xn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),n=Zn(r);if(!(i.length===0||n===void 0))return{defaultValue:n,exportName:x(e),file:t,key:i,line:e.getStartLineNumber()}},ei=(e,t)=>N(e,t,Yn),ti=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},si=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ri=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression))ti(a)&&s.push({file:n,indexName:si(a),line:a.getStartLineNumber()})}return s},ni=new Set(["delete","get","head","options","patch","post","put"]),ii=new Set(["handler","stream"]),oi=new Set(["runAction","runMutation"]),ai=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,Ze=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,Ye=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return o.isIdentifier(r)?r.getText():void 0;if(o.isObjectBindingPattern(r)){for(const i of r.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const n=i.getNameNode();return o.isIdentifier(n)?n.getText():void 0}}},et=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&r.unshift(s);for(const i of r){const n=i.getExpression();if(!o.isPropertyAccessExpression(n))continue;const a=n.getName(),c=n.getExpression();if(oi.has(a)&&Q(c,t))return a;if(ai.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},tt=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(l.PropertyAccessExpression))if(r.getName()==="auth"&&Q(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getNameNode();if(!(!o.isObjectBindingPattern(i)||!Q(r.getInitializer(),t))){for(const n of i.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="auth")return!0}}return!1},ci=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ii.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))return;const i=r.getName();if(ni.has(i)){const n=r.getExpression();return o.isIdentifier(n)&&n.getText()==="httpRoute"?i.toUpperCase():void 0}s=r.getExpression()}},li=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ze(e.getArguments()[0]),u=c&&Ye(c,!0);if(!c||u===void 0)return;const d=et(c,u);return d===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:tt(c,u),sideEffect:d}}const r=ci(e);if(r===void 0)return;const i=Ze(e.getArguments()[0]),n=i&&Ye(i,!1);if(!i||n===void 0)return;const a=et(i,n);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:tt(i,n),sideEffect:a}},ui=(e,t)=>N(e,t,li),di=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),gi=new Set(["append","set"]),he=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():"",vt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",st=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(s=>di.has(he(s.getExpression()))&&Ns(s,t)),pi=(e,t)=>{if(st(e,t))return!0;const s=ee(e);return s!==void 0&&st(s,t)},me=(e,t)=>bs(e,t)&&!pi(e,t),fi=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ee(e);return t!==void 0&&o.isNewExpression(t)&&he(t.getExpression())==="Headers"},J=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ee(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},xe=(e,t,s)=>{for(const r of e.getProperties())if(o.isPropertyAssignment(r)){const i=r.getInitializer();i!==void 0&&me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:vt(r.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(r)){const i=r.getNameNode();me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(r)){const i=J(r.getExpression());i!==void 0&&xe(i,t,s)}},bt=(e,t)=>{const s=J(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!o.isPropertyAssignment(r))return;const i=J(r.getInitializer());i!==void 0&&xe(i,"response-init",t)},mi=(e,t)=>{const s=he(e.getExpression());if(s==="Response")bt(e.getArguments()[1],t);else if(s==="Headers"){const r=J(e.getArguments()[0]);r!==void 0&&xe(r,"headers-ctor",t)}},hi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const r=s.getName(),i=s.getExpression();if(r==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){bt(e.getArguments()[1],t);return}if(gi.has(r)&&fi(i)){const n=e.getArguments()[1];n!==void 0&&me(n,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:vt(e.getArguments()[0]),line:n.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},xi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))mi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))hi(s,t)},Ei=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=As(e.getArguments()[0]);if(r===void 0)return[];const i=r.getParameters()[1];if(i===void 0)return[];const n=i.getNameNode();if(!o.isIdentifier(n))return[];const a=[];return xi(r,{exportName:x(e),relativePath:t,requestName:n.getText(),rows:a}),a},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression))s.push(...Ei(r,t));return s},$i=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(i,E(t,r)))}return s},vi=new Set(["auth","context.auth","ctx.auth"]),bi="userId",Ni=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},Si=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of r.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[n]=i.getArguments();return n&&o.isObjectLiteralExpression(n)?Ni(n):void 0}},rt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return vi.has(e.getExpression().getText())?e:void 0},Ai=e=>{if(o.isPropertyAccessExpression(e)&&rt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&rt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},wi=(e,t,s)=>{const r=[];for(const i of e.getDescendants()){const n=Ai(i);n!==void 0&&r.push({declared:n===bi||s.has(n),exportName:x(i),file:t,key:n,line:i.getStartLineNumber()})}return r},Pi=(e,t)=>{const s=Si(e,t);if(s===void 0)return[];const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...wi(n,E(t,i),s))}return r},Ii=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=$(s,"key");if(!(!r||!I(r)||D(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Ti=(e,t)=>N(e,t,Ii),Li=new Set(["delete","get","getRaw","getWithMetadata","put"]),ki=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Li}),Di=new Set(["queue","send"]),nt=new Set(["bcc","cc","to"]),Oi=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Di.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Ci=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return nt.has(t.getName())&&I(r)&&!D(r)}if(!o.isPropertyAssignment(t)||!nt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&I(s)&&!D(s)}):!1,Fi=(e,t)=>{const s=Oi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Ci(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Ki=(e,t)=>N(e,t,Fi),Ri=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Mi=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},ji=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return zs(s.getExpression())?s:void 0},zi=e=>{const t=ji(e),s=t===void 0?void 0:Mi(t);if(s===void 0)return[];const r=e.getNameNode(),i=o.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(n=>Ri(n)).map(n=>({exportName:i,file:"lunora/mutators.ts",line:n.getStartLineNumber()}))},qi=e=>e.getVariableDeclarations().flatMap(t=>zi(t)),Bi=(e,t)=>{const s=g(t,js);if(!b(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return qi(r)},Ui=new Set(["delete","get","patch"]),Vi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Wi=new Set(["auth","identity","session","user"]),_i=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Gi=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!R(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},Hi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const r=s.getNameNode();return o.isIdentifier(r)?r.getText():void 0},Qi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ji=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Xi=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Qi(s.getExpression(),t)&&Ji(s.getThenStatement())),Zi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))continue;const i=r.getName();if(!Ui.has(i))continue;const n=r.getExpression();if(!(R(n)||o.isPropertyAccessExpression(n)&&R(n.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&o.isIdentifier(a)&&a.getText()===t)return i}},Yi=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},eo=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Yi(s)==="ctx")),to=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>_i.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),so=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Vi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Wi.has(t.getName()))return!0}return eo(e)||to(e)},ro=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=so(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const y=Gi(d);if(y===void 0)continue;const w=Hi(d);if(w===void 0||c.has(w)||!Xi(i,w))continue;const p=Zi(i,w);p!==void 0&&(c.add(w),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:y,usesRls:n,visibility:r.visibility}))}return u},no=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ro(c,n))}return s},io=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),oo=new Set(["insert","insertManyUnsafe","patch","replace"]),ao=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!oo.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},co=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())o.isObjectLiteralExpression(r)&&s.push(r);return s},lo=(e,t,s,r)=>{const i=[];for(const n of e.getProperties()){let a,c;o.isPropertyAssignment(n)?(a=n.getName(),c=n.getInitializer()):o.isShorthandPropertyAssignment(n)&&(a=n.getName(),c=n.getNameNode()),!(a===void 0||c===void 0||!io.has(a))&&I(c)&&!D(c)&&i.push({exportName:x(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return i},uo=(e,t)=>{const s=ao(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?co(r,s).flatMap(i=>lo(i,s,e,t)):[]},go=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const n of uo(i,t)){const a=s(n.exportName);r.push(a===void 0?n:{...n,visibility:a})}return r},po=(e,t,s=[])=>{const r=[],i=new Map(s.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));for(const n of h(t)){const a=e.getSourceFile(n)??e.addSourceFileAtPath(n),c=E(t,n);r.push(...go(a,c,u=>i.get(`${c}:${u}`)))}return r},fo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?mo(t.getInitializer()):void 0},xo=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!fo.has(s))return;const[r]=e.getArguments(),i=r&&o.isObjectLiteralExpression(r)?ho(r):void 0;return{callee:s,exportName:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Eo=(e,t)=>N(e,t,xo),yo=new Set(["defineQueue","defineWorkflow"]),$o=new Set(["run","runAction","runMutation","runQuery"]),vo=new Set(["api","internal"]),bo=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},No=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(o.isArrowFunction(r)||o.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},St=(e,t)=>e===t||e.startsWith(`${t}.`),At=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},it=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},wt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>it(s));return o.isIdentifier(e)&&it(e)&&t.push(e),t},So=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Ao=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(l.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const i=r.getInitializer(),n=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;n&&o.isIdentifier(n)&&s.push(`${n.getText()}.body`)}return s},wo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:Ao(e),i=new Set,n=a=>At(a).some(c=>r.some(u=>St(c.getText(),u)))?!0:wt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&n(c))for(const u of So(a))i.add(u)}return{names:i,prefixes:r}},Po=(e,t)=>At(e).some(s=>t.prefixes.some(r=>St(s.getText(),r)))?!0:wt(e).some(s=>t.names.has(s.getText())),Io=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!o.isIdentifier(s)||!vo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},To=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const i=wo(e,t,r),n=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!$o.has(c.getName())||c.getExpression().getText()!==r)continue;const u=a.getArguments()[1];if(!u||!Po(u,i))continue;const d=Io(a.getArguments()[0]);d!==void 0&&n.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return n},Lo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=bo(r);if(i===void 0||!yo.has(i))continue;const n=No(r);n!==void 0&&s.push(...To(n,i==="defineQueue"?"queue":"workflow",t))}return s},ko=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Lo(i,E(t,r)))}return s},ot={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},at=new Set(["account","credential","member","passkey","session","user"]),Do=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Oo=e=>{const t=Do(e).at(-1);if(!t)return!1;const s=t.endsWith("s")?t.slice(0,-1):t;return at.has(t)||at.has(s)},Co=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Fo=(e,t)=>{const{objects:s,opaque:r}=yt(e,t);return en(s).some(i=>Co(i))?!0:r?void 0:!1},Ee=e=>{const t=e.getExpression();if(o.isIdentifier(t))return t.getText();if(o.isPropertyAccessExpression(t))return t.getName()},Ko=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ro=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&o.isCallExpression(t)?t:void 0},H={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mo=e=>{const t=Ro(e),s=t?Ee(t):void 0;if(t&&s==="protectPublic"){const r=Ko(t);return{...H,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in ot?{...H,[ot[s]]:!0}:H},jo=e=>{const t={...H};let s=e;for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))break;const i=r.getName()==="use"?s.getArguments()[0]:void 0;if(i){const n=Mo(i);t.usesCaptcha||=n.usesCaptcha,t.usesEmailGate||=n.usesEmailGate,t.usesMask||=n.usesMask,t.usesRateLimit||=n.usesRateLimit,t.usesRls||=n.usesRls}s=r.getExpression()}return t},zo=new Set(["insert","insertMany","insertManyUnsafe","replace"]),qo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!zo.has(t.getName()))return!1;const s=t.getExpression();if(!(o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!r||!(o.isStringLiteral(r)||o.isNoSubstitutionTemplateLiteral(r))?!1:Oo(r.getLiteralText())},Bo=new Set(["create","runAfter","runAt","send","sendBatch"]),Uo=new Set(["queues","scheduler","workflows"]),Vo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Bo.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Uo.has(s.getName())){const r=s.getExpression();if(o.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Pt=new Set(["generateObject","generateText","streamObject","streamText"]),_o=e=>{const t=Ee(e);return t!==void 0&&Pt.has(t)},Go=e=>{const t=Ee(e);if(t===void 0||!Pt.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(r=>o.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Ho=new Set(["log","span","trace"]),Qo=new Set(["ai"]),Jo=new Set(["email","mail"]),Xo=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),pe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"}),Zo=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Yo=new Set(["every","filter","flatMap","forEach","map","some"]),ea=new Set(["all","allSettled","race"]),ta=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const r=s.getName();if(Yo.has(r))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&ea.has(r))return t},sa=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Zo.has(t.getKind())){const s=ta(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},ra=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const r=s.getParent();if(!o.isCallExpression(r)||r.getExpression()!==s)return!1;t=r}},na=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ia=e=>{let t=!1,s=!0;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Xo.has(r.getName()))continue;const i=r.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const n=na(r);n&&(t=!0,!sa(n)&&!ra(n)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},oa=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="Error"}),ct="lunora-advisor-exempt",aa=/^[\s*/]+/u,ca=/[\w-]/u,la=e=>{const t=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
6
+ `);for(const s of t.split(`
7
+ `)){const r=s.replace(aa,"");if(!r.startsWith(ct))continue;const i=r.slice(ct.length);if(ca.test(i.charAt(0)))continue;const n=i.indexOf("--");return{exempt:!0,exemptReason:(n===-1?"":i.slice(n+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},ua=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},da=(e,t)=>{const s=ua(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const r=s.getSourceFile(),i=s.getText(),n=r.getVariableDeclaration(i)?.getInitializer();return n&&(o.isArrowFunction(n)||o.isFunctionExpression(n))?n:r.getFunction(i)},ga=e=>{let t=!1,s=!1,r=!1,i=!1,n=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(qo(u)&&(n=!0),Vo(u)&&(t=!0),Wo(u)&&(i=!0),_o(u)&&(s=!0),Go(u)&&(r=!0),n&&t&&i&&r)break;const{handlesErrors:a,reachesOutbound:c}=ia(e);return{callsMail:pe(e,Jo),emitsEvent:pe(e,Ho),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||pe(e,Qo),throwsBareError:oa(e),unboundedAiGeneration:r,usesInsertManyUnsafe:i,writesUserTable:n}},pa=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const i=r.receiver?jo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},n=da(e,s);return{...n?ga(n):{},...la(e),...i,analyzableBody:n!==void 0,exportName:e.getName(),file:t,hasEmailArg:Fo(s,r.receiver),kind:r.kind,visibility:r.visibility}},fa=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=pa(i,t);n&&s.push(n)}return s},ma=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fa(i,E(t,r)))}return s},ha=new Set(["dbRateLimit","rateLimit"]),xa=e=>o.isArrowFunction(e)?e.getBody():e,Ea=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!ha.has(s))return;const r=e.getArguments()[2];if(!r)return;const i=$(r,"key");if(!i)return;const n=xa(i);if(!(!I(n)||D(n)))return{callee:s,exportName:x(e),file:t,limitName:gt(e),line:e.getStartLineNumber()}},ya=(e,t)=>N(e,t,Ea),$a=new Set(["findFirst","findFirstOrThrow","findMany","get"]),va=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!$a.has(t.getName()))return;const s=t.getExpression();if(R(s)){const r=e.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&R(s.getExpression()))return s.getName()},ba=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&R(s.getExpression())){const r=t.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Na=e=>{let t=e;for(;o.isAwaitExpression(t)||o.isParenthesizedExpression(t)||o.isNonNullExpression(t)||o.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=Na(e);if(o.isIdentifier(s)){if(t)return;const r=ee(s);return r===void 0?void 0:It(r,!0)}if(o.isCallExpression(s))return va(s)??ba(s)},Sa=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(l.ReturnStatement)){const i=r.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),n=r.getExpression();i===e&&n!==void 0&&s.push(n)}return s},Aa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&ws(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,u=[];for(const d of Sa(i)){const y=It(d);y===void 0||c.has(y)||(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:y,usesMask:a,usesOutput:n,visibility:r.visibility}))}return u},wa=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Aa(c,n))}return s},Pa=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Ia=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=Pa($(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:n.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return i},Ta=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,n))}return s},X=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=X(e.getLeft()),s=X(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},La=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&X(t)!==void 0},ka=/(?:^|\/)__tests__\//u,Da=/\.(?:spec|test)$/u,Oa=e=>ka.test(e)||Da.test(e),Ca=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Fa=(e,t,s)=>Xs(e)?!Oa(s)&&Zs(Ca(t)):!0,Ka=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const n of r){if(La(n))continue;const a=X(n);if(a===void 0)continue;const c=Qs(a);if(c===void 0||!Fa(c,n,t))continue;const u=n.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Js(a)}))}return s},Ra=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ka(i,E(t,r)))}return s},Ma=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=$(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&I(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:n.getStartLineNumber(),table:a.table,visibility:r.visibility})}return i},ja=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ma(c,n))}return s},za=new Set(["query","unsafe"]),qa=e=>{if(!o.isPropertyAccessExpression(e)||!za.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},Ba=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Ua=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Va=(e,t)=>{if(!qa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ba(s)))return{exportName:Ua(e),file:t,line:s.getStartLineNumber()}},Wa=(e,t)=>N(e,t,Va),_a=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ga=e=>{for(const[t,s]of _a)for(const r of s)if(e===r||e.startsWith(r.endsWith("/")?r:`${r}/`))return t},Ha=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of i.getImportDeclarations()){const a=n.getModuleSpecifierValue(),c=Ga(a);c!==void 0&&s.push({file:E(t,r),line:n.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Qa=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ja=(e,t,s=[])=>{const r=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return te(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Qa,requireUnmodifiedReach:!0}).map(i=>{const n=r.get(`${i.file}:${i.exportName}`);return n===void 0?i:{...i,visibility:n}})},Xa=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Za=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ya=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),n==="expiresInSeconds"&&(s=Za(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},ec=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Xa.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},tc=(e,t)=>{const s=ec(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ya(e.getArguments()[s.optionsIndex])}},sc=(e,t)=>N(e,t,tc),rc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),ye=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&rc.has(s)?s:void 0},Tt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Lt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},nc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},$e=(e,t,s,r,i)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${r.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${i.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),ic=(e,t,s)=>{const r=[];for(const i of e.getVariableStatements().filter(n=>n.isExported()))for(const n of i.getDeclarations()){const a=n.getName();if(s.has(`${t}:${a}`)||!Tt(n))continue;const c=ye(n);c!==void 0&&r.push($e(t,a,c,n.getStartLineNumber(),Lt))}return r},oc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const i of e.getExportAssignments().filter(n=>!n.isExportEquals())){const n=ye(i.getExpression());n!==void 0&&r.push($e(t,"default",n,i.getStartLineNumber(),Lt))}return r},ac=(e,t,s)=>{const r=[];for(const i of e.getExportDeclarations().filter(n=>n.getModuleSpecifier()===void 0))for(const n of i.getNamedExports()){const a=n.getAliasNode()?.getText()??n.getName();if(s.has(`${t}:${a}`))continue;const c=n.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Tt(c))continue;const u=ye(c);u!==void 0&&r.push($e(t,a,u,n.getStartLineNumber(),nc))}return r},cc=(e,t,s)=>[...ic(e,t,s),...oc(e,t,s),...ac(e,t,s)],lc=(e,t,s)=>{const r=new Set(s.map(n=>`${n.filePath}:${n.exportName}`)),i=[];for(const n of h(t)){const a=e.getSourceFile(n);a!==void 0&&i.push(...cc(a,E(t,n),r))}return i.toSorted((n,a)=>n.cacheKey.localeCompare(a.cacheKey))},uc=new Set(["when","where"]),fe=new Set(["definePolicy","defineShape"]),dc=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const r=t.getName();return fe.has(r)?r:void 0}if(!o.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(r)){const i=r.getNameNode().getText();return fe.has(i)?i:void 0}const s=t.getText();return fe.has(s)?s:void 0},gc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,kt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(gc(e))return"empty-object";if(o.isParenthesizedExpression(e))return kt(e.getExpression())}},Dt=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Ot=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Dt(t)===e),Ct=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Dt(t)===e),pc=e=>{const t=Ot(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Ct(e).length>0},fc=e=>{const t=[],s=e.getBody();o.isBlock(s)||t.push(s);for(const r of Ot(e)){const i=o.isReturnStatement(r)?r.getExpression():void 0;t.push(i??r)}for(const r of Ct(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},mc=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},hc=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!o.isObjectLiteralExpression(r))return[];const i=[];for(const n of r.getProperties()){if(!o.isPropertyAssignment(n)||!uc.has(n.getName()))continue;const a=n.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&pc(a))for(const c of fc(a)){const u=kt(c);u!==void 0&&i.push({exportName:mc(e),file:s,form:u,key:n.getName(),line:c.getStartLineNumber(),owner:t})}}return i},xc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=dc(r);i!==void 0&&s.push(...hc(r,i,t))}return s},Ec=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xc(i,E(t,r)))}return s},yc=new Set(["query","upsert","upsertMany"]),$c=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(yc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},vc=(e,t)=>{const s=$c(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const i=$(r,"namespace");if(!(!i||!I(i)||D(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},bc=(e,t)=>N(e,t,vc),Nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},Sc=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ac=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Nc(a))continue;const c=gs(a);c!==""&&s.push({exportName:c,file:n,line:a.getStartLineNumber(),workflow:Sc(a)})}}return s},wc=".lunora-schema.json",S=(e,t)=>{b(e)&&dt(e,"utf8")===t||Bt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}S(e,t)},Pc=e=>{const t=g(e,"package.json");if(b(t))try{const s=JSON.parse(dt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Ic=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Tc=e=>{let t=b(e)?e:le(e);for(;t&&t!==le(t);){const s=g(t,"tsconfig.json");if(b(s))return s;t=le(t)}},lt=e=>e.replaceAll("\\","/"),Lc=(e,t,s)=>{if(s&&e.length>0){const n=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("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) (${n}), 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 r=new Map;for(const n of t.columns){const a=r.get(n.table)??[];a.push(n.column),r.set(n.table,a)}const i=t.columns.length>0;for(const n of e){if(n.table===void 0){if(i)throw new k("MASK_UNSUPPORTED",`defineShape "${n.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 "${n.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=r.get(n.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${n.exportName}" replicates table "${n.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})}},ut=(e,t,s)=>{const r=e.getSourceFile(t);if(r===void 0){e.createSourceFile(t,s,{overwrite:!0});return}r.getFullText()!==s&&r.replaceWithText(s)},kc=e=>{const t=Tc(e);return t?new Ge({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ge({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},$l=(e,t)=>{const s=h(t),r=g(t,"schema.ts");b(r)&&s.push(r);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>lt(c))),n=lt(t),a=`${n}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===n||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}},vl=e=>{const t=Ic(),s=t?ue.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),i=g(r,"schema.ts");if(!b(i))throw new k("INTERNAL",`schema.ts not found at ${i}`);const n=e.project??kc(r);ir(Is);const a=Hs(n,i,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:y,env:w,featureUsage:p,hasBrowser:v,hasFlags:C,hasNotify:j,identity:z,platformGate:U,queues:T,serverContent:F,storageRulesMetadata:q,usesSandbox:se,useUmbrella:K,workflows:L}=Pr({lunoraDirectory:r,project:n,projectRoot:e.projectRoot,schema:a,target:e.target}),f=g(r,"_generated"),ve=g(f,"dataModel.ts"),be=g(f,"server.ts");ut(n,ve,d),ut(n,be,F);const O=Ps(n,r),Ne=Ds(n,r),Se=Ms(n,r),B=Ys(n,r),re=qs(n,r),ne=Ls(n,r,L,c),V=e.lint===!1?void 0:_t({adminRoutes:Fr(n,r),aiRawRuns:Mr(n,r),aiToolSideEffects:Hr(n,r),argumentDerivedFetches:Xr(n,r),argumentValidators:un(n,r),authApiCalls:Ts(n,r),authConfigs:$n(n,r),browserUrlAccesses:An(n,r),configCalls:On(n,r),containerKeyAccesses:Fn(n,r),containerOverrides:qn(n,r),containers:u,exportSinks:Wn(n,r),staleMigrationImports:Ha(n,r),failOpenGuards:Jn(n,r),flagSecurityDefaults:ei(n,r),geoIndexUsages:ri(n,r),httpActionGuards:ui(n,r),httpHeaderWrites:$i(n,r),identityClaimReads:Pi(n,r),imageDeliveryUrlAccesses:Ti(n,r),inserts:Os(n,r),kvKeyAccesses:ki(n,r),mailRecipientAccesses:Ki(n,r),maskProcedures:Cs(n,r),maskStrategies:Fs(n,r),mutatorWrites:Bi(n,r),nondeterministicCalls:Bs(n,r),normalizeIdAuthorizations:no(n,r),notifyCalls:Vs(n,r),notifyConfig:Us(n,r),ownerFieldWrites:po(n,r,O),unrestrictedWhereBranches:Ec(n,r),paymentWebhooks:Eo(n,r),privilegedDispatches:ko(n,r),procedureProtections:ma(n,r),queries:Ss(n,r),queues:T,r2sqlCalls:Ws(n,r),ratelimitKeySelectors:ya(n,r),rawRowReturns:wa(n,r),relationLoads:Ta(n,r),rlsProcedures:_s(n,r),schema:a,secretLiterals:Ra(n,r),shapes:B,softDeleteReads:ja(n,r),sqlInterpolations:Wa(n,r),storageKeyAccesses:Ja(n,r,O),storageUploads:sc(n,r),vectorNamespaceAccesses:bc(n,r),workflowCalls:Ac(n,r),workflows:L,wranglerVariables:e.wranglerVariables}),Ae=V===void 0?[]:[...Vt(V,{source:"static"}),...lc(n,r,O)],Ft=Gs(n,r),we=Ks(n,r);Lc(B,we,Rs(n,r));const Kt=C?ks(n,r):[],W=$r(p,{containerCount:u.length,cronCount:ne.length,dependencies:y,hasPaymentTables:yr(a.tables),queueCount:T.length,storageColumnCount:Object.keys(Xt(a)).length,storageRuleCount:q.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:L.length}),Pe=t?ue.now():0,Ie=Zt({agents:c,functions:O,httpRoutes:Ne,mutators:re,useUmbrella:K,workflows:L}),Te=Yt({agents:c,functions:O,migrations:Se,mutators:re,shapes:B,useUmbrella:K,usesSandbox:se}),ie=or(a,Se.map(m=>m.id)),Le=es({advisories:Ae,advisorProcedures:V?.procedureProtections??[],agents:c,containers:u,env:w,flagKeys:Kt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:v,hasFlags:C,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:j,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:we,mutators:re,queues:T,rlsMetadata:Ft,schema:a,schemaSnapshot:ie,shapes:B,storageRules:q,studioFeatures:W,useUmbrella:K,workflows:L}),ke=ts(B,y.has("@lunora/db"),K),De=ss(u,a.jurisdiction),Oe=rs(L),Ce=ns(c),Fe=is(T),Ke=os(ne),Re=as(a.vectorIndexes),_=cs(a,K),Me=ls(y.has("@lunora/seed")),G=e.apiSpec??"openapi",oe=G==="openapi"||G==="both",ae=G==="openrpc"||G==="both",je=er({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:y.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:y.has("@lunora/auth"),hasBrowser:v,hasFramework:y.has("@lunora/astro")||y.has("@lunora/svelte")||y.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:W.kv,hasNotify:j,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:L.length>0,hasX402:p.x402,identity:z,jurisdiction:a.jurisdiction,useUmbrella:K,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:oe,wantsOpenRpc:ae}),ze=Pc(e.projectRoot),qe=tr({functions:O,httpRoutes:Ne,version:ze}),Be=rr({functions:O,version:ze}),Ue=`${JSON.stringify(qe,void 0,2)}
8
+ `,Ve=`${JSON.stringify(Be,void 0,2)}
9
+ `,We=sr(qe),_e=nr(Be),ce=g(r,wc),Rt=b(ce);if(e.dryRun||(b(f)||qt(f,{recursive:!0}),S(g(f,"app.ts"),je),S(ve,d),S(g(f,"api.ts"),Ie),S(be,F),S(g(f,"functions.ts"),Te),S(g(f,"shard.ts"),Le),S(g(f,"crons.ts"),Ke),S(g(f,"vectors.ts"),Re),S(g(f,"drizzle.global.ts"),_.global),S(g(f,"drizzle.shard.ts"),_.shard),P(g(f,"containers.ts"),De),P(g(f,"workflows.ts"),Oe),P(g(f,"agents.ts"),Ce),P(g(f,"queues.ts"),Fe),P(g(f,"seed.ts"),Me),P(g(f,"collections.ts"),ke),P(g(f,"openapi.json"),oe?Ue:""),P(g(f,"openapi.ts"),oe?We:""),P(g(f,"openrpc.json"),ae?Ve:""),P(g(f,"openrpc.ts"),ae?_e:""),(!Rt||e.updateSchemaBaseline===!0)&&S(ce,Wt(ie))),t){const m=ue.now(),Mt=Math.round(m-s),jt=Math.round(Pe-s),zt=Math.round(m-Pe);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${jt.toString()}ms, emit ${zt.toString()}ms)`)}return{advisories:Ae,advisorContext:V,agents:c,containers:u,cronTriggers:us(ne),generated:{agents:Ce,api:Ie,app:je,collections:ke,containers:De,crons:Ke,dataModel:d,drizzleGlobal:_.global,drizzleShard:_.shard,functions:Te,openApi:Ue,openApiModule:We,openRpc:Ve,openRpcModule:_e,queues:Fe,seed:Me,server:F,shard:Le,vectors:Re,workflows:Oe},outputDirectory:f,platformDiagnostics:U.diagnostics,queues:T,schemaSnapshot:ie,schemaSnapshotPath:ce,workflows:L}};export{wc as SCHEMA_SNAPSHOT_FILENAME,kc as createCodegenProject,$l as refreshCodegenProject,vl as runCodegen};
@@ -276,7 +276,7 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
276
276
  ? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT" }) =>
277
277
  pick(opts?.bucket).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
278
278
  : undefined,
279
- storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string }) => pick(opts?.bucket).upload(key, body, opts),
279
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
280
280
  };
281
281
  }
282
282
  `:"",H=e=>e?`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.93",
3
+ "version": "1.0.0-alpha.94",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.68",
50
- "@lunora/agent": "1.0.0-alpha.43",
51
- "@lunora/container": "1.0.0-alpha.24",
52
- "@lunora/errors": "1.0.0-alpha.15",
49
+ "@lunora/advisor": "1.0.0-alpha.69",
50
+ "@lunora/agent": "1.0.0-alpha.44",
51
+ "@lunora/container": "1.0.0-alpha.25",
52
+ "@lunora/errors": "1.0.0-alpha.16",
53
53
  "@lunora/platform": "1.0.0-alpha.6",
54
- "@lunora/queue": "1.0.0-alpha.19",
55
- "@lunora/scheduler": "1.0.0-alpha.22",
56
- "@lunora/values": "1.0.0-alpha.20",
57
- "@lunora/workflow": "1.0.0-alpha.22",
54
+ "@lunora/queue": "1.0.0-alpha.20",
55
+ "@lunora/scheduler": "1.0.0-alpha.23",
56
+ "@lunora/values": "1.0.0-alpha.21",
57
+ "@lunora/workflow": "1.0.0-alpha.23",
58
58
  "jsonc-parser": "^3.3.1",
59
59
  "ts-morph": "^28.0.0"
60
60
  },
@@ -1,9 +0,0 @@
1
- import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,P as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,M as ls,F as us}from"./emit-QxfTfRoJ.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as S,r as $s,b as vs,s as ee,d as bs,f as Ns,y as As}from"./discover-queries-i4Vd2si7.mjs";import{classifyProcedureCall as M,inlineHandler as Ss,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Os from"./discoverInserts-D6szWzrV.mjs";import Cs,{discoverMaskStrategies as Fs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-Bh5Jv_9U.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-C-oA9yKS.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-5uSsJTUF.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(o=>!t.has(o.name));if(s.length===0)return;const r=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
2
- `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
- ${r}
4
-
5
- Install them with your package manager, then re-run codegen.`)},lr="env.ts",ur=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},gr=e=>{if(i.isIdentifier(e))return ur(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&dr(t)}return!1},pr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!gr(r.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o))throw Z(o,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:o.getText()})}return t},fr=(e,t)=>{const s=g(t,lr);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=pr(r);if(o.length!==0){if(o.length>1)throw Z(r,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return o[0]}},mr=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const o=r.getInitializer(),n=r.getNameNode();if(!(o===void 0||!t(o)||!i.isObjectBindingPattern(n)))for(const a of n.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},hr=(e,t)=>{const s=Object.fromEntries(de.map(r=>[r.key,!1]));for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=mr(o);for(const c of de)if(!s[c.key]){if(n.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(de.every(c=>s[c.key]))break}return s},xr=["providerSubscriptionId","state"],Er=["providerEventId","processedAt"],He=(e,t)=>t.every(s=>s in e.shape),yr=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&He(t,xr)&&He(s,Er)},$r=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),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/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),ht="identity.ts",vr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},br=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},Nr=e=>{if(i.isIdentifier(e))return vr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&br(t)}return!1},Ar=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!Nr(r.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o))throw Z(o,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:o.getText()})}return t},Sr=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=Ar(r);if(o.length!==0){if(o.length>1)throw Z(r,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return o[0]}},wr=(e,t)=>{const s=new Map,r=new Map,o=new Map;for(const n of e)s.set(n.name,`workflow "${n.exportName}"`),r.set(n.bindingName,`workflow "${n.exportName}"`),o.set(n.className,`workflow "${n.exportName}"`);for(const n of t){const a=s.get(n.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${n.name}": produced by both ${a} and agent "${n.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(n.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${n.bindingName}": produced by both ${c} and agent "${n.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(n.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${n.className}": produced by both ${u} and agent "${n.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Pr=e=>{const{lunoraDirectory:t,project:s,projectRoot:r,schema:o}=e,n=Sr(s,t),a=fr(s,t),c=xs(s,t),u=fs(s,t),d=Gt(s,t);wr(c,d);const y=Ht(s,t),w=hs(s,t),p=Es(hr(s,t),ys(r,e.target)),v=p.usage,C=ms(s,t),j=v.browser||C.usesSandboxBrowser,z=ps(r),U=z??new Set,T=U.has("lunorash");cr(o,z);const F=b(g(t,"flags.ts")),q=b(g(t,"notify.ts"));return{agents:d,containers:y,dataModelContent:Jt(o),declaredDependencies:z,dependencies:U,env:a,featureUsage:v,hasBrowser:j,hasFlags:F,hasNotify:q,identity:n,platformGate:p,queues:u,serverContent:Qt({agents:d,containers:y,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:j,hasFlags:F,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:q,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:n,queues:u,schema:o,storageRuleBuckets:w.rules.map(se=>se.bucket),useUmbrella:T,workflows:c}),storageRulesMetadata:w,usesSandbox:C.usesSandboxBrowser||C.usesSandboxContainer,useUmbrella:T,workflows:c}},xt=new Set(["delete","get","head","options","patch","post","put"]),Ir=new Set(["handler","stream"]),Tr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Qe=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Lr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},kr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return Lr(s)},Dr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Qe.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Qe.has(s.getText()))return!0}return!1},Or=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!Ir.has(r.getName()))return;const o=kr(s);if(!o||!Tr.test(o.path))return;const n=s.getArguments()[0],a=n!==void 0&&(i.isArrowFunction(n)||i.isFunctionExpression(n))&&Dr(n);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Cr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const o of r.getDeclarations()){const n=Or(o,t);n&&s.push(n)}return s},Fr=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Cr(o,E(t,r)))}return s},Kr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Rr=(e,t)=>{if(!Kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)||D(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Mr=(e,t)=>N(e,t,Rr),jr=new Set(["generateText","streamText"]),zr=new Set(["messages","prompt","system"]),qr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Br=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const o of qr)if(o.methods.has(s)&&o.prefixes.some(n=>r===n||r.startsWith(`${n}.`)))return`${r}.${s}`},Ur=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Br(t);if(s!==void 0)return s}},Vr=e=>{const t=new Set,s=e.getFirstAncestor(n=>i.isArrowFunction(n)||i.isFunctionExpression(n)||i.isFunctionDeclaration(n)),[r]=s?.getParameters()??[],o=r?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const n of o.getElements()){const a=n.getPropertyNameNode()?.getText()??n.getName(),c=n.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Wr=e=>{if($s(e))return!0;const t=Vr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},_r=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!zr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Wr(s))return!0}return!1},Gr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const o=S(r.getExpression());if(o===void 0||!jr.has(o))continue;const[n]=r.getArguments();if(n===void 0||!i.isObjectLiteralExpression(n))continue;let a;for(const c of n.getDescendantsOfKind(l.CallExpression))if(S(c.getExpression())==="tool"&&(a=Ur(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(r),file:t,line:r.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:_r(n)})}return s},Hr=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Gr(o,E(t,r)))}return s},Qr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Jr=(e,t)=>{if(!Qr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Xr=(e,t)=>N(e,t,Jr),Et=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Zr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:Et(r)}},Yr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const o=r.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const n=r.getArguments()[0];n&&i.isObjectLiteralExpression(n)?(t.push(n),s||=Et(n)):s=!0}r=o.getExpression()}return{objects:t,opaque:s}},yt=(e,t)=>t?Yr(t):Zr(e),en=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),tn=/\.check\(|\.meta\(|length|max/iu,sn=/\bv\.any\s*\(/u,rn=/\bv\.string\s*\(/u,nn=e=>sn.test(e),on=e=>rn.test(e)&&!tn.test(e),an=e=>{const t=[],s=[];for(const r of e)for(const o of r.getProperties()){if(!i.isPropertyAssignment(o))continue;const n=o.getInitializer();if(!n)continue;const a=n.getText(),c=o.getName();nn(a)?t.push(c):on(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},cn=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=M(s);if(r?.visibility!=="public")return;const{objects:o}=yt(s,r.receiver),{anyArgs:n,unboundedStringArgs:a}=an(o);if(!(n.length===0&&a.length===0))return{anyArgs:n,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},ln=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const o of r.getDeclarations()){const n=cn(o,t);n&&s.push(n)}return s},un=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ln(o,E(t,r)))}return s},ge=e=>e?.getKind()===l.TrueKeyword,dn=e=>e?.getKind()===l.FalseKeyword,gn=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,pn=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),fn=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),mn=e=>e!==void 0&&i.isCallExpression(e)&&pn.has(S(e.getExpression())??""),hn=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),xn=e=>{const t=$(e,"advanced"),s=$(e,"emailAndPassword"),r=$(e,"session");return{analyzable:!0,disableCsrfCheck:ge($(t,"disableCSRFCheck")),emailPasswordEnabled:ge($(s,"enabled")),requireEmailVerification:ge($(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:fn($(e,"plugins"))&&mn($(e,"database")),secureCookiesDisabled:dn($(t,"useSecureCookies")),sessionFreshAgeZero:gn($(r,"freshAge")),trustedOriginsWildcard:hn($(e,"trustedOrigins"))}},En=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),yn=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(n=>i.isSpreadAssignment(n)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?xn(s):En();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...o}},$n=(e,t)=>N(e,t,yn),vn=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},bn=(e,t,s)=>{const r=vn(e.getExpression(),s);if(r===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!I(o)||D(o))&&!(s.requireUnmodifiedReach===!0&&!vs(o)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:r}},Nn=(e,t,s)=>{const r=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const n=bn(o,t,s);n&&r.push(n)}return r},te=(e,t,s)=>{const r=[];for(const o of h(t)){const n=e.getSourceFile(o)??e.addSourceFileAtPath(o);r.push(...Nn(n,E(t,o),s))}return r},An=new Set(["content","pdf","scrape","screenshot"]),Sn=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:An}),wn=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Pn=new Set(["RateLimiter"]),In=new Set(["extend"]),$t=e=>{const t=[],s=[];let r=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){r=!0;continue}if(i.isPropertyAssignment(o)){const n=o.getName();t.push(n),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(n);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},Je=e=>e&&i.isObjectLiteralExpression(e)?$t(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Tn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},Ln=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?Tn(e):void 0},kn=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Ln(t.getBody());return s?$t(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const o=S(r.getExpression());o!==void 0&&(wn.has(o)?s.push({callee:o,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])}):In.has(o)&&s.push({callee:o,file:t,line:r.getStartLineNumber(),...kn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(l.NewExpression)){const o=S(r.getExpression());o===void 0||!Pn.has(o)||s.push({callee:o,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])})}return s},On=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(o,E(t,r)))}return s},Xe="ctx.containers.",Cn=e=>{if(!e.startsWith(Xe))return!1;const t=e.slice(Xe.length);return t.length>0&&!t.includes(".")},Fn=(e,t)=>te(e,t,{argIndex:0,matchReceiver:Cn,methods:new Set(["get"])}),Kn=new Set(["allow","deny","setAllowed"]),Rn=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Mn=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Rn(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},jn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!Kn.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},zn=(e,t)=>Mn(e,t)??jn(e,t),qn=(e,t)=>N(e,t,zn),Bn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Un=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Bn.has(s)?s:void 0},Vn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const o=r.getName();t.push(o);const n=r.getInitializer();n&&i.isStringLiteral(n)&&n.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Wn=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Un(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?Vn(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},_n=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Gn=new Set(["dbRateLimit","rateLimit"]),Hn=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Qn=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=_n.get(s);if(r!==void 0)return{callee:s,exportName:x(e),failOpen:Hn(e.getArguments()[r]),file:t,limitName:Gn.has(s)?gt(e):"",line:e.getStartLineNumber()}},Jn=(e,t)=>N(e,t,Qn),Xn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ds(t.getExpression())},Zn=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Yn=(e,t)=>{if(!Xn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),n=Zn(r);if(!(o.length===0||n===void 0))return{defaultValue:n,exportName:x(e),file:t,key:o,line:e.getStartLineNumber()}},ei=(e,t)=>N(e,t,Yn),ti=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},si=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},ri=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of o.getDescendantsOfKind(l.CallExpression))ti(a)&&s.push({file:n,indexName:si(a),line:a.getStartLineNumber()})}return s},ni=new Set(["delete","get","head","options","patch","post","put"]),ii=new Set(["handler","stream"]),oi=new Set(["runAction","runMutation"]),ai=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Ze=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Ye=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const o of r.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="ctx"){const n=o.getNameNode();return i.isIdentifier(n)?n.getText():void 0}}},et=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const o of r){const n=o.getExpression();if(!i.isPropertyAccessExpression(n))continue;const a=n.getName(),c=n.getExpression();if(oi.has(a)&&Q(c,t))return a;if(ai.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},tt=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(l.PropertyAccessExpression))if(r.getName()==="auth"&&Q(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(l.VariableDeclaration)){const o=r.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Q(r.getInitializer(),t))){for(const n of o.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="auth")return!0}}return!1},ci=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ii.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const o=r.getName();if(ni.has(o)){const n=r.getExpression();return i.isIdentifier(n)&&n.getText()==="httpRoute"?o.toUpperCase():void 0}s=r.getExpression()}},li=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ze(e.getArguments()[0]),u=c&&Ye(c,!0);if(!c||u===void 0)return;const d=et(c,u);return d===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:tt(c,u),sideEffect:d}}const r=ci(e);if(r===void 0)return;const o=Ze(e.getArguments()[0]),n=o&&Ye(o,!1);if(!o||n===void 0)return;const a=et(o,n);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:tt(o,n),sideEffect:a}},ui=(e,t)=>N(e,t,li),di=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),gi=new Set(["append","set"]),he=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",vt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",st=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(s=>di.has(he(s.getExpression()))&&Ns(s,t)),pi=(e,t)=>{if(st(e,t))return!0;const s=ee(e);return s!==void 0&&st(s,t)},me=(e,t)=>bs(e,t)&&!pi(e,t),fi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ee(e);return t!==void 0&&i.isNewExpression(t)&&he(t.getExpression())==="Headers"},J=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=ee(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},xe=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const o=r.getInitializer();o!==void 0&&me(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:vt(r.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const o=r.getNameNode();me(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const o=J(r.getExpression());o!==void 0&&xe(o,t,s)}},bt=(e,t)=>{const s=J(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const o=J(r.getInitializer());o!==void 0&&xe(o,"response-init",t)},mi=(e,t)=>{const s=he(e.getExpression());if(s==="Response")bt(e.getArguments()[1],t);else if(s==="Headers"){const r=J(e.getArguments()[0]);r!==void 0&&xe(r,"headers-ctor",t)}},hi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),o=s.getExpression();if(r==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){bt(e.getArguments()[1],t);return}if(gi.has(r)&&fi(o)){const n=e.getArguments()[1];n!==void 0&&me(n,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:vt(e.getArguments()[0]),line:n.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},xi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))mi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))hi(s,t)},Ei=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=Ss(e.getArguments()[0]);if(r===void 0)return[];const o=r.getParameters()[1];if(o===void 0)return[];const n=o.getNameNode();if(!i.isIdentifier(n))return[];const a=[];return xi(r,{exportName:x(e),relativePath:t,requestName:n.getText(),rows:a}),a},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression))s.push(...Ei(r,t));return s},$i=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(o,E(t,r)))}return s},vi=new Set(["auth","context.auth","ctx.auth"]),bi="userId",Ni=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Ai=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of r.getDescendantsOfKind(l.CallExpression)){if(S(o.getExpression())!=="defineIdentity")continue;const[n]=o.getArguments();return n&&i.isObjectLiteralExpression(n)?Ni(n):void 0}},rt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return vi.has(e.getExpression().getText())?e:void 0},Si=e=>{if(i.isPropertyAccessExpression(e)&&rt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&rt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},wi=(e,t,s)=>{const r=[];for(const o of e.getDescendants()){const n=Si(o);n!==void 0&&r.push({declared:n===bi||s.has(n),exportName:x(o),file:t,key:n,line:o.getStartLineNumber()})}return r},Pi=(e,t)=>{const s=Ai(e,t);if(s===void 0)return[];const r=[];for(const o of h(t)){const n=e.getSourceFile(o)??e.addSourceFileAtPath(o);r.push(...wi(n,E(t,o),s))}return r},Ii=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=$(s,"key");if(!(!r||!I(r)||D(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Ti=(e,t)=>N(e,t,Ii),Li=new Set(["delete","get","getRaw","getWithMetadata","put"]),ki=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Li}),Di=new Set(["queue","send"]),nt=new Set(["bcc","cc","to"]),Oi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Di.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Ci=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return nt.has(t.getName())&&I(r)&&!D(r)}if(!i.isPropertyAssignment(t)||!nt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&I(s)&&!D(s)}):!1,Fi=(e,t)=>{const s=Oi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Ci(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Ki=(e,t)=>N(e,t,Fi),Ri=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Mi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ji=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return zs(s.getExpression())?s:void 0},zi=e=>{const t=ji(e),s=t===void 0?void 0:Mi(t);if(s===void 0)return[];const r=e.getNameNode(),o=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(n=>Ri(n)).map(n=>({exportName:o,file:"lunora/mutators.ts",line:n.getStartLineNumber()}))},qi=e=>e.getVariableDeclarations().flatMap(t=>zi(t)),Bi=(e,t)=>{const s=g(t,js);if(!b(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return qi(r)},Ui=new Set(["delete","get","patch"]),Vi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Wi=new Set(["auth","identity","session","user"]),_i=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Gi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!R(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Hi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},Qi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ji=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Xi=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Qi(s.getExpression(),t)&&Ji(s.getThenStatement())),Zi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const o=r.getName();if(!Ui.has(o))continue;const n=r.getExpression();if(!(R(n)||i.isPropertyAccessExpression(n)&&R(n.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return o}},Yi=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},eo=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Yi(s)==="ctx")),to=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>_i.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),so=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Vi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Wi.has(t.getName()))return!0}return eo(e)||to(e)},ro=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const o=ft(s);if(o===void 0)return[];const n=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=so(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const y=Gi(d);if(y===void 0)continue;const w=Hi(d);if(w===void 0||c.has(w)||!Xi(o,w))continue;const p=Zi(o,w);p!==void 0&&(c.add(w),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:y,usesRls:n,visibility:r.visibility}))}return u},no=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ro(c,n))}return s},io=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),oo=new Set(["insert","insertManyUnsafe","patch","replace"]),ao=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!oo.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},co=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},lo=(e,t,s,r)=>{const o=[];for(const n of e.getProperties()){let a,c;i.isPropertyAssignment(n)?(a=n.getName(),c=n.getInitializer()):i.isShorthandPropertyAssignment(n)&&(a=n.getName(),c=n.getNameNode()),!(a===void 0||c===void 0||!io.has(a))&&I(c)&&!D(c)&&o.push({exportName:x(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return o},uo=(e,t)=>{const s=ao(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?co(r,s).flatMap(o=>lo(o,s,e,t)):[]},go=(e,t,s)=>{const r=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const n of uo(o,t)){const a=s(n.exportName);r.push(a===void 0?n:{...n,visibility:a})}return r},po=(e,t,s=[])=>{const r=[],o=new Map(s.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));for(const n of h(t)){const a=e.getSourceFile(n)??e.addSourceFileAtPath(n),c=E(t,n);r.push(...go(a,c,u=>o.get(`${c}:${u}`)))}return r},fo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mo=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?mo(t.getInitializer()):void 0},xo=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!fo.has(s))return;const[r]=e.getArguments(),o=r&&i.isObjectLiteralExpression(r)?ho(r):void 0;return{callee:s,exportName:x(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},Eo=(e,t)=>N(e,t,xo),yo=new Set(["defineQueue","defineWorkflow"]),$o=new Set(["run","runAction","runMutation","runQuery"]),vo=new Set(["api","internal"]),bo=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},No=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},At=(e,t)=>e===t||e.startsWith(`${t}.`),St=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},it=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},wt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>it(s));return i.isIdentifier(e)&&it(e)&&t.push(e),t},Ao=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},So=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(l.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const o=r.getInitializer(),n=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;n&&i.isIdentifier(n)&&s.push(`${n.getText()}.body`)}return s},wo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:So(e),o=new Set,n=a=>St(a).some(c=>r.some(u=>At(c.getText(),u)))?!0:wt(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&n(c))for(const u of Ao(a))o.add(u)}return{names:o,prefixes:r}},Po=(e,t)=>St(e).some(s=>t.prefixes.some(r=>At(s.getText(),r)))?!0:wt(e).some(s=>t.names.has(s.getText())),Io=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!vo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},To=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const o=wo(e,t,r),n=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!$o.has(c.getName())||c.getExpression().getText()!==r)continue;const u=a.getArguments()[1];if(!u||!Po(u,o))continue;const d=Io(a.getArguments()[0]);d!==void 0&&n.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return n},Lo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const o=bo(r);if(o===void 0||!yo.has(o))continue;const n=No(r);n!==void 0&&s.push(...To(n,o==="defineQueue"?"queue":"workflow",t))}return s},ko=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Lo(o,E(t,r)))}return s},ot={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},at=new Set(["account","credential","member","passkey","session","user"]),Do=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Oo=e=>{const t=Do(e).at(-1);if(!t)return!1;const s=t.endsWith("s")?t.slice(0,-1):t;return at.has(t)||at.has(s)},Co=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Fo=(e,t)=>{const{objects:s,opaque:r}=yt(e,t);return en(s).some(o=>Co(o))?!0:r?void 0:!1},Ee=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Ko=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ro=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},H={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mo=e=>{const t=Ro(e),s=t?Ee(t):void 0;if(t&&s==="protectPublic"){const r=Ko(t);return{...H,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in ot?{...H,[ot[s]]:!0}:H},jo=e=>{const t={...H};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const o=r.getName()==="use"?s.getArguments()[0]:void 0;if(o){const n=Mo(o);t.usesCaptcha||=n.usesCaptcha,t.usesEmailGate||=n.usesEmailGate,t.usesMask||=n.usesMask,t.usesRateLimit||=n.usesRateLimit,t.usesRls||=n.usesRls}s=r.getExpression()}return t},zo=new Set(["insert","insertMany","insertManyUnsafe","replace"]),qo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!zo.has(t.getName()))return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:Oo(r.getLiteralText())},Bo=new Set(["create","runAfter","runAt","send","sendBatch"]),Uo=new Set(["queues","scheduler","workflows"]),Vo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Bo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Uo.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Pt=new Set(["generateObject","generateText","streamObject","streamText"]),_o=e=>{const t=Ee(e);return t!==void 0&&Pt.has(t)},Go=e=>{const t=Ee(e);if(t===void 0||!Pt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Ho=new Set(["log","span","trace"]),Qo=new Set(["ai"]),Jo=new Set(["email","mail"]),Xo=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),pe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),Zo=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Yo=new Set(["every","filter","flatMap","forEach","map","some"]),ea=new Set(["all","allSettled","race"]),ta=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName();if(Yo.has(r))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&ea.has(r))return t},sa=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Zo.has(t.getKind())){const s=ta(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},ra=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const r=s.getParent();if(!i.isCallExpression(r)||r.getExpression()!==s)return!1;t=r}},na=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ia=e=>{let t=!1,s=!0;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Xo.has(r.getName()))continue;const o=r.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const n=na(r);n&&(t=!0,!sa(n)&&!ra(n)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},oa=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),ct="lunora-advisor-exempt",aa=/^[\s*/]+/u,ca=/[\w-]/u,la=e=>{const t=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
6
- `);for(const s of t.split(`
7
- `)){const r=s.replace(aa,"");if(!r.startsWith(ct))continue;const o=r.slice(ct.length);if(ca.test(o.charAt(0)))continue;const n=o.indexOf("--");return{exempt:!0,exemptReason:(n===-1?"":o.slice(n+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},ua=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},da=(e,t)=>{const s=ua(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const r=s.getSourceFile(),o=s.getText(),n=r.getVariableDeclaration(o)?.getInitializer();return n&&(i.isArrowFunction(n)||i.isFunctionExpression(n))?n:r.getFunction(o)},ga=e=>{let t=!1,s=!1,r=!1,o=!1,n=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(qo(u)&&(n=!0),Vo(u)&&(t=!0),Wo(u)&&(o=!0),_o(u)&&(s=!0),Go(u)&&(r=!0),n&&t&&o&&r)break;const{handlesErrors:a,reachesOutbound:c}=ia(e);return{callsMail:pe(e,Jo),emitsEvent:pe(e,Ho),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||pe(e,Qo),throwsBareError:oa(e),unboundedAiGeneration:r,usesInsertManyUnsafe:o,writesUserTable:n}},pa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=M(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const o=r.receiver?jo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},n=da(e,s);return{...n?ga(n):{},...la(e),...o,analyzableBody:n!==void 0,exportName:e.getName(),file:t,hasEmailArg:Fo(s,r.receiver),kind:r.kind,visibility:r.visibility}},fa=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const o of r.getDeclarations()){const n=pa(o,t);n&&s.push(n)}return s},ma=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fa(o,E(t,r)))}return s},ha=new Set(["dbRateLimit","rateLimit"]),xa=e=>i.isArrowFunction(e)?e.getBody():e,Ea=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!ha.has(s))return;const r=e.getArguments()[2];if(!r)return;const o=$(r,"key");if(!o)return;const n=xa(o);if(!(!I(n)||D(n)))return{callee:s,exportName:x(e),file:t,limitName:gt(e),line:e.getStartLineNumber()}},ya=(e,t)=>N(e,t,Ea),$a=new Set(["findFirst","findFirstOrThrow","findMany","get"]),va=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!$a.has(t.getName()))return;const s=t.getExpression();if(R(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&R(s.getExpression()))return s.getName()},ba=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&R(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Na=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=Na(e);if(i.isIdentifier(s)){if(t)return;const r=ee(s);return r===void 0?void 0:It(r,!0)}if(i.isCallExpression(s))return va(s)??ba(s)},Aa=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(l.ReturnStatement)){const o=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),n=r.getExpression();o===e&&n!==void 0&&s.push(n)}return s},Sa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query")return[];const o=ft(s);if(o===void 0)return[];const n=r.receiver!==void 0&&ws(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,u=[];for(const d of Aa(o)){const y=It(d);y===void 0||c.has(y)||(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:y,usesMask:a,usesOutput:n,visibility:r.visibility}))}return u},wa=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sa(c,n))}return s},Pa=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Ia=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?M(s):void 0;if(!r)return[];const o=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=Pa($(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:n.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return o},Ta=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,n))}return s},X=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=X(e.getLeft()),s=X(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},La=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&X(t)!==void 0},ka=/(?:^|\/)__tests__\//u,Da=/\.(?:spec|test)$/u,Oa=e=>ka.test(e)||Da.test(e),Ca=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Fa=(e,t,s)=>Xs(e)?!Oa(s)&&Zs(Ca(t)):!0,Ka=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const n of r){if(La(n))continue;const a=X(n);if(a===void 0)continue;const c=Qs(a);if(c===void 0||!Fa(c,n,t))continue;const u=n.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:Js(a)}))}return s},Ra=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ka(o,E(t,r)))}return s},Ma=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?M(s):void 0;if(!r)return[];const o=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=$(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&I(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:n.getStartLineNumber(),table:a.table,visibility:r.visibility})}return o},ja=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ma(c,n))}return s},za=new Set(["query","unsafe"]),qa=e=>{if(!i.isPropertyAccessExpression(e)||!za.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},Ba=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Ua=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Va=(e,t)=>{if(!qa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ba(s)))return{exportName:Ua(e),file:t,line:s.getStartLineNumber()}},Wa=(e,t)=>N(e,t,Va),_a=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ga=(e,t,s=[])=>{const r=new Map(s.map(o=>[`${o.filePath}:${o.exportName}`,o.visibility]));return te(e,t,{argIndex:0,matchReceiver:o=>o==="ctx.storage"||o.startsWith("ctx.storage."),methods:_a,requireUnmodifiedReach:!0}).map(o=>{const n=r.get(`${o.file}:${o.exportName}`);return n===void 0?o:{...o,visibility:n}})},Ha=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Qa=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Ja=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){r=!0;continue}if(i.isPropertyAssignment(o)){const n=o.getName();t.push(n),n==="expiresInSeconds"&&(s=Qa(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Xa=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ha.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Za=(e,t)=>{const s=Xa(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ja(e.getArguments()[s.optionsIndex])}},Ya=(e,t)=>N(e,t,Za),ec=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),ye=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&ec.has(s)?s:void 0},Tt=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Lt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},tc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},$e=(e,t,s,r,o)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${r.toString()}) has type \`${s}\` but was not registered — ${o.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${o.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),sc=(e,t,s)=>{const r=[];for(const o of e.getVariableStatements().filter(n=>n.isExported()))for(const n of o.getDeclarations()){const a=n.getName();if(s.has(`${t}:${a}`)||!Tt(n))continue;const c=ye(n);c!==void 0&&r.push($e(t,a,c,n.getStartLineNumber(),Lt))}return r},rc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const o of e.getExportAssignments().filter(n=>!n.isExportEquals())){const n=ye(o.getExpression());n!==void 0&&r.push($e(t,"default",n,o.getStartLineNumber(),Lt))}return r},nc=(e,t,s)=>{const r=[];for(const o of e.getExportDeclarations().filter(n=>n.getModuleSpecifier()===void 0))for(const n of o.getNamedExports()){const a=n.getAliasNode()?.getText()??n.getName();if(s.has(`${t}:${a}`))continue;const c=n.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!Tt(c))continue;const u=ye(c);u!==void 0&&r.push($e(t,a,u,n.getStartLineNumber(),tc))}return r},ic=(e,t,s)=>[...sc(e,t,s),...rc(e,t,s),...nc(e,t,s)],oc=(e,t,s)=>{const r=new Set(s.map(n=>`${n.filePath}:${n.exportName}`)),o=[];for(const n of h(t)){const a=e.getSourceFile(n);a!==void 0&&o.push(...ic(a,E(t,n),r))}return o.toSorted((n,a)=>n.cacheKey.localeCompare(a.cacheKey))},ac=new Set(["when","where"]),fe=new Set(["definePolicy","defineShape"]),cc=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return fe.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const o=r.getNameNode().getText();return fe.has(o)?o:void 0}const s=t.getText();return fe.has(s)?s:void 0},lc=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,kt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(lc(e))return"empty-object";if(i.isParenthesizedExpression(e))return kt(e.getExpression())}},Dt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Ot=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Dt(t)===e),Ct=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Dt(t)===e),uc=e=>{const t=Ot(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Ct(e).length>0},dc=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Ot(e)){const o=i.isReturnStatement(r)?r.getExpression():void 0;t.push(o??r)}for(const r of Ct(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},gc=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},pc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const o=[];for(const n of r.getProperties()){if(!i.isPropertyAssignment(n)||!ac.has(n.getName()))continue;const a=n.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&uc(a))for(const c of dc(a)){const u=kt(c);u!==void 0&&o.push({exportName:gc(e),file:s,form:u,key:n.getName(),line:c.getStartLineNumber(),owner:t})}}return o},fc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const o=cc(r);o!==void 0&&s.push(...pc(r,o,t))}return s},mc=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fc(o,E(t,r)))}return s},hc=new Set(["query","upsert","upsertMany"]),xc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(hc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Ec=(e,t)=>{const s=xc(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const o=$(r,"namespace");if(!(!o||!I(o)||D(o)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},yc=(e,t)=>N(e,t,Ec),$c=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},vc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},bc=(e,t)=>{const s=[];for(const r of h(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!$c(a))continue;const c=gs(a);c!==""&&s.push({exportName:c,file:n,line:a.getStartLineNumber(),workflow:vc(a)})}}return s},Nc=".lunora-schema.json",A=(e,t)=>{b(e)&&dt(e,"utf8")===t||Bt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}A(e,t)},Ac=e=>{const t=g(e,"package.json");if(b(t))try{const s=JSON.parse(dt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Sc=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},wc=e=>{let t=b(e)?e:le(e);for(;t&&t!==le(t);){const s=g(t,"tsconfig.json");if(b(s))return s;t=le(t)}},lt=e=>e.replaceAll("\\","/"),Pc=(e,t,s)=>{if(s&&e.length>0){const n=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("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) (${n}), 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 r=new Map;for(const n of t.columns){const a=r.get(n.table)??[];a.push(n.column),r.set(n.table,a)}const o=t.columns.length>0;for(const n of e){if(n.table===void 0){if(o)throw new k("MASK_UNSUPPORTED",`defineShape "${n.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 "${n.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=r.get(n.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${n.exportName}" replicates table "${n.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})}},ut=(e,t,s)=>{const r=e.getSourceFile(t);if(r===void 0){e.createSourceFile(t,s,{overwrite:!0});return}r.getFullText()!==s&&r.replaceWithText(s)},Ic=e=>{const t=wc(e);return t?new Ge({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ge({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},xl=(e,t)=>{const s=h(t),r=g(t,"schema.ts");b(r)&&s.push(r);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>lt(c))),n=lt(t),a=`${n}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===n||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}},El=e=>{const t=Sc(),s=t?ue.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),o=g(r,"schema.ts");if(!b(o))throw new k("INTERNAL",`schema.ts not found at ${o}`);const n=e.project??Ic(r);ir(Is);const a=Hs(n,o,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:y,env:w,featureUsage:p,hasBrowser:v,hasFlags:C,hasNotify:j,identity:z,platformGate:U,queues:T,serverContent:F,storageRulesMetadata:q,usesSandbox:se,useUmbrella:K,workflows:L}=Pr({lunoraDirectory:r,project:n,projectRoot:e.projectRoot,schema:a,target:e.target}),f=g(r,"_generated"),ve=g(f,"dataModel.ts"),be=g(f,"server.ts");ut(n,ve,d),ut(n,be,F);const O=Ps(n,r),Ne=Ds(n,r),Ae=Ms(n,r),B=Ys(n,r),re=qs(n,r),ne=Ls(n,r,L,c),V=e.lint===!1?void 0:_t({adminRoutes:Fr(n,r),aiRawRuns:Mr(n,r),aiToolSideEffects:Hr(n,r),argumentDerivedFetches:Xr(n,r),argumentValidators:un(n,r),authApiCalls:Ts(n,r),authConfigs:$n(n,r),browserUrlAccesses:Sn(n,r),configCalls:On(n,r),containerKeyAccesses:Fn(n,r),containerOverrides:qn(n,r),containers:u,exportSinks:Wn(n,r),failOpenGuards:Jn(n,r),flagSecurityDefaults:ei(n,r),geoIndexUsages:ri(n,r),httpActionGuards:ui(n,r),httpHeaderWrites:$i(n,r),identityClaimReads:Pi(n,r),imageDeliveryUrlAccesses:Ti(n,r),inserts:Os(n,r),kvKeyAccesses:ki(n,r),mailRecipientAccesses:Ki(n,r),maskProcedures:Cs(n,r),maskStrategies:Fs(n,r),mutatorWrites:Bi(n,r),nondeterministicCalls:Bs(n,r),normalizeIdAuthorizations:no(n,r),notifyCalls:Vs(n,r),notifyConfig:Us(n,r),ownerFieldWrites:po(n,r,O),unrestrictedWhereBranches:mc(n,r),paymentWebhooks:Eo(n,r),privilegedDispatches:ko(n,r),procedureProtections:ma(n,r),queries:As(n,r),queues:T,r2sqlCalls:Ws(n,r),ratelimitKeySelectors:ya(n,r),rawRowReturns:wa(n,r),relationLoads:Ta(n,r),rlsProcedures:_s(n,r),schema:a,secretLiterals:Ra(n,r),shapes:B,softDeleteReads:ja(n,r),sqlInterpolations:Wa(n,r),storageKeyAccesses:Ga(n,r,O),storageUploads:Ya(n,r),vectorNamespaceAccesses:yc(n,r),workflowCalls:bc(n,r),workflows:L,wranglerVariables:e.wranglerVariables}),Se=V===void 0?[]:[...Vt(V,{source:"static"}),...oc(n,r,O)],Ft=Gs(n,r),we=Ks(n,r);Pc(B,we,Rs(n,r));const Kt=C?ks(n,r):[],W=$r(p,{containerCount:u.length,cronCount:ne.length,dependencies:y,hasPaymentTables:yr(a.tables),queueCount:T.length,storageColumnCount:Object.keys(Xt(a)).length,storageRuleCount:q.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:L.length}),Pe=t?ue.now():0,Ie=Zt({agents:c,functions:O,httpRoutes:Ne,mutators:re,useUmbrella:K,workflows:L}),Te=Yt({agents:c,functions:O,migrations:Ae,mutators:re,shapes:B,useUmbrella:K,usesSandbox:se}),ie=or(a,Ae.map(m=>m.id)),Le=es({advisories:Se,advisorProcedures:V?.procedureProtections??[],agents:c,containers:u,env:w,flagKeys:Kt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:v,hasFlags:C,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:j,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:we,mutators:re,queues:T,rlsMetadata:Ft,schema:a,schemaSnapshot:ie,shapes:B,storageRules:q,studioFeatures:W,useUmbrella:K,workflows:L}),ke=ts(B,y.has("@lunora/db"),K),De=ss(u,a.jurisdiction),Oe=rs(L),Ce=ns(c),Fe=is(T),Ke=os(ne),Re=as(a.vectorIndexes),_=cs(a,K),Me=ls(y.has("@lunora/seed")),G=e.apiSpec??"openapi",oe=G==="openapi"||G==="both",ae=G==="openrpc"||G==="both",je=er({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:y.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:y.has("@lunora/auth"),hasBrowser:v,hasFramework:y.has("@lunora/astro")||y.has("@lunora/svelte")||y.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:W.kv,hasNotify:j,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:L.length>0,hasX402:p.x402,identity:z,jurisdiction:a.jurisdiction,useUmbrella:K,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:oe,wantsOpenRpc:ae}),ze=Ac(e.projectRoot),qe=tr({functions:O,httpRoutes:Ne,version:ze}),Be=rr({functions:O,version:ze}),Ue=`${JSON.stringify(qe,void 0,2)}
8
- `,Ve=`${JSON.stringify(Be,void 0,2)}
9
- `,We=sr(qe),_e=nr(Be),ce=g(r,Nc),Rt=b(ce);if(e.dryRun||(b(f)||qt(f,{recursive:!0}),A(g(f,"app.ts"),je),A(ve,d),A(g(f,"api.ts"),Ie),A(be,F),A(g(f,"functions.ts"),Te),A(g(f,"shard.ts"),Le),A(g(f,"crons.ts"),Ke),A(g(f,"vectors.ts"),Re),A(g(f,"drizzle.global.ts"),_.global),A(g(f,"drizzle.shard.ts"),_.shard),P(g(f,"containers.ts"),De),P(g(f,"workflows.ts"),Oe),P(g(f,"agents.ts"),Ce),P(g(f,"queues.ts"),Fe),P(g(f,"seed.ts"),Me),P(g(f,"collections.ts"),ke),P(g(f,"openapi.json"),oe?Ue:""),P(g(f,"openapi.ts"),oe?We:""),P(g(f,"openrpc.json"),ae?Ve:""),P(g(f,"openrpc.ts"),ae?_e:""),(!Rt||e.updateSchemaBaseline===!0)&&A(ce,Wt(ie))),t){const m=ue.now(),Mt=Math.round(m-s),jt=Math.round(Pe-s),zt=Math.round(m-Pe);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${jt.toString()}ms, emit ${zt.toString()}ms)`)}return{advisories:Se,advisorContext:V,agents:c,containers:u,cronTriggers:us(ne),generated:{agents:Ce,api:Ie,app:je,collections:ke,containers:De,crons:Ke,dataModel:d,drizzleGlobal:_.global,drizzleShard:_.shard,functions:Te,openApi:Ue,openApiModule:We,openRpc:Ve,openRpcModule:_e,queues:Fe,seed:Me,server:F,shard:Le,vectors:Re,workflows:Oe},outputDirectory:f,platformDiagnostics:U.diagnostics,queues:T,schemaSnapshot:ie,schemaSnapshotPath:ce,workflows:L}};export{Nc as SCHEMA_SNAPSHOT_FILENAME,Ic as createCodegenProject,xl as refreshCodegenProject,El as runCodegen};