@lunora/codegen 1.0.0-alpha.403 → 1.0.0-alpha.404
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 +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ENV_FILENAME-COPIfgzp.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DvMqIcXC.mjs +54 -0
- package/package.json +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Cuhl5Xbr.mjs +0 -54
package/dist/index.d.mts
CHANGED
|
@@ -3930,6 +3930,8 @@ declare const discoverContainers: (project: Project, lunoraDirectory: string) =>
|
|
|
3930
3930
|
* across the project.
|
|
3931
3931
|
*/
|
|
3932
3932
|
declare const discoverCrons: (project: Project, lunoraDirectory: string, workflows?: ReadonlyArray<WorkflowIR>, agents?: ReadonlyArray<AgentIR>) => CronJobIR[];
|
|
3933
|
+
/** The only file a `defineEnv` contract may be declared in — mirrors `lunora/identity.ts`. */
|
|
3934
|
+
declare const ENV_FILENAME = "env.ts";
|
|
3933
3935
|
/** The only file a feature-flag provider may be declared in — mirrors `lunora/queues.ts`. */
|
|
3934
3936
|
declare const FLAGS_FILENAME = "flags.ts";
|
|
3935
3937
|
/**
|
|
@@ -5101,4 +5103,4 @@ declare const secretKindOf: (value: string) => string | undefined;
|
|
|
5101
5103
|
/** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
|
|
5102
5104
|
declare const redact: (value: string) => string;
|
|
5103
5105
|
declare const VERSION = "0.0.0";
|
|
5104
|
-
export { AGENTS_FILENAME, ALL_NOTIFY_CHANNELS, type AgentIR, type ArchitectureManifest, type AuthApiCallIR, CAPABILITY_PROBES, COMPANION_BINDING, COMPANION_SERVICE_NAME, CONTAINERS_FILENAME, type CapabilityKey, type CapabilityProbe, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContainerImageIR, type ContainerNamedImageIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DefaultScheduledContainerIR, type DriftChange, type DriftRemediation, type DriftScope, type DurableObjectScheduledContainerIR, type EmitAppOptions, FLAGS_FILENAME, type FcmCredentials, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexReference, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, type LoadedProjectConfig, type LunoraProjectConfig, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, type NotifyChannels, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, PROJECT_CONFIG_FILENAMES, type PlatformDiagnostic, type ProjectConfigLiterals, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ServiceBindingIR, type ServiceLiteral, type ShapeIR, type SourceCapabilitySignals, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, type TargetScope, type TopicIR, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerQueueProducerIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, capabilitiesUsedBy, companionServiceBinding, createCodegenProject, createTargetScope, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyChannels, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitInternalApi, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitScheduler, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findCodegenConfigFile, findProjectConfigFile, findTsconfig, fingerprintSchemaSources, foldCapabilitySignals, formatAdvisories, indexReferencesOf, isD1GlobalTable, isHyperdriveGlobalTable, isTestPath, lintSchema, listLunoraSourceFiles, loadProjectConfig, mayReadCapabilityContext, parseSchemaSnapshot, platformMatrixIds, projectConfigCandidatePaths, readBoundServiceBindings, readDevServiceBindings, readPackageDependencies, readProjectConfigLiterals, readProjectLazyFunctions, readProjectSecurityHeaders, readProjectTarget, readServiceBindings, redact, refreshCodegenProject, resolveCodegenTarget, resolveServiceBindings, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, sortedUniqueNames, sourceCapabilitySignals, toAdvisorContext, tsconfigFingerprint, validatorIrToJsonSchema };
|
|
5106
|
+
export { AGENTS_FILENAME, ALL_NOTIFY_CHANNELS, type AgentIR, type ArchitectureManifest, type AuthApiCallIR, CAPABILITY_PROBES, COMPANION_BINDING, COMPANION_SERVICE_NAME, CONTAINERS_FILENAME, type CapabilityKey, type CapabilityProbe, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContainerImageIR, type ContainerNamedImageIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DefaultScheduledContainerIR, type DriftChange, type DriftRemediation, type DriftScope, type DurableObjectScheduledContainerIR, ENV_FILENAME, type EmitAppOptions, FLAGS_FILENAME, type FcmCredentials, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexReference, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, type LoadedProjectConfig, type LunoraProjectConfig, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, type NotifyChannels, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, PROJECT_CONFIG_FILENAMES, type PlatformDiagnostic, type ProjectConfigLiterals, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ServiceBindingIR, type ServiceLiteral, type ShapeIR, type SourceCapabilitySignals, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, type TargetScope, type TopicIR, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerQueueProducerIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, capabilitiesUsedBy, companionServiceBinding, createCodegenProject, createTargetScope, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyChannels, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitInternalApi, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitScheduler, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findCodegenConfigFile, findProjectConfigFile, findTsconfig, fingerprintSchemaSources, foldCapabilitySignals, formatAdvisories, indexReferencesOf, isD1GlobalTable, isHyperdriveGlobalTable, isTestPath, lintSchema, listLunoraSourceFiles, loadProjectConfig, mayReadCapabilityContext, parseSchemaSnapshot, platformMatrixIds, projectConfigCandidatePaths, readBoundServiceBindings, readDevServiceBindings, readPackageDependencies, readProjectConfigLiterals, readProjectLazyFunctions, readProjectSecurityHeaders, readProjectTarget, readServiceBindings, redact, refreshCodegenProject, resolveCodegenTarget, resolveServiceBindings, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, sortedUniqueNames, sourceCapabilitySignals, toAdvisorContext, tsconfigFingerprint, validatorIrToJsonSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -3930,6 +3930,8 @@ declare const discoverContainers: (project: Project, lunoraDirectory: string) =>
|
|
|
3930
3930
|
* across the project.
|
|
3931
3931
|
*/
|
|
3932
3932
|
declare const discoverCrons: (project: Project, lunoraDirectory: string, workflows?: ReadonlyArray<WorkflowIR>, agents?: ReadonlyArray<AgentIR>) => CronJobIR[];
|
|
3933
|
+
/** The only file a `defineEnv` contract may be declared in — mirrors `lunora/identity.ts`. */
|
|
3934
|
+
declare const ENV_FILENAME = "env.ts";
|
|
3933
3935
|
/** The only file a feature-flag provider may be declared in — mirrors `lunora/queues.ts`. */
|
|
3934
3936
|
declare const FLAGS_FILENAME = "flags.ts";
|
|
3935
3937
|
/**
|
|
@@ -5101,4 +5103,4 @@ declare const secretKindOf: (value: string) => string | undefined;
|
|
|
5101
5103
|
/** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
|
|
5102
5104
|
declare const redact: (value: string) => string;
|
|
5103
5105
|
declare const VERSION = "0.0.0";
|
|
5104
|
-
export { AGENTS_FILENAME, ALL_NOTIFY_CHANNELS, type AgentIR, type ArchitectureManifest, type AuthApiCallIR, CAPABILITY_PROBES, COMPANION_BINDING, COMPANION_SERVICE_NAME, CONTAINERS_FILENAME, type CapabilityKey, type CapabilityProbe, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContainerImageIR, type ContainerNamedImageIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DefaultScheduledContainerIR, type DriftChange, type DriftRemediation, type DriftScope, type DurableObjectScheduledContainerIR, type EmitAppOptions, FLAGS_FILENAME, type FcmCredentials, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexReference, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, type LoadedProjectConfig, type LunoraProjectConfig, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, type NotifyChannels, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, PROJECT_CONFIG_FILENAMES, type PlatformDiagnostic, type ProjectConfigLiterals, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ServiceBindingIR, type ServiceLiteral, type ShapeIR, type SourceCapabilitySignals, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, type TargetScope, type TopicIR, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerQueueProducerIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, capabilitiesUsedBy, companionServiceBinding, createCodegenProject, createTargetScope, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyChannels, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitInternalApi, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitScheduler, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findCodegenConfigFile, findProjectConfigFile, findTsconfig, fingerprintSchemaSources, foldCapabilitySignals, formatAdvisories, indexReferencesOf, isD1GlobalTable, isHyperdriveGlobalTable, isTestPath, lintSchema, listLunoraSourceFiles, loadProjectConfig, mayReadCapabilityContext, parseSchemaSnapshot, platformMatrixIds, projectConfigCandidatePaths, readBoundServiceBindings, readDevServiceBindings, readPackageDependencies, readProjectConfigLiterals, readProjectLazyFunctions, readProjectSecurityHeaders, readProjectTarget, readServiceBindings, redact, refreshCodegenProject, resolveCodegenTarget, resolveServiceBindings, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, sortedUniqueNames, sourceCapabilitySignals, toAdvisorContext, tsconfigFingerprint, validatorIrToJsonSchema };
|
|
5106
|
+
export { AGENTS_FILENAME, ALL_NOTIFY_CHANNELS, type AgentIR, type ArchitectureManifest, type AuthApiCallIR, CAPABILITY_PROBES, COMPANION_BINDING, COMPANION_SERVICE_NAME, CONTAINERS_FILENAME, type CapabilityKey, type CapabilityProbe, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContainerImageIR, type ContainerNamedImageIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DefaultScheduledContainerIR, type DriftChange, type DriftRemediation, type DriftScope, type DurableObjectScheduledContainerIR, ENV_FILENAME, type EmitAppOptions, FLAGS_FILENAME, type FcmCredentials, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexReference, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, type LoadedProjectConfig, type LunoraProjectConfig, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, type NotifyChannels, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, PROJECT_CONFIG_FILENAMES, type PlatformDiagnostic, type ProjectConfigLiterals, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ServiceBindingIR, type ServiceLiteral, type ShapeIR, type SourceCapabilitySignals, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, type TargetScope, type TopicIR, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerQueueProducerIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, capabilitiesUsedBy, companionServiceBinding, createCodegenProject, createTargetScope, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyChannels, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitInternalApi, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitScheduler, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findCodegenConfigFile, findProjectConfigFile, findTsconfig, fingerprintSchemaSources, foldCapabilitySignals, formatAdvisories, indexReferencesOf, isD1GlobalTable, isHyperdriveGlobalTable, isTestPath, lintSchema, listLunoraSourceFiles, loadProjectConfig, mayReadCapabilityContext, parseSchemaSnapshot, platformMatrixIds, projectConfigCandidatePaths, readBoundServiceBindings, readDevServiceBindings, readPackageDependencies, readProjectConfigLiterals, readProjectLazyFunctions, readProjectSecurityHeaders, readProjectTarget, readServiceBindings, redact, refreshCodegenProject, resolveCodegenTarget, resolveServiceBindings, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, sortedUniqueNames, sourceCapabilitySignals, toAdvisorContext, tsconfigFingerprint, validatorIrToJsonSchema };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as S}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-BuNEmlCO.mjs";import{COMPANION_BINDING as u,COMPANION_SERVICE_NAME as N}from"./packem_shared/COMPANION_BINDING-Da_v9XpC.mjs";import{CodegenDiagnosticError as g,diagnosticAt as C}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as I,discoverAgents as _}from"./packem_shared/AGENTS_FILENAME-D0Y0_UgB.mjs";import{isTestPath as L,listLunoraSourceFiles as M}from"./packem_shared/isTestPath-DRIdZaij.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-ENLGem4M.mjs";import{CONTAINERS_FILENAME as P,discoverContainers as D}from"./packem_shared/CONTAINERS_FILENAME-J-e3Vanb.mjs";import{default as b}from"./packem_shared/discoverCrons-DWVXmktw.mjs";import{ENV_FILENAME as U}from"./packem_shared/ENV_FILENAME-COPIfgzp.mjs";import{capabilitiesUsedBy as H,createTargetScope as j,foldCapabilitySignals as V,mayReadCapabilityContext as k,sourceCapabilitySignals as W}from"./packem_shared/capabilitiesUsedBy-BwhaHK08.mjs";import{FLAGS_FILENAME as K,discoverFlags as Q}from"./packem_shared/FLAGS_FILENAME-6RzszxVW.mjs";import{d as q}from"./packem_shared/index-jtzAVdUp.mjs";import{default as J}from"./packem_shared/discoverHttpRoutes-CAoEemno.mjs";import{default as Z}from"./packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs";import{default as ee}from"./packem_shared/discoverInserts-DmSa4WKU.mjs";import{d as oe}from"./packem_shared/index-mFEIaT45.mjs";import{default as ie}from"./packem_shared/discoverMigrations-Duh6HVG3.mjs";import{MUTATORS_FILENAME as se,discoverMutators as de}from"./packem_shared/MUTATORS_FILENAME-C3OImAxC.mjs";import{default as me}from"./packem_shared/discoverNondeterministicCalls-BoF6ob-B.mjs";import{ALL_NOTIFY_CHANNELS as ne,NOTIFY_FILENAME as ce,discoverNotifyCalls as le,discoverNotifyChannels as Se,discoverNotifyConfig as xe}from"./packem_shared/ALL_NOTIFY_CHANNELS-CtrsBtZX.mjs";import{default as Ae}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as Ne}from"./packem_shared/discoverQueries-spxu-wHR.mjs";import{QUEUES_FILENAME as ge,discoverQueues as Ce}from"./packem_shared/QUEUES_FILENAME-Ba-sK5Ek.mjs";import{default as Ie}from"./packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs";import{default as Re}from"./packem_shared/discoverRlsProcedures-mjiA0I4S.mjs";import{default as Me}from"./packem_shared/discoverRlsMetadata-Cc0zA-gZ.mjs";import{discoverSandboxUsage as Fe}from"./packem_shared/discoverSandboxUsage-Ccy9n7G1.mjs";import{default as Pe}from"./packem_shared/discoverSchema-ynieYB0n.mjs";import{companionServiceBinding as ye,readBoundServiceBindings as be,readDevServiceBindings as Ge,readServiceBindings as Ue,resolveServiceBindings as Be}from"./packem_shared/companionServiceBinding-BZjm486n.mjs";import{SHAPES_FILENAME as je,discoverShapes as Ve}from"./packem_shared/SHAPES_FILENAME-CH0KrAdb.mjs";import{default as We}from"./packem_shared/discoverStorageRulesMetadata-CtE5trUR.mjs";import{WORKFLOWS_FILENAME as Ke,discoverWorkflows as Qe}from"./packem_shared/WORKFLOWS_FILENAME-DfVfBum_.mjs";import{emitApp as qe}from"./packem_shared/emitApp-C3IUdkkt.mjs";import{isD1GlobalTable as Je,isHyperdriveGlobalTable as Xe}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as $e,emitOpenApi as er,emitOpenApiModule as rr}from"./packem_shared/buildOpenApiDocument-B8KEeeRr.mjs";import{OPENRPC_VERSION as tr,buildOpenRpcDocument as ir,emitOpenRpc as ar,emitOpenRpcModule as sr}from"./packem_shared/OPENRPC_VERSION-UNYmA7Ty.mjs";import{DEFAULT_TARGET as fr,platformMatrixIds as mr,readProjectTarget as pr,resolveCodegenTarget as nr}from"./packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs";import{b as lr,r as Sr,c as xr,d as Er}from"./packem_shared/project-config-file-DR7xrrNB.mjs";import{PROJECT_CONFIG_FILENAMES as ur,findCodegenConfigFile as Nr,findProjectConfigFile as vr,projectConfigCandidatePaths as gr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Or,runCodegen as Ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-DvMqIcXC.mjs";import{SchemaSnapshotParseError as Rr,buildSchemaSnapshot as Lr,evaluateSchemaDrift as Mr,indexReferencesOf as Tr,parseSchemaSnapshot as Fr}from"./packem_shared/SchemaSnapshotParseError-DnAuFdpl.mjs";import{default as Pr}from"./packem_shared/fingerprintSchemaSources-C8H1wOcH.mjs";import{schemaFromIr as yr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Gr,validatorIrToJsonSchema as Ur}from"./packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{SDK_LANGUAGES as Hr,SDK_TARGETS as jr,generateSdk as Vr}from"./sdk/index.mjs";import{redact as Wr,secretKindOf as zr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Qr}from"./packem_shared/emitDrizzleSchema-BzOChEYW.mjs";import{e as qr}from"./packem_shared/server-CRFaUMKQ.mjs";import{e as Jr}from"./packem_shared/shard-Csztu3jG.mjs";import{G as Zr}from"./packem_shared/shared-Cn7dMQ_u.mjs";import{MESSAGE_SOLUTIONS as eo,findSolutionByMessage as ro}from"@lunora/errors";import{createCodegenProject as to,findTsconfig as io,refreshCodegenProject as ao,tsconfigFingerprint as so}from"./packem_shared/createCodegenProject-Cfr1xHPC.mjs";import{t as mo,u as po,v as no}from"./packem_shared/shard-runtime-D0xuE0pX.mjs";import{emitApi as lo,emitCollections as So,emitInternalApi as xo}from"./packem_shared/emitApi-lwadq5G7.mjs";import{emitCrons as Ao,emitScheduler as uo,emitVectors as No,emitWranglerCronTriggers as vo}from"./packem_shared/emitCrons-CCRKs482.mjs";import{emitDataModel as Co}from"./packem_shared/emitDataModel-BvCZS4Yq.mjs";import{emitFunctions as Io}from"./packem_shared/emitFunctions-ppMX7E3X.mjs";import{isTypedSchema as Ro}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{I as AGENTS_FILENAME,ne as ALL_NOTIFY_CHANNELS,E as CAPABILITY_PROBES,u as COMPANION_BINDING,N as COMPANION_SERVICE_NAME,P as CONTAINERS_FILENAME,g as CodegenDiagnosticError,fr as DEFAULT_TARGET,U as ENV_FILENAME,K as FLAGS_FILENAME,Zr as GENERATED_HEADER,Gr as LUNORA_ERROR_CODES,eo as LUNORA_SOLUTION_RULES,se as MUTATORS_FILENAME,ce as NOTIFY_FILENAME,tr as OPENRPC_VERSION,ur as PROJECT_CONFIG_FILENAMES,ge as QUEUES_FILENAME,Or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Hr as SDK_LANGUAGES,jr as SDK_TARGETS,je as SHAPES_FILENAME,Rr as SchemaSnapshotParseError,e as VERSION,Ke as WORKFLOWS_FILENAME,$e as buildOpenApiDocument,ir as buildOpenRpcDocument,Lr as buildSchemaSnapshot,H as capabilitiesUsedBy,ye as companionServiceBinding,to as createCodegenProject,j as createTargetScope,n as describeErrorLevelFindings,C as diagnosticAt,i as diffSchemaSnapshots,_ as discoverAgents,F as discoverAuthApiCalls,D as discoverContainers,b as discoverCrons,Q as discoverFlags,q as discoverFunctions,J as discoverHttpRoutes,Z as discoverHyperdriveCalls,ee as discoverInserts,oe as discoverMaskProcedures,ie as discoverMigrations,de as discoverMutators,me as discoverNondeterministicCalls,le as discoverNotifyCalls,Se as discoverNotifyChannels,xe as discoverNotifyConfig,Ne as discoverQueries,Ce as discoverQueues,Ie as discoverR2sqlCalls,Me as discoverRlsMetadata,Re as discoverRlsProcedures,Fe as discoverSandboxUsage,Pe as discoverSchema,Ve as discoverShapes,We as discoverStorageRulesMetadata,Qe as discoverWorkflows,mo as emitAgents,lo as emitApi,qe as emitApp,So as emitCollections,po as emitContainers,Ao as emitCrons,Co as emitDataModel,Qr as emitDrizzleSchema,Io as emitFunctions,xo as emitInternalApi,er as emitOpenApi,rr as emitOpenApiModule,ar as emitOpenRpc,sr as emitOpenRpcModule,uo as emitScheduler,qr as emitServer,Jr as emitShard,No as emitVectors,no as emitWorkflows,vo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Mr as evaluateSchemaDrift,Nr as findCodegenConfigFile,ro as findLunoraSolution,vr as findProjectConfigFile,io as findTsconfig,Pr as fingerprintSchemaSources,V as foldCapabilitySignals,d as formatAdvisories,Vr as generateSdk,Tr as indexReferencesOf,Je as isD1GlobalTable,Xe as isHyperdriveGlobalTable,L as isTestPath,Ro as isTypedSchema,f as lintSchema,M as listLunoraSourceFiles,lr as loadProjectConfig,k as mayReadCapabilityContext,Fr as parseSchemaSnapshot,mr as platformMatrixIds,gr as projectConfigCandidatePaths,be as readBoundServiceBindings,Ge as readDevServiceBindings,Ae as readPackageDependencies,Sr as readProjectConfigLiterals,xr as readProjectLazyFunctions,Er as readProjectSecurityHeaders,pr as readProjectTarget,Ue as readServiceBindings,Wr as redact,ao as refreshCodegenProject,nr as resolveCodegenTarget,Be as resolveServiceBindings,Ir as runCodegen,yr as schemaFromIr,zr as secretKindOf,a as serializeSchemaSnapshot,S as sortedUniqueNames,W as sourceCapabilitySignals,m as toAdvisorContext,so as tsconfigFingerprint,Ur as validatorIrToJsonSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as l}from"node:fs";import{join as d}from"node:path";import{SyntaxKind as c,Node as i}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as m}from"./module-specifiers-BctA0m_p.mjs";import{a as u}from"./attribution-BhGR_h0Z.mjs";const p="env.ts",g=e=>{const n=e.getSymbol();if(!n)return e.getText()==="defineEnv";for(const t of n.getDeclarations())if(i.isImportSpecifier(t))return m(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineEnv":!1;return!1},v=e=>{const n=e.getSymbol();if(!n)return!1;for(const t of n.getDeclarations()){if(!i.isNamespaceImport(t))continue;const o=t.getFirstAncestorByKind(c.ImportDeclaration);return o!==void 0&&m(o.getModuleSpecifierValue())}return!1},E=e=>{if(i.isIdentifier(e))return g(e);if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(n)&&v(n)}return!1},x=e=>{const n=[];for(const t of e.getVariableDeclarations()){const o=t.getInitializer();if(o?.getKind()!==c.CallExpression||!E(o.getExpression()))continue;const s=t.getNameNode();if(!i.isIdentifier(s)){if(t.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw f(s,"defineEnv exports must be plain named exports (no destructuring)")}const a=u(t,"member");a!==void 0&&n.push({exportName:a})}return n},D=(e,n)=>{const t=d(n,p);if(!l(t))return;const o=e.getSourceFile(t)??e.addSourceFileAtPath(t),r=x(o);if(r.length!==0){if(r.length>1)throw f(o,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(s=>s.exportName).join(", ")}); exactly one is allowed`);return r[0]}};export{p as ENV_FILENAME,D as discoverEnv};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import{existsSync as z,readFileSync as Xe,mkdirSync as jt,writeFileSync as Or,rmSync as fe,readdirSync as Ht}from"node:fs";import{dirname as Ze,join as v,basename as kr,relative as Gt}from"node:path";import{performance as St}from"node:perf_hooks";import{runAdvisor as Rr}from"@lunora/advisor";import{LunoraError as R}from"@lunora/errors";import{serializeSchemaSnapshot as Fr}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Lr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Yt,ts as Dr,VariableDeclarationKind as Qt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as I,descendantsOfKind as E,bindingKeyName as pe,collectCallRows as O,findObjectProperty as q,collectSecurityCallRows as _r,propertyInitializer as L,listSecurityScanFiles as et,objectLiteralFromCallbackBody as _n,limitNameOf as Mn,optionsObjectLiteral as zn,handlerOf as Mr,collectNodeRows as ae,chainRootOf as tt,outermostValueWrapper as T,isWriteTarget as st,isSameNode as N,unwrapExpression as h,isConstDeclaration as ce,memberAccessOf as Jt,returningFunctionOf as kt,walkChain as zr,RUN_METHODS as $n,functionReferenceSegments as $r,isTestPath as Kr,isFunctionLike as le,functionKeyOf as Kn,withSourceListMemo as Br}from"./isTestPath-DRIdZaij.mjs";import{j as Z,h as Y,d as D,b as Xt,c as S,a as Zt,w as es,k as Vr,l as Ur,f as Wr,m as qr,g as Rt,i as jr}from"./attribution-BhGR_h0Z.mjs";import{b as Bs,r as At,a as J,e as Hr,m as Bn,c as nt,f as ts,E as Vn,C as Un,d as Gr,g as Yr,i as Qr}from"./context-root-DnvrQxae.mjs";import{a as C,i as Wn,c as ie,d as qn,e as Jr,f as Xr,g as jn}from"./classify-procedure-call-BZ164dkJ.mjs";import{a as A,s as Zr}from"./property-name-7cBlgK_O.mjs";import{b as eo,a as Hn}from"./module-specifiers-BctA0m_p.mjs";import{r as it,s as to}from"./parse-validator-BisfC8bR.mjs";import so from"./discoverAuthApiCalls-ENLGem4M.mjs";import{i as $,r as Gn}from"./database-calls-BRI5W-Mp.mjs";import{i as Ft,p as Yn,w as no,d as io}from"./index-jtzAVdUp.mjs";import ro from"./discoverHyperdriveCalls-BaRayTZe.mjs";import{diagnosticAt as Ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ss,a as qe,s as Qn,d as oo}from"./index-mFEIaT45.mjs";import{MUTATORS_FILENAME as ao,isDefineMutatorCallee as co,mutatorServerImplOf as lo,discoverMutators as uo}from"./MUTATORS_FILENAME-C3OImAxC.mjs";import fo from"./discoverNondeterministicCalls-BoF6ob-B.mjs";import{discoverNotifyConfig as po,discoverNotifyCalls as go}from"./ALL_NOTIFY_CHANNELS-CtrsBtZX.mjs";import mo from"./discoverR2sqlCalls-CZjqFVi_.mjs";import ho from"./discoverRlsProcedures-mjiA0I4S.mjs";import{s as ns,n as vo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Eo,redact as xo,isHeuristicSecretKind as So,isSecretishName as Ao}from"./redact-Cy14LEnc.mjs";import{r as Jn,p as yo,c as bo,a as No,e as Po,d as wo}from"./project-config-file-DR7xrrNB.mjs";import{a as _e,d as Io,r as Co}from"./modules-Qpm_zqz4.mjs";import{WORKFLOWS_FILENAME as To,discoverWorkflows as Oo}from"./WORKFLOWS_FILENAME-DfVfBum_.mjs";import{r as ko}from"./json-data-Chfs2Cz5.mjs";import{a as Ro,I as Fo,g as Lo,G as Xn,d as Do,i as _o}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as Mo}from"./createCodegenProject-Cfr1xHPC.mjs";import{findTsconfig as lx,refreshCodegenProject as dx,tsconfigFingerprint as ux}from"./createCodegenProject-Cfr1xHPC.mjs";import{wranglerString as zo,wranglerValue as $o,companionName as Ko,COMPANION_FILES as Bo}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as Vo,usedCapabilities as Uo}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Zn,isHyperdriveGlobalTable as ei}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Wo}from"./AGENTS_FILENAME-D0Y0_UgB.mjs";import{discoverContainers as qo}from"./CONTAINERS_FILENAME-J-e3Vanb.mjs";import jo from"./discoverCrons-DWVXmktw.mjs";import{discoverEnv as Ho}from"./ENV_FILENAME-COPIfgzp.mjs";import{contextPropertiesRead as Go,createTargetScope as Yo,fileWiresRequestSecretTool as Qo,discoverFeatureUsage as Jo}from"./capabilitiesUsedBy-BwhaHK08.mjs";import ti from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Xo,findProjectConfigFile as si,findCodegenConfigFile as Zo}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as ea}from"./QUEUES_FILENAME-Ba-sK5Ek.mjs";import{discoverSandboxUsage as ta}from"./discoverSandboxUsage-Ccy9n7G1.mjs";import{resolveServiceBindings as sa}from"./companionServiceBinding-BZjm486n.mjs";import na from"./discoverStorageRulesMetadata-CtE5trUR.mjs";import{resolveCodegenTarget as Me,gatePlatformFeatures as ia,readTargetDiagnostics as ra,vectorizeDimensionDiagnostics as oa,liveStreamsDeliveryAuthorizationDiagnostic as aa,socketRoutesDeliveryAuthorizationDiagnostic as ca,studioPlatformFor as la,platformFeatureAvailable as da,gateAdminTokenRevocation as ua}from"./DEFAULT_TARGET-CVYzxQ0y.mjs";import{i as fa}from"./schema-BgM8A3XV.mjs";import{b as ni,e as pa}from"./shard-Csztu3jG.mjs";import{e as ga,a as ma}from"./server-CRFaUMKQ.mjs";import{emitDataModel as ha}from"./emitDataModel-BvCZS4Yq.mjs";import{i as va,b as Ea,e as xa,d as Sa,f as Aa,c as ya}from"./unwrap-handler-return-DUzluwPj.mjs";import ba from"./discoverHttpRoutes-CAoEemno.mjs";import Na from"./discoverInserts-DmSa4WKU.mjs";import{e as ii}from"./exported-procedure-chains-h8Y7xDjq.mjs";import Pa from"./discoverMigrations-Duh6HVG3.mjs";import Vs from"./discoverQueries-spxu-wHR.mjs";import wa from"./discoverRlsMetadata-Cc0zA-gZ.mjs";import Ia from"./discoverSchema-ynieYB0n.mjs";import{discoverShapes as Ca}from"./SHAPES_FILENAME-CH0KrAdb.mjs";import{i as Ta}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as Oa,emitApp as ka}from"./emitApp-C3IUdkkt.mjs";import{readJsonSync as Ra}from"@visulima/fs";import{indexReferencesOf as Fa,buildSchemaSnapshot as La}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Da,emitOpenApiModule as _a}from"./buildOpenApiDocument-B8KEeeRr.mjs";import{buildOpenRpcDocument as Ma,emitOpenRpcModule as za}from"./OPENRPC_VERSION-UNYmA7Ty.mjs";import{w as $a,u as Ka,v as Ba,t as Va,x as Ua}from"./shard-runtime-D0xuE0pX.mjs";import{emitCollections as Wa,emitSeed as qa,emitApi as ja,emitInternalApi as Ha}from"./emitApi-lwadq5G7.mjs";import{emitCrons as Ga,emitScheduler as Ya,emitAdminRevocations as Qa,emitShardRegistry as Ja,emitDurableObjects as Xa,emitVectors as Za,emitWranglerCronTriggers as ec}from"./emitCrons-CCRKs482.mjs";import tc from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as ri,emitFunctions as sc,emitLazyFunctionModules as nc}from"./emitFunctions-ppMX7E3X.mjs";const ic=(e,t=!1)=>{if(e.length===0)return"";const s=Do(t),n=e.map(c=>{if(Ro(c.exportName,"live stream export name"),!Fo.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{Lo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${p} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(_=>`\${encodeURIComponent(key.${_})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${p} => ({
|
|
2
|
+
__lunoraLive: ${m},
|
|
3
|
+
topic: \`${u.name}:${x}\`,
|
|
4
|
+
}),`});return` ${c.exportName}: {
|
|
5
|
+
${l.join(`
|
|
6
|
+
`)}
|
|
7
|
+
},`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${Xn}import type { ${a} } from "${s.server}";
|
|
8
|
+
|
|
9
|
+
${n.join(`
|
|
10
|
+
`)}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A typed reference to each declared live topic, grouped by the stream's export name:
|
|
14
|
+
* \`live.posts.post({ postId })\`. Pass one to \`ctx.live.publish(ref, payload)\` on the server, or to a
|
|
15
|
+
* live-topic hook in the browser. A reference is plain data and carries no server code.
|
|
16
|
+
*/
|
|
17
|
+
export const live = {
|
|
18
|
+
${i.join(`
|
|
19
|
+
`)}
|
|
20
|
+
};
|
|
21
|
+
`},oi=new Set(["delete","get","head","options","patch","post","put"]),rc=new Set(["handler","stream"]),oc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Us=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),ac=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!oi.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},cc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||oi.has(n.getName()))break;s=n.getExpression()}return ac(s)},lc=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Us.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Us.has(s.getText()))return!0}return!1},dc=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!rc.has(n.getName()))return;const i=cc(s);if(!i||!oc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&lc(o);return{exportName:Y(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},uc=(e,t)=>{const s=[];for(const n of Z(e)){const i=dc(n,t);i&&s.push(i)}return s},fc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...uc(i,I(t,n)))}return s},pc=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},gc=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?pe(t):void 0}},mc=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Bs(a)}))return!1;const n=D(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Bs(i)},Ws=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=pc(e);return n!==void 0&&gc(n)===t?!0:t==="args"&&mc(e)},ai=(e,t)=>r.isIdentifier(e)?Ws(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Ws(s,t)),hc=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},qs=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Xt(t)?t.getInitializer():void 0},Lt=e=>ai(e,"args"),X=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of E(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},G=e=>{if(Lt(e))return!0;const t=X(e);return t!==void 0&&Lt(t)},vc=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=X(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},ge=e=>{if(At(e))return!0;const t=qs(e);if(t!==void 0&&At(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=qs(i);return o!==void 0&&At(o)})},ze=(e,t)=>ai(e,t),Ec=(e,t)=>{if(ze(e,t))return!0;const s=X(e);if(s!==void 0&&ze(s,t))return!0;const n=hc(e);if(n!==void 0){const i=X(n);return i!==void 0&&ze(i,t)}return!1},xc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:J(e.getExpression(),["ai"]),Sc=(e,t)=>{if(!xc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)||ge(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Ac=(e,t)=>O(e,t,Sc),yc=new Set(["generateText","streamText"]),bc=new Set(["messages","prompt","system"]),Nc=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Pc=(e,t)=>Nc.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),wc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Hr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Pc(i,s));return n===void 0?void 0:`${n}.${s}`},Ic=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=wc(t);if(s!==void 0)return s}},Cc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=pe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Tc=e=>{if(Lt(e))return!0;const t=Cc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},Oc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!bc.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&Tc(s))return!0}return!1},kc=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=C(n.getExpression());if(i===void 0||!yc.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(C(c.getExpression())==="tool"&&(a=Ic(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Oc(o)})}return s},Rc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kc(i,I(t,n)))}return s},Fc=e=>J(e,["fetch"]),Lc=(e,t)=>{if(!Fc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Dc=(e,t)=>O(e,t,Lc),is=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=it(s.getExpression());return n===void 0||is(n,t)})}finally{t.delete(e)}},_c=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=q(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:it(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:is(i)}},Mc=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?it(o):void 0;a===void 0?s=!0:(t.push(a),s||=is(a))}n=i.getExpression()}return{objects:t,opaque:s}},rs=(e,t)=>t?Mc(t):_c(e),ci=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=it(s.getExpression());return n===void 0?[]:ci(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},zc=e=>e.flatMap(t=>ci(t,new Set)),$c=new Set(["check","length","max"]),Dt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if($c.has(s.getName()))return!0;t=n}},_t=e=>eo(e)||e==="@lunora/values",Kc=e=>{const t=new Set(["v"]);for(const s of Wn(e,"v",_t))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&_t(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Bc=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},Vc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Uc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&_t(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),os=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return Vc(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Uc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Wc=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},qc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},jc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Hc=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>qc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=jc(t);return s?[s]:[]}),li=(e,t)=>{if(os(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return li(e.getExpression(),t)},Gc=(e,t)=>{const s=Wc(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Dt(e),i=new Set(Hc(s).map(o=>li(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=os(o,t);return a===void 0?[]:[{bounded:Dt(o)||n&&i.has(o),factory:a}]})},Yc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=os(s,t),i=n===void 0?[]:[{bounded:Dt(s),factory:n}];return r.isCallExpression(s)?[...i,...Gc(s,t)]:i}),Qc=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Yc(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Jc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ie(n);if(i?.visibility!=="public")return;const{objects:o}=rs(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Qc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Y(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Xc=(e,t)=>{const s=[],n=Kc(e),i={destructured:Bc(e,n),namespaces:n};for(const o of Z(e)){const a=Jc(o,t,i);a&&s.push(a)}return s},Zc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xc(i,I(t,n)))}return s},yt=e=>e?.getKind()===d.TrueKeyword,el=e=>e?.getKind()===d.FalseKeyword,tl=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,sl=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),nl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&C(t.getExpression())==="scim"),il=e=>e!==void 0&&r.isCallExpression(e)&&sl.has(C(e.getExpression())??""),rl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),ol=e=>{const t=L(e,"advanced"),s=L(e,"emailAndPassword"),n=L(e,"session");return{analyzable:!0,disableCsrfCheck:yt(L(t,"disableCSRFCheck")),emailPasswordEnabled:yt(L(s,"enabled")),requireEmailVerification:yt(L(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:nl(L(e,"plugins"))&&il(L(e,"database")),secureCookiesDisabled:el(L(t,"useSecureCookies")),sessionFreshAgeZero:tl(L(n,"freshAge")),trustedOriginsWildcard:rl(L(e,"trustedOrigins"))}},al=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),cl=(e,t)=>{if(C(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?ol(s):al();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},ll=(e,t)=>_r(e,t,cl),dl=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Bn(e.getExpression(),t.matchReceiver)?s:void 0},ul=(e,t,s)=>{const n=dl(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!G(i)||ge(i))&&!(s.requireUnmodifiedReach===!0&&!vc(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},rt=(e,t,s)=>O(e,t,(n,i)=>ul(n,i,s)),fl=new Set(["content","pdf","scrape","screenshot"]),pl=(e,t)=>rt(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:fl}),gl=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),ml=new Set(["RateLimiter"]),hl=new Set(["extend"]),js="lunora",vl=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],di=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Mt=e=>e&&r.isObjectLiteralExpression(e)?di(e):{analyzable:!1,presentKeys:[],trueKeys:[]},El=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&_n(t.getBody());return s?di(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},xl=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=C(n.getExpression());i!==void 0&&(gl.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Mt(n.getArguments()[0])}):hl.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...El(n.getArguments()[0])}))}for(const n of E(e,d.NewExpression)){const i=C(n.getExpression());i===void 0||!ml.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Mt(n.getArguments()[0])})}return s},Sl=e=>{for(const t of vl){const s=v(e,t);if(!z(s))continue;const n=new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Xe(s,"utf8")),i=[];for(const o of E(n,d.CallExpression))C(o.getExpression())===js&&i.push({callee:js,file:t,line:o.getStartLineNumber(),...Mt(o.getArguments()[0])});return i}return[]},Al=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...xl(o,n))}return s.push(...Sl(Ze(t))),s},Hs="ctx.containers.",yl=e=>{if(!e.startsWith(Hs))return!1;const t=e.slice(Hs.length);return t.length>0&&!t.includes(".")},bl=(e,t)=>rt(e,t,{argIndex:0,matchReceiver:yl,methods:new Set(["get"])}),Nl=new Set(["allow","deny","setAllowed"]),Pl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=q(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},wl=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Pl(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Il=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Nl.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Cl=(e,t)=>wl(e,t)??Il(e,t),Tl=(e,t)=>O(e,t,Cl),Ol=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&$(s.getExpression())?s.getName():void 0},kl=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&$(s)?1:0]},Rl=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Fl=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>Rl.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Ll=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=Ol(i);if(a===void 0)return;const c=Fl(kl(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},Dl=new Set(["defineExportSink","r2Sink","webhookExportSink"]),_l=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Dl.has(s)?s:void 0},Ml=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},zl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of E(o,d.CallExpression)){const c=_l(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Ml(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},$l=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Kl=new Set(["dbRateLimit","rateLimit"]),Bl=e=>{const t=zn(e);if(!t)return!1;const s=q(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Vl=(e,t)=>{const s=C(e.getExpression());if(s===void 0)return;const n=$l.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:Bl(e.getArguments()[n]),file:t,limitName:Kl.has(s)?Mn(e):"",line:e.getStartLineNumber()}},Ul=(e,t)=>O(e,t,Vl),Wl=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ie(t);if(s?.kind!=="query")return;const n=Mr(t,s.receiver);return n?{exportName:Y(e)??e.getName(),handler:n}:void 0},Gs=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},ql=e=>{const t=Gs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Gs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},jl=(e,t)=>{const s=[];for(const n of nt(e.handler,"flags"))s.push({callee:ql(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Hl=(e,t)=>{const s=[];for(const n of Z(e)){const i=Wl(n);i&&s.push(...jl(i,t))}return s},Gl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hl(i,I(t,n)))}return s},Yl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:J(e.getExpression(),["flags"]),Ql=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Jl=(e,t)=>{if(!Yl(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Ql(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},Xl=(e,t)=>O(e,t,Jl),Zl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},ed=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},td=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of E(i,d.CallExpression))Zl(a)&&s.push({file:o,indexName:ed(a),line:a.getStartLineNumber()})}return s},sd=new Set(["delete","get","head","options","patch","post","put"]),nd=new Set(["handler","stream"]),id=new Set(["runAction","runMutation"]),rd=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Ce=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,ui=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(pe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Ys=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:ui(s,"ctx")},Qs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:ui(s,"request")},Js=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(id.has(a)&&Ce(c,t))return a;if(rd.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Ce(c.getExpression(),t))return`db.${a}`}},Xs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Ce(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Ce(n.getInitializer(),t))){for(const o of i.getElements())if(pe(o)==="auth")return!0}}return!1},od=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ad=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Ce(n.getExpression(),t)},cd=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],fi=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:cd(s)},ld=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?fi(t,a.getText()):[]}return[]},dd=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=fi(s,t.getText());return n.length>0?n:ld(t,s)},Zs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>ad(i,t)&&dd(i).some(o=>od.test(o)))},ud=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!nd.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(sd.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},fd=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ft(e.getArguments()[0]),l=c&&Ys(c,!0);if(!c||l===void 0||Zs(c,Qs(c,!0)))return;const u=Js(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Xs(c,l),sideEffect:u}}const n=ud(e);if(n===void 0)return;const i=Ft(e.getArguments()[0]),o=i&&Ys(i,!1);if(!i||o===void 0||Zs(i,Qs(i,!1)))return;const a=Js(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Xs(i,o),sideEffect:a}},pd=(e,t)=>O(e,t,fd),gd=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),md=new Set(["append","set"]),pi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",en=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>gd.has(C(n.getExpression())??"")&&ze(n,t)),hd=(e,t)=>{if(en(e,t))return!0;const s=X(e);return s!==void 0&&en(s,t)},zt=(e,t)=>Ec(e,t)&&!hd(e,t),vd=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=X(e);return t!==void 0&&r.isNewExpression(t)&&C(t.getExpression())==="Headers"},je=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=X(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},as=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:pi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=je(n.getExpression());i!==void 0&&as(i,t,s)}},gi=(e,t)=>{const s=je(e);if(s===void 0)return;const n=q(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=je(n.getInitializer());i!==void 0&&as(i,"response-init",t)},Ed=(e,t)=>{const s=C(e.getExpression());if(s==="Response")gi(e.getArguments()[1],t);else if(s==="Headers"){const n=je(e.getArguments()[0]);n!==void 0&&as(n,"headers-ctor",t)}},xd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){gi(e.getArguments()[1],t);return}if(md.has(n)&&vd(i)){const o=e.getArguments()[1];o!==void 0&&zt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:pi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Sd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Ed(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))xd(s,t)},Ad=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ft(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return Sd(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},yd=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression))s.push(...Ad(n,t));return s},bd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...yd(i,I(t,n)))}return s},mi="identity.ts",Nd=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Hn(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Pd=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Hn(n.getModuleSpecifierValue())}return!1},wd=e=>{if(r.isIdentifier(e))return Nd(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Pd(t)}return!1},Id=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!wd(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Ee(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Zt(s,"member");a!==void 0&&t.push({exportName:a})}return t},Cd=(e,t)=>{const s=v(t,mi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Id(n);if(i.length!==0){if(i.length>1)throw Ee(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Td=new Set(["auth","context.auth"]),Od="userId",kd=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},Rd=(e,t)=>{const s=v(t,mi);if(!z(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(C(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?kd(o):void 0}},tn=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Td.has(t.getText())||J(t,["auth"])?e:void 0},Fd=e=>{if(r.isPropertyAccessExpression(e)&&tn(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&tn(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},sn=(e,t,s)=>{const n=Fd(e);return n===void 0?void 0:{declared:n===Od||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},Ld=(e,t)=>{const s=Rd(e,t);return s===void 0?[]:[...ae(e,t,d.PropertyAccessExpression,(n,i)=>sn(n,i,s)),...ae(e,t,d.ElementAccessExpression,(n,i)=>sn(n,i,s))]},Dd=(e,t)=>{if(C(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=L(s,"key");if(!(!n||!G(n)||ge(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},_d=(e,t)=>O(e,t,Dd),Md=new Set(["delete","get","getRaw","getWithMetadata","put"]),zd=(e,t,s=[])=>{const n=rt(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Md});return es(n,s)},$d=new Set(["queue","send"]),nn=new Set(["bcc","cc","to"]),Kd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!$d.has(t))return;const s=e.getExpression();return J(s,["mail"])||J(s,["email"])?t:void 0},Bd=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return nn.has(A(t))&&G(n)&&!ge(n)}if(!r.isPropertyAssignment(t)||!nn.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&G(s)&&!ge(s)}):!1,Vd=(e,t)=>{const s=Kd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Bd(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Ud=(e,t)=>O(e,t,Vd),Wd=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=qe(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=qe(l);if(u===void 0)continue;const f=Qn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},qd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;return n?.receiver?ss(n.receiver).flatMap(i=>Wd(i,Y(e)??e.getName(),t)):[]},jd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...qd(a,o))}return s},Hd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},Gd=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=q(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Yd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return co(s.getExpression())?s:void 0},Qd=e=>{const t=Yd(e),s=t===void 0?void 0:Gd(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?Y(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Hd(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Jd=e=>e.getVariableDeclarations().flatMap(t=>Qd(t)),Xd=(e,t)=>{const s=v(t,ao);if(!z(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Jd(n)},Zd=new Set(["delete","get","patch"]),eu=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),tu=new Set(["auth","identity","session","user"]),su=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),nu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!$(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},iu=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},ru=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),ou=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,au=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>ru(s.getExpression(),t)&&ou(s.getThenStatement())),cu=(e,t)=>{for(const s of E(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Zd.has(i))continue;const o=n.getExpression(),a=$(o);if(!(a||r.isPropertyAccessExpression(o)&&$(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},lu=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>ts(tt(s))!==void 0)),du=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>su.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),uu=e=>{for(const t of E(e,d.Identifier))if(eu.has(t.getText()))return!0;return[...tu].some(t=>nt(e,t).length>0)?!0:lu(e)||du(e)},fu=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&qn(n.receiver,"use","rls"),a=uu(i),c=new Set,l=[];for(const u of E(i,d.CallExpression)){const f=nu(u);if(f===void 0)continue;const p=iu(u);if(p===void 0||c.has(p)||!au(i,p))continue;const m=cu(i,p);m!==void 0&&(c.add(p),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},pu=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...fu(a,o))}return s},hi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},gu=e=>{const t=T(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!st(s)},mu=e=>{const t=T(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},hu=e=>{const s=T(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!st(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},He=e=>{const t=D(e);return t===void 0||Ur(t.getSourceFile())},$t=(e,t)=>{const s=T(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&He(o);if(hi(tt(o),t))return!(r.isPropertyAccessExpression(o)&&Vn.has(o.getName()))||r.isExpressionStatement(T(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!He(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},$e={kind:"opaque"},vu={kind:"unreached"},Eu=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Kt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=Eu(s);return i===void 0||Xt(i)?void 0:i}const n=ce(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},vi=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?$e:c===void 0?a.some(l=>l.isRestParameter())?$e:vu:c.isRestParameter()?$e:{kind:"parameter",parameter:c}},xu=e=>{const t=T(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Kt(s.getExpression());return n===void 0?$e:vi(n,s,t)},Su=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Au=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Ei=e=>{const t=T(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Au(s);if(n!==void 0)return N(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},yu=4,xi=(e,t,s=0)=>{if(Vr(e))return!0;if(gu(e)){const i=T(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!Su.has(c)}if(mu(e)||hu(e)||Ei(e)||$t(e,t))return!0;const n=xu(e);return n?.kind==="unreached"||n?.kind==="parameter"&&bu(n.parameter,s+1)},rn=new WeakMap,bu=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=rn.get(e.compilerNode);if(n!==void 0)return n;if(t>yu)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||xi(a,void 0,t));return(o||t===0)&&rn.set(e.compilerNode,o),o},on=new WeakMap,Nu=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=D(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Pu=(e,t,s)=>{const{context:n,impl:i}=e,o=on.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(p=>{const m=p.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(p=>[p.getText(),p.getParentOrThrow().compilerNode])),u=p=>r.isIdentifier(a)?xi(p,n):!st(p),f=!Nu(i,s)&&c.every(p=>(p.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(p=>{const m=p.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(p)||D(p)?.compilerNode!==x?!0:u(p)});return on.set(i.compilerNode,f),f},an=new WeakMap,wu=e=>{let t=an.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=lo(s);return n===void 0?[]:[[n.compilerNode,s]]})),an.set(e.compilerNode,t)),t},Iu=e=>{const t=wu(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:Y(n)??n.getName()};return a!==void 0&&Pu(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},bt="args",Ne=e=>{const t=Jt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===bt?t.member:void 0}if(!r.isIdentifier(e))return;const s=D(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ce(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&pe(i)===bt||r.isIdentifier(o)&&o.getText()===bt?pe(s):void 0},Cu=new Set(["auth","identity","user"]),Bt=e=>{const t=i=>{const o=ts(i);return o!==void 0&&o.length>0&&Cu.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=X(s);return n!==void 0&&t(n)},Si=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Ne(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?X(n):void 0;if(o!==void 0)for(const a of Si(o,t-1))s.add(a)}return s},Ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Ke(n),...Ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const p=Ne(h(u)??u);return p===void 0?[]:Ke(f).filter(m=>m===p)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Ne(h(n)??n),c=Ne(h(i)??i);return a!==void 0&&Bt(i)&&o.push(a),c!==void 0&&Bt(n)&&o.push(c),o},Tu=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&Jr(i.getExpression(),"defineIdentityGuard")},Ou=e=>{if(!Tu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Ne(h(s)??s),o=t.some((a,c)=>c!==n&&Bt(a));return i!==void 0&&o?[i]:[]})},ku=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},Ru=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),cn=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Fu=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Lu=(e,t)=>{const s=new Set;for(const n of E(e,d.IfStatement))if(n.getEnd()<=t&&cn(n,e)&&ku(n.getThenStatement()))for(const i of Ke(n.getExpression()))s.add(i);for(const n of E(e,d.CallExpression))if(n.getEnd()<=t&&Fu(n)&&cn(n,e))for(const i of Ou(n))s.add(i);return s},Du=(e,t)=>{const s=Si(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Ru);if(n===void 0)return!1;const i=Lu(n,e.getStart());return[...s].every(o=>i.has(o))},_u=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Mu=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Vt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Ai=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),zu=e=>{const t=T(e),s=t.getParent();if(r.isVariableDeclaration(s))return N(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},$u=e=>{const t=zu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ce(t)?[t]:void 0:Ai(t)},Pe=e=>e.isUnion()?e.getUnionTypes().every(t=>Pe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Pe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ge=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Be=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Ku=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&Mu.get(s.getText())?.has(t.getName())===!0&&He(s)},Bu=e=>{const t=kt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=T(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ge(n,Un)?n:void 0},Vu=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=T(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ge(n,_u,t)?n:void 0},Uu=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Wu=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&N(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},ln=e=>{const t=T(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Ku(s);return Vu(s,t)??Uu(s,t)??Wu(s,t)??(n?s:Bu(t))},qu=5e4,yi=()=>({inProgress:new Set,verdicts:new Map});class ju{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>qu&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Hu=8,Gu=8;class Yu{budget;scope;taint;verdicts=yi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Pe(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Ai(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Hu?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(T(l),!0,a,0))&&(t===n||!Pe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=ln(o);m!==void 0;m=ln(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=T(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Pe(o.getType());if(st(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=$u(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const p=this.nestedReturningFunctionOf(o);return p!==void 0?this.resultCompromises(p,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=T(t).getParent();if(n>=Gu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===T(t)?this.valueCompromises(i,!1,s,n+1):!Ge(i,Vt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ce(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=T(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Be(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ge(t,Vt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Kt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!$t(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if($t(s,this.scope.context))return!1;const i=Kt(t.getExpression()),o=i===void 0?void 0:vi(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Ei(t)||N(kt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=kt(t);return N(s,this.scope.impl)?void 0:s}}const Qu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Ju=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=D(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Xu=new Set(["all","allSettled","any","race"]),dn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,Nt=8;class Zu{budget=new ju;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=yi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Yu(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,Nt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Wr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=D(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(p=>p.getInitializer())].some(p=>p!==void 0&&this.isTaintedValue(p,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(p=>p.compilerNode===t.compilerNode):-1,o=T(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const p=h(a.getExpression());if(!r.isPropertyAccessExpression(p)||!Vt.has(p.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(p.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&ce(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(p=>{const m=T(p),x=m.getParent();return!r.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&He(i)&&Xu.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(p=>!r.isSpreadElement(p)&&this.isRootedInContext(p,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Be(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),i=dn(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Vn.has(i)?!1:i!==void 0&&Un.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Be(a)!==void 0)&&(i===void 0||!Qu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=tt(i),c=r.isIdentifier(a)?dn(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Be(i);if(o===void 0)return!Ju(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=zr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(hi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?D(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ce(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Xt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,Nt))return!1;if(this.variableDepth>=Nt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const un=new WeakMap,ef=e=>{const t=un.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Zu(e);return un.set(e.impl.compilerNode,s),s},tf=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),sf=new Set(["insert","insertManyUnsafe","patch","replace"]),nf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return sf.has(t)&&Gr(e.getExpression())?t:void 0},rf=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},of=(e,t)=>{const s=Jt(e);return s?.member===t?h(s.object):void 0},fn=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,bi=(e,t,s,n=1)=>{const i=of(e,s);if(i!==void 0)return fn(i,t);const o=r.isIdentifier(e)?D(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&pe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ce(l)&&fn(h(l.getInitializer()),t))}const a=ce(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&bi(a,t,s,n-1)},Ut=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ut(t.getWhenTrue()),...Ut(t.getWhenFalse())]:[t]},af=(e,t,s)=>{const n=[],i=s===void 0?void 0:ef(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!tf.has(a))continue;const l=Ut(c).filter(f=>i===void 0?G(f)&&!Yr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&bi(c,s.parameter,a),p=l.every(m=>Du(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...p&&{guarded:!0}})}}return n},cf=(e,t,s)=>{const n=nf(e.getExpression()),i=n==="patch"||n==="replace"?2:1,o=n===void 0?void 0:e.getArguments()[i];if(n===void 0||o===void 0)return[];const a=rf(o,n);if(a.length===0)return[];const c=S(e),l=Iu(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>af(f,u,l))},lf=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>cf(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return es(o,s).map(c=>qr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},df=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),uf=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,ff=e=>{const t=q(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?uf(t.getInitializer()):void 0},pf=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!df.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?ff(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},gf=(e,t)=>O(e,t,pf),mf=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),hf=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},vf=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=q(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Ni=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Pi=(e,t)=>e===t||e.startsWith(`${t}.`),wi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},pn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},Ii=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>pn(s));return r.isIdentifier(e)&&pn(e)&&t.push(e),t},Ef=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},xf=e=>{const t=Ni(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Sf=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:xf(e),i=new Set,o=a=>wi(a).some(c=>n.some(l=>Pi(c.getText(),l)))?!0:Ii(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Ef(a))i.add(l)}return{names:i,prefixes:n}},Af=(e,t)=>wi(e).some(s=>t.prefixes.some(n=>Pi(s.getText(),n)))?!0:Ii(e).some(s=>t.names.has(s.getText())),yf=e=>{const t=$r(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},bf=(e,t,s)=>{const n=Ni(e,0);if(n===void 0)return[];const i=Sf(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!$n.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Af(u,i))continue;const f=yf(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:S(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Nf=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=hf(n),o=i===void 0?void 0:mf.get(i);if(o===void 0)continue;const a=vf(n,o);a!==void 0&&s.push(...bf(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Pf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Nf(i,I(t,n)))}return s},gn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},mn=new Set(["account","credential","member","passkey","session","user"]),wf=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),If=e=>{const s=wf(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return mn.has(s)||mn.has(n)},Cf=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Tf=(e,t)=>{const{objects:s,opaque:n}=rs(e,t);return zc(s).some(i=>Cf(i))?!0:n?void 0:!1},Of=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!q(t,"captcha"),usesRateLimit:!!q(t,"rateLimit")}},kf=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Ve={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Rf=e=>{const t=kf(e),s=t?C(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Of(t);return{...Ve,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in gn?{...Ve,[gn[s]]:!0}:Ve},Ff=e=>{const t={...Ve};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=Rf(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Lf=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Df=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Lf.has(t.getName()))return!1;const s=t.getExpression();if(!$(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:If(i.getLiteralText())},_f=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),hn=new Set(["queues","scheduler","topics","workflows"]),Mf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!_f.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&hn.has(s.getName())&&Qr(s.getExpression()))return!0;s=s.getExpression()}const n=ts(s);return n?.length===1&&hn.has(n[0]??"")},zf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},Ci=new Set(["generateObject","generateText","streamObject","streamText"]),$f=e=>{const t=C(e.getExpression());return t!==void 0&&Ci.has(t)},Kf=e=>{const t=C(e.getExpression());if(t===void 0||!Ci.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!q(s,"maxOutputTokens")},Bf=new Set(["log","span","trace"]),Vf=new Set(["ai"]),Uf=new Set(["email","mail"]),Wf=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Pt=(e,t)=>[...t].some(s=>nt(e,s).length>0),Ti=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),qf=new Set(["every","filter","flatMap","forEach","map","some"]),jf=new Set(["all","allSettled","race"]),Oi=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(qf.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&jf.has(n))return t},Hf=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ti.has(t.getKind())){const s=Oi(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Gf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Ti.has(t.getKind())){if(t=Oi(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Yf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const x=m.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(m.getParent())}),p=u.getCatchClause();return f&&p!==void 0&&p.getDescendantsOfKind(d.ThrowStatement).length>0})},Qf=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Jf=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Xf=e=>{let t=!1,s=!0;for(const n of[...Wf].flatMap(i=>nt(e,i))){const i=Jf(n);i&&(t=!0,!Hf(i)&&!Qf(i)&&!Yf(i)&&!Gf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Zf=e=>E(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),vn="lunora-advisor-exempt",ep=/^[\s*/]+/u,tp=/[\w-]/u,sp=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
22
|
+
`);for(const n of s.split(`
|
|
23
|
+
`)){const i=n.replace(ep,"");if(!i.startsWith(vn))continue;const o=i.slice(vn.length);if(tp.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},np=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=q(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},ip=(e,t)=>{const s=np(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},rp=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of E(e,d.CallExpression))if(Df(l)&&(o=!0),Mf(l)&&(t=!0),zf(l)&&(i=!0),$f(l)&&(s=!0),Kf(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Xf(e);return{callsMail:Pt(e,Uf),emitsEvent:Pt(e,Bf),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Pt(e,Vf),throwsBareError:Zf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},op=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ie(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Ff(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=ip(e,s);return{...o?rp(o):{},...sp(e),...i,analyzableBody:o!==void 0,exportName:Y(e)??e.getName(),file:t,hasEmailArg:Tf(s,n.receiver),kind:n.kind,visibility:n.visibility}},ap=(e,t)=>{const s=[];for(const n of Z(e)){const i=op(n,t);i&&s.push(i)}return s},cp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ap(i,I(t,n)))}return s},lp=new Set(["dbRateLimit","rateLimit"]),dp=e=>r.isArrowFunction(e)?e.getBody():e,up=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},ki=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Ri=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},fp=(e,t)=>G(e)||t!==void 0&&Ri(e,t).some(s=>ki(s)),pp=(e,t)=>t===void 0?ge(e):Ri(e,t).some(s=>!ki(s)),gp=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!lp.has(s))return;const n=L(zn(e.getArguments()[2]),"key");if(!n)return;const i=dp(n),o=up(n);if(!(!fp(i,o)||pp(i,o)))return{callee:s,scope:S(e),file:t,limitName:Mn(e),line:e.getStartLineNumber()}},mp=(e,t)=>O(e,t,gp),hp=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),vp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!hp.has(t.getName()))return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&$(s.getExpression()))return s.getName()},Ep=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&$(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},xp=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Fi=(e,t=!1)=>{const s=xp(e);if(r.isIdentifier(s)){if(t)return;const n=X(s);return n===void 0?void 0:Fi(n,!0)}if(r.isCallExpression(s))return vp(s)??Ep(s)},Sp=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of E(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},Ap=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Xr(n.receiver,"output"),a=n.receiver!==void 0&&qn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Sp(i)){const f=Fi(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},yp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Ap(a,o))}return s},bp=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},Np=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=bp(L(a.options,"with"));c.length!==0&&i.push({exportName:Y(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Pp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Np(a,o))}return s},H=(e,t)=>`${e}:${t}`,En=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},wp=(e,t)=>[...ae(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?En(s,n,s.getName(),s.isExported()):void 0),...ae(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?En(i,n,s.getName(),i.isExported()):void 0})],Ip=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(H(c,a))},Cp=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Tp=(e,t)=>{const s=new Map(e.map(n=>[H(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(H(i.file,i.name))?.set(Cp(n),{fields:n.fields,method:n.method,table:n.table})}return s},Op=(e,t,s)=>E(e.node,d.CallExpression).map(n=>Ip(n,t,s)).filter(n=>n!==void 0),kp=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(H(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(H(o.file,o.name))?.push(a)}},Rp=(e,t,s)=>{const n=new Map(e.map(a=>[H(a.file,a.name),a])),i=new Map(e.map(a=>[`${ns(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[H(a.file,a.name),Op(a,n,t)]));return kp(s,n,i,o),o},Fp=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Lp=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(H(i.file,i.name))??[])Fp(t.get(H(i.file,i.name)),t.get(H(o.file,o.name)))&&(n=!0)}},Dp=(e,t,s,n)=>{const i=wp(e,t),o=Tp(i,s);return Lp(i,o,Rp(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(H(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ye=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ye(e.getLeft()),s=Ye(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},_p=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ye(t)!==void 0},Mp=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},zp=(e,t,s)=>So(e)?!Kr(s)&&Ao(Mp(t)):!0,$p=(e,t)=>{const s=[],n=[...E(e,d.BinaryExpression),...E(e,d.StringLiteral),...E(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(_p(o))continue;const a=Ye(o);if(a===void 0)continue;const c=Eo(a);if(c===void 0||!zp(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:xo(a)}))}return s},Kp=(e,t)=>{const s=[],n=new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Xe(i,"utf8"),{overwrite:!0});s.push(...$p(o,I(t,i)))}return s},Bp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=L(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&G(c);!l&&!u||i.push({exportName:Y(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Vp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Bp(a,o))}return s},Up=new Set(["query","unsafe"]),Wp=e=>!r.isPropertyAccessExpression(e)||!Up.has(e.getName())?!1:J(e.getExpression(),["sql"]),qp=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),jp=(e,t)=>{if(!Wp(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!qp(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Hp=(e,t)=>O(e,t,jp),Gp=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Yp=e=>{for(const[t,s]of Gp)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Qp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Yp(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Jp=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Xp=(e,t,s=[])=>{const n=rt(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Jp,requireUnmodifiedReach:!0});return es(n,s)},Zp=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),eg=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,tg=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=eg(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},sg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Zp.get(t);return s===void 0?void 0:Bn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},ng=(e,t)=>{const s=sg(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...tg(e.getArguments()[s.optionsIndex])}},ig=(e,t)=>O(e,t,ng),rg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Li=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:rg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>le(i)||s(i));if(!(n===void 0||le(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},cs=(e,t)=>N(e.getFirstAncestor(s=>N(s,t)||le(s)),t),og=(e,t)=>N(e,t)||e.getFirstAncestor(s=>N(s,t))!==void 0,Di=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return N(e,t)||cs(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Li(e);return s!==void 0&&!og(s,t)}return!1},_i=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],ag=e=>_i(e).some(t=>Di(t,e)),cg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},lg=e=>_i(e).some(t=>Di(t,e)||r.isBreakStatement(t)&&N(Li(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>cg(t)&&cs(t,e)),dg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>cs(t,e)),ug=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),fg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",wt=(e,t)=>{const s=ug(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||lg(e)||dg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(le)!==void 0))return{file:t,kind:fg(e),line:e.getStartLineNumber(),scope:i}},pg=(e,t)=>[...ae(e,t,d.WhileStatement,wt),...ae(e,t,d.ForStatement,wt),...ae(e,t,d.DoStatement,wt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),gg=new Set(["when","where"]),It=new Set(["definePolicy","defineShape"]),mg=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return It.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return It.has(i)?i:void 0}const s=t.getText();return It.has(s)?s:void 0},hg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Mi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(hg(e))return"empty-object";if(r.isParenthesizedExpression(e))return Mi(e.getExpression())}},ls=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),vg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ls(t)===e),zi=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>ls(t)===e),Eg=e=>{const t=vg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||zi(e).length>0},xg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>ls(t)===e),Wt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",Sg=(e,t)=>Wt(e)||Wt(t),Ag=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),xn=e=>!Wt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),yg=(e,t,s)=>{const n=Ag.get(e);if(n!==void 0)return Sg(t,s)?n==="positive"?"negative":"positive":xn(t)||xn(s)?void 0:n},we=e=>{if(r.isParenthesizedExpression(e))return we(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=yg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=we(e.getLeft()),i=we(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Sn=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},bg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Ng=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Pg=e=>{const t=[];for(const s of zi(e)){const n=we(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of xg(e)){const n=we(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Sn(s.getThenStatement()):Sn(s.getElseStatement())??bg(s);i!==void 0&&t.push(Ng(i))}return t},wg=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Ig=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!gg.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&Eg(a))for(const c of Pg(a)){const l=Mi(c);l!==void 0&&i.push({exportName:wg(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},Cg=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=mg(n);i!==void 0&&s.push(...Ig(n,i,t))}return s},Tg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Cg(i,I(t,n)))}return s},Og=new Set(["query","upsert","upsertMany","upsertNow"]),he=new Set,kg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Og.has(t))return J(e.getExpression(),["vectors"])?t:void 0},ds=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},$i=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Ki=e=>$i(e)?.getDeclarations()[0],Rg=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Bi=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},An=(e,t,s)=>{const n=$i(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Bi(Ki(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return us(o,t,s-1)}return G(e)},us=(e,t,s)=>{const n=ds(e);return ge(n)?!1:r.isIdentifier(n)?An(n,t,s):G(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>Rg(i)&&An(i,t,s))},Vi=e=>{const t=Bi(Ki(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ne=(e,t)=>{const s=ds(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ne(s.getWhenTrue(),t),...ne(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ne(s.getLeft(),t),...ne(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Vi(s);return n===void 0?[]:ne(n,!1)}return[]},Fg=(e,t)=>{const s=ne(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Qe(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Lg=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Dg=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Qe=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Fg(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Lg(n)&&(s=[Dg(n)]);return s},_g=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Mg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return he;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return he;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},qt=(e,t=!0,s=he)=>{const n=ds(e);if(r.isIdentifier(n)){const o=t?Vi(n):void 0;return o===void 0?[{node:n,parameters:s}]:qt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?qt(o.getExpression(),t,s):ne(o,!0).flatMap(a=>Qe(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=us(i.getExpression(),he,1)?Mg(o):he;return _g(o).flatMap(c=>ne(c,!0).flatMap(l=>Qe(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},zg=(e,t)=>{const s=kg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?qt(n):ne(n,!0).flatMap(o=>Qe(o,!0).map(a=>({node:a,parameters:he})))).some(({node:o,parameters:a})=>us(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},$g=(e,t)=>O(e,t,zg),Kg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:p,wranglerVariables:m,workflows:x}=s;return Lr({adminRoutes:fc(e,t),aiRawRuns:Ac(e,t),aiToolSideEffects:Rc(e,t),argumentDerivedFetches:Dc(e,t),argumentValidators:Zc(e,t),authApiCalls:so(e,t),authConfigs:ll(e,t),browserUrlAccesses:pl(e,t),callEdges:n.callEdges,configCalls:Al(e,t),containerKeyAccesses:bl(e,t),containerOverrides:Tl(e,t),containers:i,countReads:Ll(e,t,f.tables),crons:o,cronTargets:o.flatMap(_=>_.functionPath===void 0?[]:[_.functionPath]),exportSinks:zl(e,t),staleMigrationImports:Qp(e,t),failOpenGuards:Ul(e,t),flagReads:Gl(e,t),flagSecurityDefaults:Xl(e,t),geoIndexUsages:td(e,t),httpActionGuards:pd(e,t),httpHeaderWrites:bd(e,t),hyperdriveCalls:ro(e,t),identityClaimReads:Ld(e,t),imageDeliveryUrlAccesses:_d(e,t),inserts:n.inserts,kvKeyAccesses:zd(e,t,a),mailRecipientAccesses:Ud(e,t),maskProcedures:oo(e,t),maskStrategies:jd(e,t),mutatorWrites:Xd(e,t),nondeterministicCalls:fo(e,t),normalizeIdAuthorizations:pu(e,t),notifyCalls:go(e,t),notifyConfig:po(e,t),mutators:l,ownerFieldWrites:lf(e,t,a,l),unrestrictedWhereBranches:Tg(e,t),paymentWebhooks:gf(e,t),privilegedDispatches:Pf(e,t),procedureProtections:cp(e,t),queries:n.queries,queues:u,r2sqlCalls:mo(e,t),ratelimitKeySelectors:mp(e,t),rawRowReturns:yp(e,t),relationLoads:Pp(e,t),rlsProcedures:ho(e,t),schema:f,secretLiterals:Kp(e,t),modules:c,shapes:p,softDeleteReads:Vp(e,t),sqlInterpolations:Hp(e,t),storageKeyAccesses:Xp(e,t,a),storageUploads:ig(e,t),tableWrites:n.tableWrites,rowEffects:Dp(e,t,n.tableWrites,n.callEdges),unboundedLoops:pg(e,t),vectorNamespaceAccesses:$g(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:m})},Bg=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),Vg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>Bg(i))]},Ug=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Wg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",yn={error:"ERROR",info:"INFO",warn:"WARN"},bn={ERROR:2,INFO:0,WARN:1},qg=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),jg=(e,t)=>{const{advisor:s}=Jn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(yn,n)?yn[n]:void 0;return i===void 0?[...t,qg(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>Wg(o)||bn[o.level]>=bn[i])},Hg=(e,t)=>{const{advisor:s}=Jn(e),n=Vg(t,s?.accept??[]);return jg(e,s?.acceptUnreadable===!0?[...n,Ug()]:n)},Gg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Yg="crons",Qg=To.replace(/\.ts$/u,""),me=(e,t)=>`${ns(e)}:${t}`,Ct=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Jg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Gg[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...Ct("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Ct("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Ct("workflow",t.workflow,"workflow name")}))],Xg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Zg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Xg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},em=e=>Jg(e).flatMap(t=>Zg(t)),tm=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:Yg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],sm=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),be=(e,t)=>t===void 0?e:{...e,module:t},nm=e=>{const t=new Map,s=new Map,n=sm(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(me(c.file,c.exportName),l)};for(const c of e.functions){const l=me(c.filePath,c.exportName),u=[...vo(c.filePath),c.exportName].join(".");o(be({detail:c.kind,id:`function:${l}`,kind:"function",name:u},_e(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=me(c.filePath,c.exportName);o(be({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},_e(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(be({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(be({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},_e(e.modules,c.filePath)),me(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(be({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},_e(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},me(Qg,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},im=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,rm=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(me(e.file,e.exportName))??{reason:im(e.exportName)},om=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=rm(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},Tt=e=>`${e.from}|${e.kind}|${e.to}`,am=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,cm=e=>{const{nodes:t,sites:s}=nm(e),n=new Map,i=new Map;for(const o of[...tm(e),...em(e)]){const a=om(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(Tt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(am(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>Tt(o).localeCompare(Tt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},lm=e=>`${Xn}export const architecture = ${ko(e,"Record<string, unknown>")};
|
|
24
|
+
`,Nn=(e,t="api")=>{const s=new Map;for(const n of e){const i=ns(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new R("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},dm=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Zn(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>ei(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:Vo)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},um=(e,t,s={})=>{if(t===void 0)return;const n=dm(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
25
|
+
`);throw new R("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
26
|
+
${i}
|
|
27
|
+
|
|
28
|
+
Install them with your package manager, then re-run codegen.`)},fm={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},pm=new Set(["allowedHosts","deniedHosts","interceptHttps"]),gm=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},mm=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),hm=new Set(["durable"]),vm=new Set(["rollback"]),Ui=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Em="defineApp",Ie="app",Pn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Ie&&s.getInitializer()?.getText()===t)||t===Ie&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Ie),xm=e=>{if(e===void 0||!Xo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Ie;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Ie;if(r.isVariableDeclaration(t))return Pn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&Pn(e.getSourceFile(),s)},Sm="AppBuilder",Wi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},Am=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Sm&&s.getDeclarations().some(n=>Wi(n))},ym=e=>e.getText()===Em&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Wi(t)),qi=(e,t,s=new Set)=>{const n=tt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(ym(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return xm(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return qi(e,a.getInitializer(),s)}}return!1},ji=(e,t)=>{const s=Jt(t.getExpression());return s?.member==="deliveryAuthorization"&&(qi(e,s.object)||Am(s.object))},bm=new Map([["defineContainer",{keys:pm,signal:"containerEgressPolicy"}],["defineStep",{keys:vm,signal:"workflowRollback"}],["stream",{keys:hm,signal:"durableStreams"}]]),Nm=(e,t)=>{const s=bm.get(Ui(t));if(s!==void 0)return t.getArguments().some(n=>mm(gm(e,n),s.keys))?s.signal:void 0},Pm=(e,t)=>fm[Ui(t)]??(ji(e,t)?"deliveryAuthorization":void 0),wm=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Go(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=Nm(o,c)??Pm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>jn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Xe(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>ji(i,o))}return n},Im=(e,t)=>{const s=Yo();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Qo(i,s))return!0}return!1},Cm="createWorker",Tm="extend",wn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,In=e=>{const t=[],s=wn(L(e,"backupCron"));s!==void 0&&t.push(s);const n=L(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=wn(i.getNameNode());o!==void 0&&t.push(o)}return t},Om=e=>{const t=C(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Cm)return r.isObjectLiteralExpression(s)?In(s):[];if(t!==Tm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=_n(s.getBody());return n===void 0?[]:In(n)},km=(e,t)=>{const s=[];for(const{filePath:n}of et(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...Om(o))}return[...new Set(s)]},Hi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Hi(e.inner)},Rm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Hi(n);return i!==void 0&&t.has(i)}))},Fm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new R("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new R("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Lm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Cd(s,t),a=Ho(s,t),c=Oo(s,t),{queues:l,topics:u}=ea(s,t),f=sa(n),p=Wo(s,t);Fm(c,p);const m=qo(s,t),x=na(s,t),_=jo(s,t,c,p),K=km(s,t),P=wm(s,t,si(n)),V=ta(s,t),ee=Im(s,t),w=Jo(s,t);w.browser=w.browser||V.usesSandboxBrowser;const U=Me(n,e.target),Q=ia(w,U,{agents:p.length>0,commitOrderedTables:i.tables.some(b=>b.commitOrdered===!0),cronTriggers:_.length>0,crossShardFanout:i.tables.some(b=>fa(b)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(b=>b.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(b=>b.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(b=>b.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Rm(i),secretValues:ee,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(b=>b.schedules!==void 0)}),F=Q.usage,M=Uo(F),te=Q.signals.vectorStore!==!1,se=Q.signals.services===!1?[]:f,re=ti(n),oe=re??new Set,B=oe.has("lunorash");um(i,re,{hasVectors:te,scheduler:F.scheduler||_.length>0,storage:F.storage||x.rules.length>0||Object.keys(ni(i)).length>0,usage:F});const k=z(v(t,"flags.ts")),W=z(v(t,"notify.ts"));return{agents:p,capabilities:M,containers:m,crons:_,dataModelContent:ha(i),declaredDependencies:re,dependencies:oe,entryCronTriggers:K,env:a,featureUsage:F,hasFlags:k,hasNotify:W,identity:o,platformGate:{...Q,diagnostics:[...ra(n,e.target),...Q.diagnostics,...oa(U,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[aa(U)]:[],...P.socketRoutes&&P.deliveryAuthorization?[ca(U)]:[]]},queues:l,serverContent:ga({agents:p,capabilities:M,containers:m,env:a,hasVectors:te,hasFlags:k,hasNotify:W,identity:o,queues:l,schema:i,services:se,storageRuleBuckets:x.rules.map(b=>b.bucket),topics:u,useUmbrella:B,workflows:c}),services:se,storageRulesMetadata:x,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:B,workflows:c}},Gi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Dm=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},_m=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Mm=/^[\w$]+:[\w$]+$/u,zm=(e,t)=>{const s=Kn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Cn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},$m=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Cn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Qt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Cn(s):void 0}}},Km=(e,t,s)=>({schedule:{argKeys:$m(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Bm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if($n.has(s))return zm(s,n);if((s==="runAfter"||s==="runAt")&&Dm(t)){const l=Kn(i)??(r.isStringLiteral(i)&&Mm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Km(s,n,o)}}const a=_m.get(s),c=a===void 0?void 0:Gi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Vm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Yi=e=>Dr.isOptionalChain(e.compilerNode),Um=(e,t)=>r.isIfStatement(t)?!N(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?N(e,t.getStatement()):r.isForStatement(t)?N(e,t.getStatement())||N(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:le(t)?t.getFirstAncestor(le)!==void 0:r.isConditionalExpression(t)?!N(e,t.getCondition()):r.isBinaryExpression(t)?!N(e,t.getLeft())&&Vm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Yi(t)?!N(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&ag(s)),Wm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&N(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(le);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&N(o.getFirstAncestor(le),i))===!0},qm=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&N(e,t.getStatement())||r.isForStatement(t)&&(N(e,t.getStatement())||N(t.getIncrementor(),e)),jm=(e,t)=>{if(Yi(e)||t==="schedule"&&Wm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Um(s,i)){if(!qm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Tn=(e,t,s)=>{if(s===void 0)return;const n=jm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Hm=(e,t)=>[...O(e,t,(s,n)=>Tn(s,n,Bm(s))),...ae(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Gi(s,"services");return Tn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Gm=new Set(["boolean","number","object","string"]),Ym=e=>{const t=e.getName();if(!Gm.has(t))return;const s=e.getExpression();return J(s,["flags"])||J(s,["flags","details"])?t:void 0},Qm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Ym(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Jm=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Qm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Xm=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||va(o))return;const a=e.getSourceFile().getFilePath();if(Ea(i,e,a)){const c=xa(i,e,a,0,new Set);return c===void 0&&Sa(o),c}return o},Zm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Zr(t.getNameNode());return s===void 0||s==="namespace"}),eh=(e,t)=>{for(const{filePath:s}of et(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Zm(a)))return i}}},th="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",sh=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Ee(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${th}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},nh="room:",ih="__lunora_socket__:",rh=/^[A-Za-z]\w*$/u,On=e=>rh.test(e),oh=e=>`${e}:`.startsWith(nh)||`${e}:`.startsWith(ih),Qi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Ji=e=>Qi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),kn=e=>A(e),fs=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),ue=(e,t)=>{const s=Ee(e,`defineLiveStream ${t}`);return new R("LIVE_STREAM_NOT_LITERAL",s.message)},Xi=(e,t,s)=>{const n=fs(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ue(n??e,`needs ${s} so codegen can read its topics`);if(Ji(i))throw ue(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},ah=(e,t)=>{const s=kn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Ji(n))throw ue(n,`cannot spread into or compute the keys of topic "${s}"`);if(!On(s)||oh(s))throw new R("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(fs(n,"key")===void 0)return{fields:[],name:s};const a=Xi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>kn(l)),c=a.find(l=>!On(l));if(c!==void 0)throw new R("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},ch=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Qi(n))throw ue(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=fs(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ue(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Xi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>ah(a,l))}},lh=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new R("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},dh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},uh=(e,t)=>E(e,d.CallExpression).filter(s=>jn(s,"defineLiveStream")).map(s=>{const n=dh(s),i=r.isVariableDeclaration(n)?Zt(n,"binding"):void 0;if(i===void 0)throw new R("LIVE_STREAM_NOT_EXPORTED",Ee(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return ch(s,i,t)}),fh=(e,t)=>{const s=y(t).flatMap(n=>uh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return lh(s),s},ph=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,gh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?ph(e):!0,Zi=(e,t=!1)=>{for(const s of e.getProperties()){if(gh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Zi(n,!0))return!0}return!1},mh=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of ii(n))for(const o of ss(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Zi(a)))return!0}}return!1},hh=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=qe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=qe(a);c!==void 0&&s.push({column:c,strategy:Qn(a),table:i})}}return s},vh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of ii(i))for(const a of ss(o))for(const c of hh(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Eh=["providerSubscriptionId","state"],xh=["providerEventId","processedAt"],Rn=(e,t)=>t.every(s=>s in e.shape),Sh=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Rn(t,Eh)&&Rn(s,xh)},Ah=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],yh=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},bh=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},Nh="@lunora/privacy",er="userId",Fn=new Set(["user","users"]),Ph=e=>e.replaceAll("\\","/"),wh="privacy",Ih=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),ot=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Te=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",ps=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Ch=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},at=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Th=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Ch(s,"tables"),i=ot(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:ps(n).map(a=>Te(a)))t.datasets.set(o,i)},gs=8,ve=(e,t=0)=>{if(t>gs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return ve(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:ve(i,t+1)},Oh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:ve(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?ps(n):[],o=new Set(i.map(a=>Te(a)));for(const a of Ah)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?ot(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Te(a)==="user"&&t.userTables.add(c))}},Ln=(e,t,s)=>{t.datasets.set(ot(e.getArguments()[0])??s,s)},kh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Te(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},tr=(e,t=0)=>{const s=ve(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>gs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?tr(i.getExpression(),t+1):[kh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Rh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:tr(t)},Fh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:ve(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?ps(n):[])t.excluded.set(Te(i),r.isPropertyAssignment(i)?ot(i.getInitializer())??"":"")},Lh=(e,t)=>{switch(at(e)){case"actionCacheDataset":{Ln(e,t,"actionCache");break}case"authDataset":{Oh(e,t);break}case"defineDataset":{Th(e,t);break}case"documentHistoryDataset":{Ln(e,t,"documentHistory");break}}},ms=e=>e!==void 0&&r.isCallExpression(e)&&at(e)==="defineDataset",sr=e=>e!==void 0&&r.isCallExpression(e)&&Ih.has(at(e)??""),Dh=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(ms(i)||sr(i))?n:void 0},nr=(e,t,s=0)=>{const n=ve(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>gs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!nr(i.getExpression(),t,s+1))return!1}else if(!ms(i)&&!sr(i)){const o=r.isIdentifier(i)?Dh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},_h=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||nr(t,s)?s:void 0},Mh=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(Lh(i,t),at(i)==="definePrivacy"){const o=Rh(i);Fh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:_h(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>ms(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},zh=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),...z(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Ph(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},$h=(e,t,s)=>{if(s?.has(Nh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Fn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Fn)},i=[],o=[];for(const f of zh(e,t)){const p=Mh(f,n);i.push(...p.declared),o.push(...p.privacyCalls)}const a=new Set;for(const f of o){for(const p of f.passed??[])a.add(p);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:yh(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},ir=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&ir(n,t)),Kh=(e,t)=>e.extensionKey!==wh&&(er in e.shape||Object.values(e.shape).some(s=>ir(s,t))),Bh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${er}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Vh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Kh(o,t.userTables)).map(o=>o.name),[n]=bh(s,t.classifications);if(n!==void 0)throw new R("PRIVACY_COVERAGE",Bh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new R("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Uh=(e,t)=>{const s=la(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Wh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Dn=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),qh="",jh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Hh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Qt.Const?t.getInitializer():void 0},Ue=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ue(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Hh(e);if(n!==void 0)return Ue(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},Gh=(e,t)=>{if(Wh.has(e))return{method:e,tables:Ue(t)??[qh]}},Ot=(e,t,s)=>e===void 0?void 0:{...e,fields:jh(t,e.method,s)},Yh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Qt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Qh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Yh(n);if(i!==void 0)return Dn.has(s)?Ot({method:s,tables:[i]},e,1):void 0;if($(n))return Ot(Gh(s,e.getArguments()[0]),e,2);if(Dn.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Ot({method:s,tables:[n.getName()]},e,1)},Jh=(e,t)=>O(e,t,(s,n)=>{const i=Qh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Xh=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Zh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||q(s,"args")===void 0)return!1}return rs(e,t).opaque},ev=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ie(a);c!==void 0&&Zh(a,c.receiver)&&s.push(Xh(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},tv=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...ev(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},sv=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Je=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),rr=e=>!e.isAny(),or=e=>{const t=e.getType();if(!rr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:sv.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},nv=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},ar={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},iv=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),rv={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},ov=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),av={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},cv=(e,t,s)=>{if(!t.some(i=>jr(i)))return rv;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return ov.has(s.typeName)&&!n&&!t.some(i=>Ta(i))?av:ar},cr=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:iv(u),p=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${p}`:p,title:"Procedure exists at runtime but is missing from the generated API"}},lv=(e,t,s)=>{const n=[];for(const i of Z(e)){const o=r.isIdentifier(i.getNameNode())?Rt(i):[i.getName()],c=o.some(u=>Je(s,t,u))||!nv(i)?void 0:or(i),[l=i.getName()]=o;c!==void 0&&n.push(cr(t,l,c,i.getStartLineNumber(),cv(i,o,c)))}return n},dv=(e,t,s)=>{if(Je(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=or(i.getExpression());o!==void 0&&n.push(cr(t,"default",o,i.getStartLineNumber(),ar))}return n},uv=(e,t,s)=>[...lv(e,t,s),...dv(e,t,s)],fv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Rt(n).some(i=>Je(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Rt(n).find(o=>Je(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),pv=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),gv=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...uv(c,l,s)),i.push(...fv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!rr(a.getType()))&&n.push(pv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},mv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},hv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},vv=(e,t)=>O(e,t,(s,n)=>mv(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:hv(s)}:void 0),lr=e=>e==="@lunora/workflow",Ev=e=>new Set(e.getImportDeclarations().filter(t=>lr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),xv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),Sv=(e,t)=>{const s=Wn(e,"defineWorkflowEvent",lr),n=Ev(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!xv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?Zt(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new R("WORKFLOW_EVENT_NOT_LITERAL",Ee(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:I(t,e.getFilePath()),type:l.getLiteralValue()})}return i},Av=(e,t)=>{const s=y(t).flatMap(i=>Sv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new R("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},yv=e=>{const t=zo(e,"compatibility_date"),s=$o(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:Ko(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
|
|
29
|
+
`},bv=e=>`// Generated by @lunora/codegen. Do not edit.
|
|
30
|
+
// Serves the advisor procedure list to the app's Worker, which forwards it to a hosted Studio after the admin check.
|
|
31
|
+
const PROCEDURES = ${JSON.stringify(e)};
|
|
32
|
+
|
|
33
|
+
const ADVISOR_PROCEDURES_PATH = "/__lunora/advisor-procedures";
|
|
34
|
+
|
|
35
|
+
export default {
|
|
36
|
+
fetch(request: Request): Response {
|
|
37
|
+
if (new URL(request.url).pathname !== ADVISOR_PROCEDURES_PATH) {
|
|
38
|
+
return Response.json({ error: "not found" }, { status: 404 });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (request.method !== "GET") {
|
|
42
|
+
return Response.json({ error: "GET only" }, { status: 405 });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return new Response(PROCEDURES, { headers: { "Content-Type": "application/json" }, status: 200 });
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
`,Nv=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":bv(t),"wrangler.jsonc":yv(e)}:{},Pv=(e,t)=>{for(const s of new Set([Zo(t),si(e)])){const n=s===void 0?[]:yo(s);if(s!==void 0&&n.length>0)throw new R("PROJECT_CONFIG_INVALID",`${kr(s)} is invalid:
|
|
49
|
+
${n.map(i=>` - ${i}`).join(`
|
|
50
|
+
`)}`)}},wv=(e,t,s)=>{for(const n of s)t[n]===void 0&&fe(v(e,n),{force:!0});for(const n of[...new Set(s.map(i=>Ze(v(e,i))))].toSorted((i,o)=>o.length-i.length))z(n)&&Ht(n).length===0&&fe(n,{recursive:!0})},Iv=(e,t)=>{for(const s of Ht(e,{recursive:!0,withFileTypes:!0})){const n=v(s.parentPath,s.name);s.isFile()&&t[Gt(e,n)]===void 0&&fe(n)}},Oe=(e,t)=>{z(e)&&Xe(e,"utf8")===t||Or(e,t,"utf8")},Cv=(e,t)=>{if(t===""){fe(e,{force:!0});return}Oe(e,t)},Tv=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){fe(s,{force:!0,recursive:!0});return}if(z(s))for(const n of Ht(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Gt(e,i)]===void 0&&fe(i)}for(const[n,i]of Object.entries(t))jt(Ze(v(e,n)),{recursive:!0}),Oe(v(e,n),i)},Ov=(e,t,s,n)=>{const i=v(e,t);if(n!==void 0)wv(i,s,n);else if(Object.keys(s).length===0){fe(i,{force:!0,recursive:!0});return}else z(i)&&Iv(i,s);for(const[o,a]of Object.entries(s)){const c=v(i,o);jt(Ze(c),{recursive:!0}),Oe(c,a)}},kv=e=>{try{const t=Ra(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},We=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Rv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Fv=(e,t)=>{z(e)||jt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Oe(v(e,n.name),n.content),s.push(n.name);break}case"directory":{Ov(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{Tv(e,n.files),s.push(...Object.keys(n.files));break}default:Cv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},Lv=e=>{const t=kv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Da({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Ma({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
|
|
51
|
+
`,openApiModuleContent:_a(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
|
|
52
|
+
`,openRpcModuleContent:za(i)}},Dv=".lunora-schema.json",_v=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Mv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new R("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new R("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new R("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},zv=8,$v=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:p,useUmbrella:m,workflows:x}=e,_=()=>ya(()=>{const w=io(l,a,{lazyFunctions:o}),U=uo(l,a);return{functions:w,httpRoutes:ba(l,a),mutators:U}});let{erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=_();no(y(a).map(w=>l.getSourceFileOrThrow(w)),w=>Gt(a,w.getFilePath())),Nn([...P,...ee].map(w=>w.filePath)),Nn(V.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const U=u?P:P.filter(B=>B.channel?.kind!=="room"&&B.lifecycle!=="socket"),Q=ja({agents:t,functions:U,httpRoutes:V,mutators:ee,useUmbrella:m,workflows:x}),F={agents:t,functions:U,lazyFunctions:o,migrations:c,mutators:ee,shapes:f,useUmbrella:m,usesSandbox:p},M=sc(F),te=nc(F),se=Ha({functions:P,useUmbrella:m}),re=v(a,"_generated",ri),oe=[[s,Q],[i,se],[n,M],...Object.entries(te).map(([B,k])=>[v(re,B),k])];if(w>=zv||oe.every(([B,k])=>Rv(l,B,k)))return{apiContent:Q,erased:K,functions:P,functionModulesContent:te,functionsContent:M,httpRoutes:V,internalContent:se,mutators:ee};for(const[B,k]of oe)We(l,B,k);({erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=_())}},Kv=e=>{const t=_v(),s=t?St.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora");Pv(e.projectRoot,n);const i=bo(n),o=e.lazyFunctions===!0||i,a=No(n),c=v(n,"schema.ts");if(!z(c))throw new R("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??Mo(n);to(Xm);const u=Ia(l,c,e.projectRoot);Vh(u.tables,$h(l,n,ti(e.projectRoot)));const{agents:f,capabilities:p,containers:m,crons:x,dataModelContent:_,dependencies:K,entryCronTriggers:P,env:V,featureUsage:ee,hasFlags:w,hasNotify:U,identity:Q,platformGate:F,queues:M,serverContent:te,services:se,storageRulesMetadata:re,topics:oe,usesSandbox:B,useUmbrella:k,workflows:W}=Lm({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});sh(u,u.jurisdiction===void 0?void 0:eh(l,n));const b=v(n,"_generated"),dr=v(b,"dataModel.ts"),ur=v(b,"server.ts"),fr=v(b,"api.ts"),pr=v(b,"internal.ts"),gr=v(b,"functions.ts");We(l,dr,_),We(l,ur,te);const hs=Object.fromEntries(se.filter(g=>g.rpcEntrypoint!==void 0).flatMap(g=>Object.entries(ma(g,b))));for(const[g,xt]of Object.entries(hs))We(l,v(b,g),xt);const ke=Pa(l,n),de=Ca(l,n),ct=F.signals.typedWebSockets!==!1,{apiContent:vs,erased:mr,functions:j,functionModulesContent:Es,functionsContent:xs,httpRoutes:lt,internalContent:Ss,mutators:dt}=$v({agents:f,apiPath:fr,generatedFunctionsPath:gr,internalPath:pr,lazyFunctions:o,roomsSupported:ct,lunoraDirectory:n,migrations:ke,project:l,shapes:de,useUmbrella:k,usesSandbox:B,workflows:W}),As=Io(l,n),ut=Co(As,u,[...j,...lt].map(g=>g.filePath)),Re=As.length>0,xe=e.lint===!1&&!Re?void 0:{callEdges:Hm(l,n),inserts:Na(l,n),queries:Vs(l,n,j),tableWrites:Jh(l,n),workflowCalls:vv(l,n)},hr=Fa(xe?.queries??Vs(l,n,j)),Se=e.lint===!1||xe===void 0?void 0:Kg(l,n,{callSites:xe,containers:m,crons:x,functions:j,modules:ut,mutators:dt,queues:M,schema:u,shapes:de,workflows:W,wranglerVariables:e.wranglerVariables}),ys=Se===void 0?[]:Hg(e.projectRoot,[...Rr(Se,{source:"static"}),...gv(l,n,{byName:new Set([...W,...M,...f,...m].map(g=>g.exportName)),byPath:new Set([...j,...dt,...de,...ke].map(g=>`${g.filePath}:${g.exportName}`))}),...tv(l,n),...Aa(mr,n),...$a(M,e.wranglerQueueProducers)]),vr=wa(l,n),bs=vh(l,n);Mv(de,bs,mh(l,n));const Er=w?Jm(l,n):[],ft=F.signals.vectorStore!==!1,xr=da(Me(e.projectRoot,e.target),"deliveryAuthorization"),Ae=Uh(ee,{containerCount:m.length,cronCount:x.length,dependencies:K,hasPaymentTables:Sh(u.tables),queueCount:M.length,storageColumnCount:Object.keys(ni(u)).length,storageRuleCount:re.rules.length,vectorIndexCount:u.vectorIndexes.length,target:Me(e.projectRoot,e.target),vectorStoreSupported:ft,workflowCount:W.length}),Ns=t?St.now():0,pt=La(u,ke.map(g=>g.id)),gt=fh(l,n),Ps=pa({advisories:ys.filter(g=>g.name!=="procedure_type_check_unavailable"),agents:f,capabilities:p,containers:m,env:V,flagKeys:Er,hasFlags:w,hasNotify:U,hasIpReaders:j.some(g=>g.readsIp===!0)||de.some(g=>g.readsIp===!0),hasRooms:ct&&j.some(g=>g.channel?.kind==="room"),hasSensitiveArgs:f.length>0||j.some(g=>_o(g)),hasSecretValues:F.signals.secretValues===!0,hasSockets:ct&&j.some(g=>g.lifecycle==="socket"),lazyFunctions:o,hasVectors:ft,liveStreamDeclarations:gt,liveStreams:F.signals.liveStreams===!0,maskMetadata:bs,mutators:dt,queues:M,rlsMetadata:vr,schema:u,schemaSnapshot:pt,shapes:de,services:se,storageRules:re,studioFeatures:Ae,topics:oe,useUmbrella:k,workflowEvents:Av(l,n),workflows:W}),ws=Wa(de,K.has("@lunora/db"),k),Is=Ka(m,u.jurisdiction),Cs=Ba(W,{lazy:o}),Ts=Va(f,{lazy:o}),Os=Ua(M,e.wranglerQueueProducers),ks=ic(gt,k),Rs=Ga(x),Sr=Ya(Ae.scheduler),Fe=ua(Me(e.projectRoot,e.target)),Ar=Fe.supported?Qa(k):"",yr=Ja(u.tables,k,u.jurisdiction),br=Po(e.projectRoot)?Xa(k):"",Fs=Za(u.vectorIndexes),Le=tc(u,k),Ls=qa(K.has("@lunora/seed")),De=e.apiSpec??"openapi",mt=De==="openapi"||De==="both",Nr=Se?.procedureProtections??[],Pr=Se===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...Nr]},ht=`${JSON.stringify(Pr,void 0,2)}
|
|
53
|
+
`,vt=De==="openrpc"||De==="both",Ds=Oa(K.has("@lunora/auth")),_s=ka({agentWorkflows:f.map(g=>g.className),capabilities:p,emailAgents:f.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:K.has("@lunora/cloudflare-access"),hasAuth:K.has("@lunora/auth"),hasFramework:K.has("@lunora/astro")||K.has("@lunora/svelte")||K.has("@lunora/vue")||z(v(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(g=>Zn(g)),hasHyperdriveGlobal:u.tables.some(g=>ei(g)),hasKvIntrospector:Ae.kv,hasNotify:U,hasQueue:M.some(g=>g.mode==="push"),liveStreams:F.signals.liveStreams===!0,liveStreamsWithheld:F.liveStreamsWithheld,liveStreamDeclarations:gt,hasAdminRevocations:Fe.supported,hasScheduler:Ae.scheduler,hasSourcedTables:u.tables.some(g=>g.externalSource!==void 0),hasStorage:Ae.storage,hasDeliveryAuthorization:xr,hasVectors:ft,hasWorkflow:W.length>0,identity:Q,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(g=>({name:g.name,shardMode:g.shardMode})),securityHeaders:wo(n),spaAssetsBindings:e.spaAssetsBindings,useUmbrella:k,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:Re,wantsOpenApi:mt,wantsOpenRpc:vt}),{openApiContent:Ms,openApiModuleContent:zs,openRpcContent:$s,openRpcModuleContent:Ks}=Lv({functions:j,httpRoutes:lt,modules:ut,projectRoot:e.projectRoot,wantsArchitecture:Re}),ye=Re&&xe!==void 0?cm({...xe,crons:x,functions:j,httpRoutes:lt,modules:ut,queues:M,schema:u,services:se,topics:oe,workflows:W}):void 0,Et=v(n,Dv),wr=z(Et),Ir=e.dryRun?[]:Fv(b,[{content:_s,kind:"always",name:"app.ts"},{content:_,kind:"always",name:"dataModel.ts"},{content:vs,kind:"always",name:"api.ts"},{content:Ss,kind:"always",name:"internal.ts"},{content:te,kind:"always",name:"server.ts"},{content:xs,kind:"always",name:"functions.ts"},{files:Es,kind:"directory",name:ri},{content:Ps,kind:"always",name:"shard.ts"},{content:Rs,kind:"always",name:"crons.ts"},{content:Fs,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:Is,kind:"optional",name:"containers.ts"},{content:Cs,kind:"optional",name:"workflows.ts"},{content:Ts,kind:"optional",name:"agents.ts"},{content:Os,kind:"optional",name:"queues.ts"},{content:ks,kind:"optional",name:"live.ts"},{content:Sr,kind:"optional",name:"scheduler.ts"},{content:yr,kind:"optional",name:"shardRegistry.ts"},{content:Ar,kind:"optional",name:"adminRevocations.ts"},{content:br,kind:"optional",name:"durableObjects.ts"},{content:Ls,kind:"optional",name:"seed.ts"},{content:Ds,kind:"optional",name:"authModule.ts"},{content:ws,kind:"optional",name:"collections.ts"},{files:hs,kind:"services"},{files:Nv(e.projectRoot,ht,a),kind:"directory",name:"companion",owned:Bo},{content:mt?Ms:"",kind:"optional",name:"openapi.json"},{content:mt?zs:"",kind:"optional",name:"openapi.ts"},{content:vt?$s:"",kind:"optional",name:"openrpc.json"},{content:vt?Ks:"",kind:"optional",name:"openrpc.ts"},{content:ht,kind:"optional",name:"advisor-procedures.json"},{content:ye===void 0?"":`${JSON.stringify(ye,void 0,2)}
|
|
54
|
+
`,kind:"optional",name:"architecture.json"},{content:ye===void 0?"":lm(ye),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!wr&&Oe(Et,Fr(pt)),t){const g=St.now(),xt=Math.round(g-s),Cr=Math.round(Ns-s),Tr=Math.round(g-Ns);console.error(`@lunora/codegen: codegen took ${xt.toString()}ms (discovery ${Cr.toString()}ms, emit ${Tr.toString()}ms)`)}return{advisories:ys,advisorContext:Se,agents:f,architecture:ye,containers:m,cronTriggers:[...new Set([...ec(x),...P])],generated:{advisorProceduresJson:ht,agents:Ts,api:vs,app:_s,authModule:Ds,collections:ws,containers:Is,crons:Rs,dataModel:_,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:Es,functions:xs,internal:Ss,live:ks,openApi:Ms,openApiModule:zs,openRpc:$s,openRpcModule:Ks,queues:Os,seed:Ls,server:te,shard:Ps,vectors:Fs,workflows:Cs},migrations:ke,outputDirectory:b,platformDiagnostics:Fe.diagnostic===void 0?F.diagnostics:[...F.diagnostics,Fe.diagnostic],queues:M,indexReferences:hr,schemaSnapshot:pt,schemaSnapshotPath:Et,schemaTables:u.tables,workflows:W,writtenFiles:Ir}},ox=e=>Br(()=>Kv(e));export{Dv as SCHEMA_SNAPSHOT_FILENAME,Mo as createCodegenProject,lx as findTsconfig,dx as refreshCodegenProject,ox as runCodegen,ux as tsconfigFingerprint};
|
package/package.json
CHANGED
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import{existsSync as _,readFileSync as Xe,mkdirSync as Gt,writeFileSync as Or,rmSync as pe,readdirSync as Yt}from"node:fs";import{dirname as Ze,join as v,basename as kr,relative as Qt}from"node:path";import{performance as yt}from"node:perf_hooks";import{runAdvisor as Rr}from"@lunora/advisor";import{LunoraError as R}from"@lunora/errors";import{serializeSchemaSnapshot as Fr}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Lr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Jt,ts as Dr,VariableDeclarationKind as Xt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as I,descendantsOfKind as E,bindingKeyName as ge,collectCallRows as O,findObjectProperty as q,collectSecurityCallRows as _r,propertyInitializer as L,listSecurityScanFiles as et,objectLiteralFromCallbackBody as Mn,limitNameOf as zn,optionsObjectLiteral as $n,handlerOf as Mr,collectNodeRows as ae,chainRootOf as tt,outermostValueWrapper as T,isWriteTarget as st,isSameNode as N,unwrapExpression as h,isConstDeclaration as ce,memberAccessOf as Zt,returningFunctionOf as Ft,walkChain as zr,RUN_METHODS as Kn,functionReferenceSegments as $r,isTestPath as Kr,isFunctionLike as le,functionKeyOf as Bn,withSourceListMemo as Br}from"./isTestPath-DRIdZaij.mjs";import{j as Z,h as Y,d as D,b as es,c as S,a as nt,w as ts,k as Vr,l as Ur,f as Wr,m as qr,g as Lt,i as jr}from"./attribution-BhGR_h0Z.mjs";import{b as Vs,r as bt,a as J,e as Hr,m as Vn,c as it,f as ss,E as Un,C as Wn,d as Gr,g as Yr,i as Qr}from"./context-root-DnvrQxae.mjs";import{a as C,i as qn,c as ie,d as jn,e as Jr,f as Xr,g as Hn}from"./classify-procedure-call-BZ164dkJ.mjs";import{a as A,s as Zr}from"./property-name-7cBlgK_O.mjs";import{b as eo,a as rt}from"./module-specifiers-BctA0m_p.mjs";import{r as ot,s as to}from"./parse-validator-BisfC8bR.mjs";import so from"./discoverAuthApiCalls-ENLGem4M.mjs";import{i as $,r as Gn}from"./database-calls-BRI5W-Mp.mjs";import{i as Dt,p as Yn,w as no,d as io}from"./index-jtzAVdUp.mjs";import ro from"./discoverHyperdriveCalls-BaRayTZe.mjs";import{diagnosticAt as de}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ns,a as qe,s as Qn,d as oo}from"./index-mFEIaT45.mjs";import{MUTATORS_FILENAME as ao,isDefineMutatorCallee as co,mutatorServerImplOf as lo,discoverMutators as uo}from"./MUTATORS_FILENAME-C3OImAxC.mjs";import fo from"./discoverNondeterministicCalls-BoF6ob-B.mjs";import{discoverNotifyConfig as po,discoverNotifyCalls as go}from"./ALL_NOTIFY_CHANNELS-CtrsBtZX.mjs";import mo from"./discoverR2sqlCalls-CZjqFVi_.mjs";import ho from"./discoverRlsProcedures-mjiA0I4S.mjs";import{s as is,n as vo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Eo,redact as xo,isHeuristicSecretKind as So,isSecretishName as Ao}from"./redact-Cy14LEnc.mjs";import{r as Jn,p as yo,c as bo,a as No,e as Po,d as wo}from"./project-config-file-DR7xrrNB.mjs";import{a as _e,d as Io,r as Co}from"./modules-Qpm_zqz4.mjs";import{WORKFLOWS_FILENAME as To,discoverWorkflows as Oo}from"./WORKFLOWS_FILENAME-DfVfBum_.mjs";import{r as ko}from"./json-data-Chfs2Cz5.mjs";import{a as Ro,I as Fo,g as Lo,G as Xn,d as Do,i as _o}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as Mo}from"./createCodegenProject-Cfr1xHPC.mjs";import{findTsconfig as px,refreshCodegenProject as gx,tsconfigFingerprint as mx}from"./createCodegenProject-Cfr1xHPC.mjs";import{wranglerString as zo,wranglerValue as $o,companionName as Ko,COMPANION_FILES as Bo}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as Vo,usedCapabilities as Uo}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Zn,isHyperdriveGlobalTable as ei}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Wo}from"./AGENTS_FILENAME-D0Y0_UgB.mjs";import{discoverContainers as qo}from"./CONTAINERS_FILENAME-J-e3Vanb.mjs";import jo from"./discoverCrons-DWVXmktw.mjs";import{contextPropertiesRead as Ho,createTargetScope as Go,fileWiresRequestSecretTool as Yo,discoverFeatureUsage as Qo}from"./capabilitiesUsedBy-BwhaHK08.mjs";import ti from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Jo,findProjectConfigFile as si,findCodegenConfigFile as Xo}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Zo}from"./QUEUES_FILENAME-Ba-sK5Ek.mjs";import{discoverSandboxUsage as ea}from"./discoverSandboxUsage-Ccy9n7G1.mjs";import{resolveServiceBindings as ta}from"./companionServiceBinding-BZjm486n.mjs";import sa from"./discoverStorageRulesMetadata-CtE5trUR.mjs";import{resolveCodegenTarget as Me,gatePlatformFeatures as na,readTargetDiagnostics as ia,vectorizeDimensionDiagnostics as ra,liveStreamsDeliveryAuthorizationDiagnostic as oa,socketRoutesDeliveryAuthorizationDiagnostic as aa,studioPlatformFor as ca,platformFeatureAvailable as la,gateAdminTokenRevocation as da}from"./DEFAULT_TARGET-CVYzxQ0y.mjs";import{i as ua}from"./schema-BgM8A3XV.mjs";import{b as ni,e as fa}from"./shard-Csztu3jG.mjs";import{e as pa,a as ga}from"./server-CRFaUMKQ.mjs";import{emitDataModel as ma}from"./emitDataModel-BvCZS4Yq.mjs";import{i as ha,b as va,e as Ea,d as xa,f as Sa,c as Aa}from"./unwrap-handler-return-DUzluwPj.mjs";import ya from"./discoverHttpRoutes-CAoEemno.mjs";import ba from"./discoverInserts-DmSa4WKU.mjs";import{e as ii}from"./exported-procedure-chains-h8Y7xDjq.mjs";import Na from"./discoverMigrations-Duh6HVG3.mjs";import Us from"./discoverQueries-spxu-wHR.mjs";import Pa from"./discoverRlsMetadata-Cc0zA-gZ.mjs";import wa from"./discoverSchema-ynieYB0n.mjs";import{discoverShapes as Ia}from"./SHAPES_FILENAME-CH0KrAdb.mjs";import{i as Ca}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as Ta,emitApp as Oa}from"./emitApp-C3IUdkkt.mjs";import{readJsonSync as ka}from"@visulima/fs";import{indexReferencesOf as Ra,buildSchemaSnapshot as Fa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as La,emitOpenApiModule as Da}from"./buildOpenApiDocument-B8KEeeRr.mjs";import{buildOpenRpcDocument as _a,emitOpenRpcModule as Ma}from"./OPENRPC_VERSION-UNYmA7Ty.mjs";import{w as za,u as $a,v as Ka,t as Ba,x as Va}from"./shard-runtime-D0xuE0pX.mjs";import{emitCollections as Ua,emitSeed as Wa,emitApi as qa,emitInternalApi as ja}from"./emitApi-lwadq5G7.mjs";import{emitCrons as Ha,emitScheduler as Ga,emitAdminRevocations as Ya,emitShardRegistry as Qa,emitDurableObjects as Ja,emitVectors as Xa,emitWranglerCronTriggers as Za}from"./emitCrons-CCRKs482.mjs";import ec from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as ri,emitFunctions as tc,emitLazyFunctionModules as sc}from"./emitFunctions-ppMX7E3X.mjs";const nc=(e,t=!1)=>{if(e.length===0)return"";const s=Do(t),n=e.map(c=>{if(Ro(c.exportName,"live stream export name"),!Fo.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{Lo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${p} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(M=>`\${encodeURIComponent(key.${M})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${p} => ({
|
|
2
|
-
__lunoraLive: ${m},
|
|
3
|
-
topic: \`${u.name}:${x}\`,
|
|
4
|
-
}),`});return` ${c.exportName}: {
|
|
5
|
-
${l.join(`
|
|
6
|
-
`)}
|
|
7
|
-
},`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${Xn}import type { ${a} } from "${s.server}";
|
|
8
|
-
|
|
9
|
-
${n.join(`
|
|
10
|
-
`)}
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* A typed reference to each declared live topic, grouped by the stream's export name:
|
|
14
|
-
* \`live.posts.post({ postId })\`. Pass one to \`ctx.live.publish(ref, payload)\` on the server, or to a
|
|
15
|
-
* live-topic hook in the browser. A reference is plain data and carries no server code.
|
|
16
|
-
*/
|
|
17
|
-
export const live = {
|
|
18
|
-
${i.join(`
|
|
19
|
-
`)}
|
|
20
|
-
};
|
|
21
|
-
`},oi=new Set(["delete","get","head","options","patch","post","put"]),ic=new Set(["handler","stream"]),rc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ws=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),oc=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!oi.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},ac=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||oi.has(n.getName()))break;s=n.getExpression()}return oc(s)},cc=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Ws.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Ws.has(s.getText()))return!0}return!1},lc=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!ic.has(n.getName()))return;const i=ac(s);if(!i||!rc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&cc(o);return{exportName:Y(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},dc=(e,t)=>{const s=[];for(const n of Z(e)){const i=lc(n,t);i&&s.push(i)}return s},uc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...dc(i,I(t,n)))}return s},fc=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},pc=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?ge(t):void 0}},gc=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Vs(a)}))return!1;const n=D(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Vs(i)},qs=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=fc(e);return n!==void 0&&pc(n)===t?!0:t==="args"&&gc(e)},ai=(e,t)=>r.isIdentifier(e)?qs(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>qs(s,t)),mc=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},js=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!es(t)?t.getInitializer():void 0},_t=e=>ai(e,"args"),X=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of E(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},G=e=>{if(_t(e))return!0;const t=X(e);return t!==void 0&&_t(t)},hc=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=X(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},me=e=>{if(bt(e))return!0;const t=js(e);if(t!==void 0&&bt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=js(i);return o!==void 0&&bt(o)})},ze=(e,t)=>ai(e,t),vc=(e,t)=>{if(ze(e,t))return!0;const s=X(e);if(s!==void 0&&ze(s,t))return!0;const n=mc(e);if(n!==void 0){const i=X(n);return i!==void 0&&ze(i,t)}return!1},Ec=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:J(e.getExpression(),["ai"]),xc=(e,t)=>{if(!Ec(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)||me(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Sc=(e,t)=>O(e,t,xc),Ac=new Set(["generateText","streamText"]),yc=new Set(["messages","prompt","system"]),bc=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Nc=(e,t)=>bc.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),Pc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Hr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Nc(i,s));return n===void 0?void 0:`${n}.${s}`},wc=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=Pc(t);if(s!==void 0)return s}},Ic=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=ge(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Cc=e=>{if(_t(e))return!0;const t=Ic(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},Tc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!yc.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&Cc(s))return!0}return!1},Oc=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=C(n.getExpression());if(i===void 0||!Ac.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(C(c.getExpression())==="tool"&&(a=wc(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Tc(o)})}return s},kc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Oc(i,I(t,n)))}return s},Rc=e=>J(e,["fetch"]),Fc=(e,t)=>{if(!Rc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Lc=(e,t)=>O(e,t,Fc),rs=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=ot(s.getExpression());return n===void 0||rs(n,t)})}finally{t.delete(e)}},Dc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=q(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ot(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:rs(i)}},_c=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?ot(o):void 0;a===void 0?s=!0:(t.push(a),s||=rs(a))}n=i.getExpression()}return{objects:t,opaque:s}},os=(e,t)=>t?_c(t):Dc(e),ci=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=ot(s.getExpression());return n===void 0?[]:ci(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},Mc=e=>e.flatMap(t=>ci(t,new Set)),zc=new Set(["check","length","max"]),Mt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(zc.has(s.getName()))return!0;t=n}},zt=e=>eo(e)||e==="@lunora/values",$c=e=>{const t=new Set(["v"]);for(const s of qn(e,"v",zt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&zt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Kc=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},Bc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Vc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&zt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),as=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return Bc(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Vc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Uc=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},Wc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},qc=e=>r.isReturnStatement(e)?e.getExpression():void 0,jc=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Wc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=qc(t);return s?[s]:[]}),li=(e,t)=>{if(as(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return li(e.getExpression(),t)},Hc=(e,t)=>{const s=Uc(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Mt(e),i=new Set(jc(s).map(o=>li(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=as(o,t);return a===void 0?[]:[{bounded:Mt(o)||n&&i.has(o),factory:a}]})},Gc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=as(s,t),i=n===void 0?[]:[{bounded:Mt(s),factory:n}];return r.isCallExpression(s)?[...i,...Hc(s,t)]:i}),Yc=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Gc(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Qc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ie(n);if(i?.visibility!=="public")return;const{objects:o}=os(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Yc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Y(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Jc=(e,t)=>{const s=[],n=$c(e),i={destructured:Kc(e,n),namespaces:n};for(const o of Z(e)){const a=Qc(o,t,i);a&&s.push(a)}return s},Xc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Jc(i,I(t,n)))}return s},Nt=e=>e?.getKind()===d.TrueKeyword,Zc=e=>e?.getKind()===d.FalseKeyword,el=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,tl=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),sl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&C(t.getExpression())==="scim"),nl=e=>e!==void 0&&r.isCallExpression(e)&&tl.has(C(e.getExpression())??""),il=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),rl=e=>{const t=L(e,"advanced"),s=L(e,"emailAndPassword"),n=L(e,"session");return{analyzable:!0,disableCsrfCheck:Nt(L(t,"disableCSRFCheck")),emailPasswordEnabled:Nt(L(s,"enabled")),requireEmailVerification:Nt(L(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:sl(L(e,"plugins"))&&nl(L(e,"database")),secureCookiesDisabled:Zc(L(t,"useSecureCookies")),sessionFreshAgeZero:el(L(n,"freshAge")),trustedOriginsWildcard:il(L(e,"trustedOrigins"))}},ol=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),al=(e,t)=>{if(C(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?rl(s):ol();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},cl=(e,t)=>_r(e,t,al),ll=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Vn(e.getExpression(),t.matchReceiver)?s:void 0},dl=(e,t,s)=>{const n=ll(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!G(i)||me(i))&&!(s.requireUnmodifiedReach===!0&&!hc(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},at=(e,t,s)=>O(e,t,(n,i)=>dl(n,i,s)),ul=new Set(["content","pdf","scrape","screenshot"]),fl=(e,t)=>at(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ul}),pl=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),gl=new Set(["RateLimiter"]),ml=new Set(["extend"]),Hs="lunora",hl=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],di=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},$t=e=>e&&r.isObjectLiteralExpression(e)?di(e):{analyzable:!1,presentKeys:[],trueKeys:[]},vl=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Mn(t.getBody());return s?di(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},El=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=C(n.getExpression());i!==void 0&&(pl.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...$t(n.getArguments()[0])}):ml.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...vl(n.getArguments()[0])}))}for(const n of E(e,d.NewExpression)){const i=C(n.getExpression());i===void 0||!gl.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...$t(n.getArguments()[0])})}return s},xl=e=>{for(const t of hl){const s=v(e,t);if(!_(s))continue;const n=new Jt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Xe(s,"utf8")),i=[];for(const o of E(n,d.CallExpression))C(o.getExpression())===Hs&&i.push({callee:Hs,file:t,line:o.getStartLineNumber(),...$t(o.getArguments()[0])});return i}return[]},Sl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...El(o,n))}return s.push(...xl(Ze(t))),s},Gs="ctx.containers.",Al=e=>{if(!e.startsWith(Gs))return!1;const t=e.slice(Gs.length);return t.length>0&&!t.includes(".")},yl=(e,t)=>at(e,t,{argIndex:0,matchReceiver:Al,methods:new Set(["get"])}),bl=new Set(["allow","deny","setAllowed"]),Nl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=q(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},Pl=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Nl(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},wl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!bl.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Il=(e,t)=>Pl(e,t)??wl(e,t),Cl=(e,t)=>O(e,t,Il),Tl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&$(s.getExpression())?s.getName():void 0},Ol=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&$(s)?1:0]},kl=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Rl=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>kl.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Fl=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=Tl(i);if(a===void 0)return;const c=Rl(Ol(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},Ll=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Dl=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Ll.has(s)?s:void 0},_l=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Ml=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of E(o,d.CallExpression)){const c=Dl(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?_l(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},zl=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),$l=new Set(["dbRateLimit","rateLimit"]),Kl=e=>{const t=$n(e);if(!t)return!1;const s=q(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Bl=(e,t)=>{const s=C(e.getExpression());if(s===void 0)return;const n=zl.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:Kl(e.getArguments()[n]),file:t,limitName:$l.has(s)?zn(e):"",line:e.getStartLineNumber()}},Vl=(e,t)=>O(e,t,Bl),Ul=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ie(t);if(s?.kind!=="query")return;const n=Mr(t,s.receiver);return n?{exportName:Y(e)??e.getName(),handler:n}:void 0},Ys=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Wl=e=>{const t=Ys(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Ys(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},ql=(e,t)=>{const s=[];for(const n of it(e.handler,"flags"))s.push({callee:Wl(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},jl=(e,t)=>{const s=[];for(const n of Z(e)){const i=Ul(n);i&&s.push(...ql(i,t))}return s},Hl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...jl(i,I(t,n)))}return s},Gl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:J(e.getExpression(),["flags"]),Yl=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Ql=(e,t)=>{if(!Gl(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Yl(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},Jl=(e,t)=>O(e,t,Ql),Xl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Zl=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},ed=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of E(i,d.CallExpression))Xl(a)&&s.push({file:o,indexName:Zl(a),line:a.getStartLineNumber()})}return s},td=new Set(["delete","get","head","options","patch","post","put"]),sd=new Set(["handler","stream"]),nd=new Set(["runAction","runMutation"]),id=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Ce=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,ui=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ge(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Qs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:ui(s,"ctx")},Js=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:ui(s,"request")},Xs=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(nd.has(a)&&Ce(c,t))return a;if(id.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Ce(c.getExpression(),t))return`db.${a}`}},Zs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Ce(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Ce(n.getInitializer(),t))){for(const o of i.getElements())if(ge(o)==="auth")return!0}}return!1},rd=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,od=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Ce(n.getExpression(),t)},ad=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],fi=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:ad(s)},cd=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?fi(t,a.getText()):[]}return[]},ld=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=fi(s,t.getText());return n.length>0?n:cd(t,s)},en=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>od(i,t)&&ld(i).some(o=>rd.test(o)))},dd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!sd.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(td.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},ud=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Dt(e.getArguments()[0]),l=c&&Qs(c,!0);if(!c||l===void 0||en(c,Js(c,!0)))return;const u=Xs(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Zs(c,l),sideEffect:u}}const n=dd(e);if(n===void 0)return;const i=Dt(e.getArguments()[0]),o=i&&Qs(i,!1);if(!i||o===void 0||en(i,Js(i,!1)))return;const a=Xs(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Zs(i,o),sideEffect:a}},fd=(e,t)=>O(e,t,ud),pd=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),gd=new Set(["append","set"]),pi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",tn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>pd.has(C(n.getExpression())??"")&&ze(n,t)),md=(e,t)=>{if(tn(e,t))return!0;const s=X(e);return s!==void 0&&tn(s,t)},Kt=(e,t)=>vc(e,t)&&!md(e,t),hd=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=X(e);return t!==void 0&&r.isNewExpression(t)&&C(t.getExpression())==="Headers"},je=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=X(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},cs=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Kt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:pi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Kt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=je(n.getExpression());i!==void 0&&cs(i,t,s)}},gi=(e,t)=>{const s=je(e);if(s===void 0)return;const n=q(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=je(n.getInitializer());i!==void 0&&cs(i,"response-init",t)},vd=(e,t)=>{const s=C(e.getExpression());if(s==="Response")gi(e.getArguments()[1],t);else if(s==="Headers"){const n=je(e.getArguments()[0]);n!==void 0&&cs(n,"headers-ctor",t)}},Ed=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){gi(e.getArguments()[1],t);return}if(gd.has(n)&&hd(i)){const o=e.getArguments()[1];o!==void 0&&Kt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:pi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},xd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))vd(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Ed(s,t)},Sd=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Dt(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return xd(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},Ad=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression))s.push(...Sd(n,t));return s},yd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ad(i,I(t,n)))}return s},mi="identity.ts",bd=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return rt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Nd=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&rt(n.getModuleSpecifierValue())}return!1},Pd=e=>{if(r.isIdentifier(e))return bd(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Nd(t)}return!1},wd=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Pd(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw de(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=nt(s,"member");a!==void 0&&t.push({exportName:a})}return t},Id=(e,t)=>{const s=v(t,mi);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=wd(n);if(i.length!==0){if(i.length>1)throw de(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Cd=new Set(["auth","context.auth"]),Td="userId",Od=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},kd=(e,t)=>{const s=v(t,mi);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(C(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Od(o):void 0}},sn=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Cd.has(t.getText())||J(t,["auth"])?e:void 0},Rd=e=>{if(r.isPropertyAccessExpression(e)&&sn(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&sn(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},nn=(e,t,s)=>{const n=Rd(e);return n===void 0?void 0:{declared:n===Td||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},Fd=(e,t)=>{const s=kd(e,t);return s===void 0?[]:[...ae(e,t,d.PropertyAccessExpression,(n,i)=>nn(n,i,s)),...ae(e,t,d.ElementAccessExpression,(n,i)=>nn(n,i,s))]},Ld=(e,t)=>{if(C(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=L(s,"key");if(!(!n||!G(n)||me(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Dd=(e,t)=>O(e,t,Ld),_d=new Set(["delete","get","getRaw","getWithMetadata","put"]),Md=(e,t,s=[])=>{const n=at(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:_d});return ts(n,s)},zd=new Set(["queue","send"]),rn=new Set(["bcc","cc","to"]),$d=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!zd.has(t))return;const s=e.getExpression();return J(s,["mail"])||J(s,["email"])?t:void 0},Kd=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return rn.has(A(t))&&G(n)&&!me(n)}if(!r.isPropertyAssignment(t)||!rn.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&G(s)&&!me(s)}):!1,Bd=(e,t)=>{const s=$d(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Kd(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Vd=(e,t)=>O(e,t,Bd),Ud=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=qe(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=qe(l);if(u===void 0)continue;const f=Qn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Wd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;return n?.receiver?ns(n.receiver).flatMap(i=>Ud(i,Y(e)??e.getName(),t)):[]},qd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Wd(a,o))}return s},jd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},Hd=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=q(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Gd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return co(s.getExpression())?s:void 0},Yd=e=>{const t=Gd(e),s=t===void 0?void 0:Hd(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?Y(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>jd(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Qd=e=>e.getVariableDeclarations().flatMap(t=>Yd(t)),Jd=(e,t)=>{const s=v(t,ao);if(!_(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Qd(n)},Xd=new Set(["delete","get","patch"]),Zd=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),eu=new Set(["auth","identity","session","user"]),tu=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),su=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!$(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},nu=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},iu=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),ru=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,ou=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>iu(s.getExpression(),t)&&ru(s.getThenStatement())),au=(e,t)=>{for(const s of E(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Xd.has(i))continue;const o=n.getExpression(),a=$(o);if(!(a||r.isPropertyAccessExpression(o)&&$(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},cu=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>ss(tt(s))!==void 0)),lu=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>tu.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),du=e=>{for(const t of E(e,d.Identifier))if(Zd.has(t.getText()))return!0;return[...eu].some(t=>it(e,t).length>0)?!0:cu(e)||lu(e)},uu=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&jn(n.receiver,"use","rls"),a=du(i),c=new Set,l=[];for(const u of E(i,d.CallExpression)){const f=su(u);if(f===void 0)continue;const p=nu(u);if(p===void 0||c.has(p)||!ou(i,p))continue;const m=au(i,p);m!==void 0&&(c.add(p),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},fu=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...uu(a,o))}return s},hi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},pu=e=>{const t=T(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!st(s)},gu=e=>{const t=T(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},mu=e=>{const s=T(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!st(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},He=e=>{const t=D(e);return t===void 0||Ur(t.getSourceFile())},Bt=(e,t)=>{const s=T(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&He(o);if(hi(tt(o),t))return!(r.isPropertyAccessExpression(o)&&Un.has(o.getName()))||r.isExpressionStatement(T(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!He(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},$e={kind:"opaque"},hu={kind:"unreached"},vu=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Vt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=vu(s);return i===void 0||es(i)?void 0:i}const n=ce(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},vi=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?$e:c===void 0?a.some(l=>l.isRestParameter())?$e:hu:c.isRestParameter()?$e:{kind:"parameter",parameter:c}},Eu=e=>{const t=T(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Vt(s.getExpression());return n===void 0?$e:vi(n,s,t)},xu=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Su=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Ei=e=>{const t=T(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Su(s);if(n!==void 0)return N(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},Au=4,xi=(e,t,s=0)=>{if(Vr(e))return!0;if(pu(e)){const i=T(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!xu.has(c)}if(gu(e)||mu(e)||Ei(e)||Bt(e,t))return!0;const n=Eu(e);return n?.kind==="unreached"||n?.kind==="parameter"&&yu(n.parameter,s+1)},on=new WeakMap,yu=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=on.get(e.compilerNode);if(n!==void 0)return n;if(t>Au)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||xi(a,void 0,t));return(o||t===0)&&on.set(e.compilerNode,o),o},an=new WeakMap,bu=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=D(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Nu=(e,t,s)=>{const{context:n,impl:i}=e,o=an.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(p=>{const m=p.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(p=>[p.getText(),p.getParentOrThrow().compilerNode])),u=p=>r.isIdentifier(a)?xi(p,n):!st(p),f=!bu(i,s)&&c.every(p=>(p.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(p=>{const m=p.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(p)||D(p)?.compilerNode!==x?!0:u(p)});return an.set(i.compilerNode,f),f},cn=new WeakMap,Pu=e=>{let t=cn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=lo(s);return n===void 0?[]:[[n.compilerNode,s]]})),cn.set(e.compilerNode,t)),t},wu=e=>{const t=Pu(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:Y(n)??n.getName()};return a!==void 0&&Nu(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},Pt="args",Ne=e=>{const t=Zt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===Pt?t.member:void 0}if(!r.isIdentifier(e))return;const s=D(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ce(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ge(i)===Pt||r.isIdentifier(o)&&o.getText()===Pt?ge(s):void 0},Iu=new Set(["auth","identity","user"]),Ut=e=>{const t=i=>{const o=ss(i);return o!==void 0&&o.length>0&&Iu.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=X(s);return n!==void 0&&t(n)},Si=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Ne(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?X(n):void 0;if(o!==void 0)for(const a of Si(o,t-1))s.add(a)}return s},Ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Ke(n),...Ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const p=Ne(h(u)??u);return p===void 0?[]:Ke(f).filter(m=>m===p)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Ne(h(n)??n),c=Ne(h(i)??i);return a!==void 0&&Ut(i)&&o.push(a),c!==void 0&&Ut(n)&&o.push(c),o},Cu=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&Jr(i.getExpression(),"defineIdentityGuard")},Tu=e=>{if(!Cu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Ne(h(s)??s),o=t.some((a,c)=>c!==n&&Ut(a));return i!==void 0&&o?[i]:[]})},Ou=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},ku=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),ln=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Ru=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Fu=(e,t)=>{const s=new Set;for(const n of E(e,d.IfStatement))if(n.getEnd()<=t&&ln(n,e)&&Ou(n.getThenStatement()))for(const i of Ke(n.getExpression()))s.add(i);for(const n of E(e,d.CallExpression))if(n.getEnd()<=t&&Ru(n)&&ln(n,e))for(const i of Tu(n))s.add(i);return s},Lu=(e,t)=>{const s=Si(t);if(s.size===0)return!1;const n=e.getFirstAncestor(ku);if(n===void 0)return!1;const i=Fu(n,e.getStart());return[...s].every(o=>i.has(o))},Du=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),_u=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Wt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Ai=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Mu=e=>{const t=T(e),s=t.getParent();if(r.isVariableDeclaration(s))return N(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},zu=e=>{const t=Mu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ce(t)?[t]:void 0:Ai(t)},Pe=e=>e.isUnion()?e.getUnionTypes().every(t=>Pe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Pe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ge=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Be=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},$u=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&_u.get(s.getText())?.has(t.getName())===!0&&He(s)},Ku=e=>{const t=Ft(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=T(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ge(n,Wn)?n:void 0},Bu=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=T(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ge(n,Du,t)?n:void 0},Vu=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Uu=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&N(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},dn=e=>{const t=T(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&$u(s);return Bu(s,t)??Vu(s,t)??Uu(s,t)??(n?s:Ku(t))},Wu=5e4,yi=()=>({inProgress:new Set,verdicts:new Map});class qu{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Wu&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const ju=8,Hu=8;class Gu{budget;scope;taint;verdicts=yi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Pe(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Ai(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=ju?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(T(l),!0,a,0))&&(t===n||!Pe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=dn(o);m!==void 0;m=dn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=T(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Pe(o.getType());if(st(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=zu(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const p=this.nestedReturningFunctionOf(o);return p!==void 0?this.resultCompromises(p,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=T(t).getParent();if(n>=Hu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===T(t)?this.valueCompromises(i,!1,s,n+1):!Ge(i,Wt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ce(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=T(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Be(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ge(t,Wt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Vt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!Bt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(Bt(s,this.scope.context))return!1;const i=Vt(t.getExpression()),o=i===void 0?void 0:vi(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Ei(t)||N(Ft(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Ft(t);return N(s,this.scope.impl)?void 0:s}}const Yu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Qu=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=D(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Ju=new Set(["all","allSettled","any","race"]),un=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,wt=8;class Xu{budget=new qu;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=yi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Gu(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,wt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Wr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=D(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(p=>p.getInitializer())].some(p=>p!==void 0&&this.isTaintedValue(p,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(p=>p.compilerNode===t.compilerNode):-1,o=T(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const p=h(a.getExpression());if(!r.isPropertyAccessExpression(p)||!Wt.has(p.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(p.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&ce(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(p=>{const m=T(p),x=m.getParent();return!r.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&He(i)&&Ju.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(p=>!r.isSpreadElement(p)&&this.isRootedInContext(p,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Be(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),i=un(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Un.has(i)?!1:i!==void 0&&Wn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Be(a)!==void 0)&&(i===void 0||!Yu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=tt(i),c=r.isIdentifier(a)?un(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Be(i);if(o===void 0)return!Qu(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=zr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(hi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?D(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ce(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=es(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,wt))return!1;if(this.variableDepth>=wt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const fn=new WeakMap,Zu=e=>{const t=fn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Xu(e);return fn.set(e.impl.compilerNode,s),s},ef=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),tf=new Set(["insert","insertManyUnsafe","patch","replace"]),sf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return tf.has(t)&&Gr(e.getExpression())?t:void 0},nf=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},rf=(e,t)=>{const s=Zt(e);return s?.member===t?h(s.object):void 0},pn=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,bi=(e,t,s,n=1)=>{const i=rf(e,s);if(i!==void 0)return pn(i,t);const o=r.isIdentifier(e)?D(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ge(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ce(l)&&pn(h(l.getInitializer()),t))}const a=ce(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&bi(a,t,s,n-1)},qt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...qt(t.getWhenTrue()),...qt(t.getWhenFalse())]:[t]},of=(e,t,s)=>{const n=[],i=s===void 0?void 0:Zu(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!ef.has(a))continue;const l=qt(c).filter(f=>i===void 0?G(f)&&!Yr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&bi(c,s.parameter,a),p=l.every(m=>Lu(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...p&&{guarded:!0}})}}return n},af=(e,t,s)=>{const n=sf(e.getExpression()),i=n==="patch"||n==="replace"?2:1,o=n===void 0?void 0:e.getArguments()[i];if(n===void 0||o===void 0)return[];const a=nf(o,n);if(a.length===0)return[];const c=S(e),l=wu(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>of(f,u,l))},cf=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>af(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return ts(o,s).map(c=>qr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},lf=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),df=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,uf=e=>{const t=q(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?df(t.getInitializer()):void 0},ff=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!lf.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?uf(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},pf=(e,t)=>O(e,t,ff),gf=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),mf=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},hf=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=q(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Ni=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Pi=(e,t)=>e===t||e.startsWith(`${t}.`),wi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},gn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},Ii=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>gn(s));return r.isIdentifier(e)&&gn(e)&&t.push(e),t},vf=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Ef=e=>{const t=Ni(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},xf=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Ef(e),i=new Set,o=a=>wi(a).some(c=>n.some(l=>Pi(c.getText(),l)))?!0:Ii(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of vf(a))i.add(l)}return{names:i,prefixes:n}},Sf=(e,t)=>wi(e).some(s=>t.prefixes.some(n=>Pi(s.getText(),n)))?!0:Ii(e).some(s=>t.names.has(s.getText())),Af=e=>{const t=$r(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},yf=(e,t,s)=>{const n=Ni(e,0);if(n===void 0)return[];const i=xf(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!Kn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Sf(u,i))continue;const f=Af(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:S(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},bf=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=mf(n),o=i===void 0?void 0:gf.get(i);if(o===void 0)continue;const a=hf(n,o);a!==void 0&&s.push(...yf(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Nf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...bf(i,I(t,n)))}return s},mn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},hn=new Set(["account","credential","member","passkey","session","user"]),Pf=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),wf=e=>{const s=Pf(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return hn.has(s)||hn.has(n)},If=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Cf=(e,t)=>{const{objects:s,opaque:n}=os(e,t);return Mc(s).some(i=>If(i))?!0:n?void 0:!1},Tf=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!q(t,"captcha"),usesRateLimit:!!q(t,"rateLimit")}},Of=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Ve={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},kf=e=>{const t=Of(e),s=t?C(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Tf(t);return{...Ve,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in mn?{...Ve,[mn[s]]:!0}:Ve},Rf=e=>{const t={...Ve};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=kf(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Ff=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Lf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ff.has(t.getName()))return!1;const s=t.getExpression();if(!$(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:wf(i.getLiteralText())},Df=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),vn=new Set(["queues","scheduler","topics","workflows"]),_f=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Df.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&vn.has(s.getName())&&Qr(s.getExpression()))return!0;s=s.getExpression()}const n=ss(s);return n?.length===1&&vn.has(n[0]??"")},Mf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},Ci=new Set(["generateObject","generateText","streamObject","streamText"]),zf=e=>{const t=C(e.getExpression());return t!==void 0&&Ci.has(t)},$f=e=>{const t=C(e.getExpression());if(t===void 0||!Ci.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!q(s,"maxOutputTokens")},Kf=new Set(["log","span","trace"]),Bf=new Set(["ai"]),Vf=new Set(["email","mail"]),Uf=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),It=(e,t)=>[...t].some(s=>it(e,s).length>0),Ti=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Wf=new Set(["every","filter","flatMap","forEach","map","some"]),qf=new Set(["all","allSettled","race"]),Oi=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Wf.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&qf.has(n))return t},jf=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ti.has(t.getKind())){const s=Oi(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Hf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Ti.has(t.getKind())){if(t=Oi(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Gf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const x=m.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(m.getParent())}),p=u.getCatchClause();return f&&p!==void 0&&p.getDescendantsOfKind(d.ThrowStatement).length>0})},Yf=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Qf=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Jf=e=>{let t=!1,s=!0;for(const n of[...Uf].flatMap(i=>it(e,i))){const i=Qf(n);i&&(t=!0,!jf(i)&&!Yf(i)&&!Gf(i)&&!Hf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Xf=e=>E(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),En="lunora-advisor-exempt",Zf=/^[\s*/]+/u,ep=/[\w-]/u,tp=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
22
|
-
`);for(const n of s.split(`
|
|
23
|
-
`)){const i=n.replace(Zf,"");if(!i.startsWith(En))continue;const o=i.slice(En.length);if(ep.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},sp=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=q(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},np=(e,t)=>{const s=sp(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},ip=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of E(e,d.CallExpression))if(Lf(l)&&(o=!0),_f(l)&&(t=!0),Mf(l)&&(i=!0),zf(l)&&(s=!0),$f(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Jf(e);return{callsMail:It(e,Vf),emitsEvent:It(e,Kf),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||It(e,Bf),throwsBareError:Xf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},rp=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ie(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Rf(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=np(e,s);return{...o?ip(o):{},...tp(e),...i,analyzableBody:o!==void 0,exportName:Y(e)??e.getName(),file:t,hasEmailArg:Cf(s,n.receiver),kind:n.kind,visibility:n.visibility}},op=(e,t)=>{const s=[];for(const n of Z(e)){const i=rp(n,t);i&&s.push(i)}return s},ap=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...op(i,I(t,n)))}return s},cp=new Set(["dbRateLimit","rateLimit"]),lp=e=>r.isArrowFunction(e)?e.getBody():e,dp=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},ki=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Ri=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},up=(e,t)=>G(e)||t!==void 0&&Ri(e,t).some(s=>ki(s)),fp=(e,t)=>t===void 0?me(e):Ri(e,t).some(s=>!ki(s)),pp=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!cp.has(s))return;const n=L($n(e.getArguments()[2]),"key");if(!n)return;const i=lp(n),o=dp(n);if(!(!up(i,o)||fp(i,o)))return{callee:s,scope:S(e),file:t,limitName:zn(e),line:e.getStartLineNumber()}},gp=(e,t)=>O(e,t,pp),mp=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),hp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!mp.has(t.getName()))return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&$(s.getExpression()))return s.getName()},vp=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&$(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Ep=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Fi=(e,t=!1)=>{const s=Ep(e);if(r.isIdentifier(s)){if(t)return;const n=X(s);return n===void 0?void 0:Fi(n,!0)}if(r.isCallExpression(s))return hp(s)??vp(s)},xp=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of E(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},Sp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Xr(n.receiver,"output"),a=n.receiver!==void 0&&jn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of xp(i)){const f=Fi(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Ap=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Sp(a,o))}return s},yp=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},bp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=yp(L(a.options,"with"));c.length!==0&&i.push({exportName:Y(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Np=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...bp(a,o))}return s},H=(e,t)=>`${e}:${t}`,xn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Pp=(e,t)=>[...ae(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?xn(s,n,s.getName(),s.isExported()):void 0),...ae(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?xn(i,n,s.getName(),i.isExported()):void 0})],wp=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(H(c,a))},Ip=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Cp=(e,t)=>{const s=new Map(e.map(n=>[H(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(H(i.file,i.name))?.set(Ip(n),{fields:n.fields,method:n.method,table:n.table})}return s},Tp=(e,t,s)=>E(e.node,d.CallExpression).map(n=>wp(n,t,s)).filter(n=>n!==void 0),Op=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(H(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(H(o.file,o.name))?.push(a)}},kp=(e,t,s)=>{const n=new Map(e.map(a=>[H(a.file,a.name),a])),i=new Map(e.map(a=>[`${is(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[H(a.file,a.name),Tp(a,n,t)]));return Op(s,n,i,o),o},Rp=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Fp=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(H(i.file,i.name))??[])Rp(t.get(H(i.file,i.name)),t.get(H(o.file,o.name)))&&(n=!0)}},Lp=(e,t,s,n)=>{const i=Pp(e,t),o=Cp(i,s);return Fp(i,o,kp(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(H(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ye=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ye(e.getLeft()),s=Ye(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Dp=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ye(t)!==void 0},_p=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Mp=(e,t,s)=>So(e)?!Kr(s)&&Ao(_p(t)):!0,zp=(e,t)=>{const s=[],n=[...E(e,d.BinaryExpression),...E(e,d.StringLiteral),...E(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Dp(o))continue;const a=Ye(o);if(a===void 0)continue;const c=Eo(a);if(c===void 0||!Mp(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:xo(a)}))}return s},$p=(e,t)=>{const s=[],n=new Jt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Xe(i,"utf8"),{overwrite:!0});s.push(...zp(o,I(t,i)))}return s},Kp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=L(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&G(c);!l&&!u||i.push({exportName:Y(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Bp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Kp(a,o))}return s},Vp=new Set(["query","unsafe"]),Up=e=>!r.isPropertyAccessExpression(e)||!Vp.has(e.getName())?!1:J(e.getExpression(),["sql"]),Wp=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),qp=(e,t)=>{if(!Up(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Wp(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},jp=(e,t)=>O(e,t,qp),Hp=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Gp=e=>{for(const[t,s]of Hp)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Yp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Gp(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Qp=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Jp=(e,t,s=[])=>{const n=at(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Qp,requireUnmodifiedReach:!0});return ts(n,s)},Xp=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Zp=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,eg=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=Zp(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},tg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Xp.get(t);return s===void 0?void 0:Vn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},sg=(e,t)=>{const s=tg(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...eg(e.getArguments()[s.optionsIndex])}},ng=(e,t)=>O(e,t,sg),ig=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Li=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:ig(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>le(i)||s(i));if(!(n===void 0||le(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},ls=(e,t)=>N(e.getFirstAncestor(s=>N(s,t)||le(s)),t),rg=(e,t)=>N(e,t)||e.getFirstAncestor(s=>N(s,t))!==void 0,Di=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return N(e,t)||ls(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Li(e);return s!==void 0&&!rg(s,t)}return!1},_i=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],og=e=>_i(e).some(t=>Di(t,e)),ag=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},cg=e=>_i(e).some(t=>Di(t,e)||r.isBreakStatement(t)&&N(Li(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>ag(t)&&ls(t,e)),lg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>ls(t,e)),dg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),ug=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Ct=(e,t)=>{const s=dg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||cg(e)||lg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(le)!==void 0))return{file:t,kind:ug(e),line:e.getStartLineNumber(),scope:i}},fg=(e,t)=>[...ae(e,t,d.WhileStatement,Ct),...ae(e,t,d.ForStatement,Ct),...ae(e,t,d.DoStatement,Ct)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),pg=new Set(["when","where"]),Tt=new Set(["definePolicy","defineShape"]),gg=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Tt.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return Tt.has(i)?i:void 0}const s=t.getText();return Tt.has(s)?s:void 0},mg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Mi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(mg(e))return"empty-object";if(r.isParenthesizedExpression(e))return Mi(e.getExpression())}},ds=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),hg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ds(t)===e),zi=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>ds(t)===e),vg=e=>{const t=hg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||zi(e).length>0},Eg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>ds(t)===e),jt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",xg=(e,t)=>jt(e)||jt(t),Sg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Sn=e=>!jt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Ag=(e,t,s)=>{const n=Sg.get(e);if(n!==void 0)return xg(t,s)?n==="positive"?"negative":"positive":Sn(t)||Sn(s)?void 0:n},we=e=>{if(r.isParenthesizedExpression(e))return we(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Ag(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=we(e.getLeft()),i=we(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},An=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},yg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},bg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Ng=e=>{const t=[];for(const s of zi(e)){const n=we(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Eg(e)){const n=we(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?An(s.getThenStatement()):An(s.getElseStatement())??yg(s);i!==void 0&&t.push(bg(i))}return t},Pg=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},wg=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!pg.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&vg(a))for(const c of Ng(a)){const l=Mi(c);l!==void 0&&i.push({exportName:Pg(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},Ig=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=gg(n);i!==void 0&&s.push(...wg(n,i,t))}return s},Cg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ig(i,I(t,n)))}return s},Tg=new Set(["query","upsert","upsertMany","upsertNow"]),ve=new Set,Og=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Tg.has(t))return J(e.getExpression(),["vectors"])?t:void 0},us=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},$i=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Ki=e=>$i(e)?.getDeclarations()[0],kg=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Bi=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},yn=(e,t,s)=>{const n=$i(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Bi(Ki(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return fs(o,t,s-1)}return G(e)},fs=(e,t,s)=>{const n=us(e);return me(n)?!1:r.isIdentifier(n)?yn(n,t,s):G(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>kg(i)&&yn(i,t,s))},Vi=e=>{const t=Bi(Ki(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ne=(e,t)=>{const s=us(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ne(s.getWhenTrue(),t),...ne(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ne(s.getLeft(),t),...ne(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Vi(s);return n===void 0?[]:ne(n,!1)}return[]},Rg=(e,t)=>{const s=ne(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Qe(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Fg=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Lg=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Qe=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Rg(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Fg(n)&&(s=[Lg(n)]);return s},Dg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},_g=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return ve;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return ve;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Ht=(e,t=!0,s=ve)=>{const n=us(e);if(r.isIdentifier(n)){const o=t?Vi(n):void 0;return o===void 0?[{node:n,parameters:s}]:Ht(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Ht(o.getExpression(),t,s):ne(o,!0).flatMap(a=>Qe(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=fs(i.getExpression(),ve,1)?_g(o):ve;return Dg(o).flatMap(c=>ne(c,!0).flatMap(l=>Qe(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Mg=(e,t)=>{const s=Og(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Ht(n):ne(n,!0).flatMap(o=>Qe(o,!0).map(a=>({node:a,parameters:ve})))).some(({node:o,parameters:a})=>fs(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},zg=(e,t)=>O(e,t,Mg),$g=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:p,wranglerVariables:m,workflows:x}=s;return Lr({adminRoutes:uc(e,t),aiRawRuns:Sc(e,t),aiToolSideEffects:kc(e,t),argumentDerivedFetches:Lc(e,t),argumentValidators:Xc(e,t),authApiCalls:so(e,t),authConfigs:cl(e,t),browserUrlAccesses:fl(e,t),callEdges:n.callEdges,configCalls:Sl(e,t),containerKeyAccesses:yl(e,t),containerOverrides:Cl(e,t),containers:i,countReads:Fl(e,t,f.tables),crons:o,cronTargets:o.flatMap(M=>M.functionPath===void 0?[]:[M.functionPath]),exportSinks:Ml(e,t),staleMigrationImports:Yp(e,t),failOpenGuards:Vl(e,t),flagReads:Hl(e,t),flagSecurityDefaults:Jl(e,t),geoIndexUsages:ed(e,t),httpActionGuards:fd(e,t),httpHeaderWrites:yd(e,t),hyperdriveCalls:ro(e,t),identityClaimReads:Fd(e,t),imageDeliveryUrlAccesses:Dd(e,t),inserts:n.inserts,kvKeyAccesses:Md(e,t,a),mailRecipientAccesses:Vd(e,t),maskProcedures:oo(e,t),maskStrategies:qd(e,t),mutatorWrites:Jd(e,t),nondeterministicCalls:fo(e,t),normalizeIdAuthorizations:fu(e,t),notifyCalls:go(e,t),notifyConfig:po(e,t),mutators:l,ownerFieldWrites:cf(e,t,a,l),unrestrictedWhereBranches:Cg(e,t),paymentWebhooks:pf(e,t),privilegedDispatches:Nf(e,t),procedureProtections:ap(e,t),queries:n.queries,queues:u,r2sqlCalls:mo(e,t),ratelimitKeySelectors:gp(e,t),rawRowReturns:Ap(e,t),relationLoads:Np(e,t),rlsProcedures:ho(e,t),schema:f,secretLiterals:$p(e,t),modules:c,shapes:p,softDeleteReads:Bp(e,t),sqlInterpolations:jp(e,t),storageKeyAccesses:Jp(e,t,a),storageUploads:ng(e,t),tableWrites:n.tableWrites,rowEffects:Lp(e,t,n.tableWrites,n.callEdges),unboundedLoops:fg(e,t),vectorNamespaceAccesses:zg(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:m})},Kg=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),Bg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>Kg(i))]},Vg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Ug=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",bn={error:"ERROR",info:"INFO",warn:"WARN"},Nn={ERROR:2,INFO:0,WARN:1},Wg=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),qg=(e,t)=>{const{advisor:s}=Jn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(bn,n)?bn[n]:void 0;return i===void 0?[...t,Wg(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>Ug(o)||Nn[o.level]>=Nn[i])},jg=(e,t)=>{const{advisor:s}=Jn(e),n=Bg(t,s?.accept??[]);return qg(e,s?.acceptUnreadable===!0?[...n,Vg()]:n)},Hg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Gg="crons",Yg=To.replace(/\.ts$/u,""),he=(e,t)=>`${is(e)}:${t}`,Ot=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Qg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Hg[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...Ot("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Ot("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Ot("workflow",t.workflow,"workflow name")}))],Jg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Xg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Jg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Zg=e=>Qg(e).flatMap(t=>Xg(t)),em=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:Gg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],tm=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),be=(e,t)=>t===void 0?e:{...e,module:t},sm=e=>{const t=new Map,s=new Map,n=tm(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(he(c.file,c.exportName),l)};for(const c of e.functions){const l=he(c.filePath,c.exportName),u=[...vo(c.filePath),c.exportName].join(".");o(be({detail:c.kind,id:`function:${l}`,kind:"function",name:u},_e(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=he(c.filePath,c.exportName);o(be({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},_e(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(be({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(be({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},_e(e.modules,c.filePath)),he(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(be({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},_e(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},he(Yg,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},nm=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,im=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(he(e.file,e.exportName))??{reason:nm(e.exportName)},rm=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=im(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},kt=e=>`${e.from}|${e.kind}|${e.to}`,om=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,am=e=>{const{nodes:t,sites:s}=sm(e),n=new Map,i=new Map;for(const o of[...em(e),...Zg(e)]){const a=rm(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(kt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(om(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>kt(o).localeCompare(kt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},cm=e=>`${Xn}export const architecture = ${ko(e,"Record<string, unknown>")};
|
|
24
|
-
`,Pn=(e,t="api")=>{const s=new Map;for(const n of e){const i=is(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new R("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},lm=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Zn(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>ei(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:Vo)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},dm=(e,t,s={})=>{if(t===void 0)return;const n=lm(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
25
|
-
`);throw new R("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
26
|
-
${i}
|
|
27
|
-
|
|
28
|
-
Install them with your package manager, then re-run codegen.`)},um="env.ts",fm=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return rt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},pm=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&rt(n.getModuleSpecifierValue())}return!1},gm=e=>{if(r.isIdentifier(e))return fm(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&pm(t)}return!1},mm=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!gm(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw de(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=nt(s,"member");a!==void 0&&t.push({exportName:a})}return t},hm=(e,t)=>{const s=v(t,um);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=mm(n);if(i.length!==0){if(i.length>1)throw de(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},vm={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Em=new Set(["allowedHosts","deniedHosts","interceptHttps"]),xm=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},Sm=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Am=new Set(["durable"]),ym=new Set(["rollback"]),Ui=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},bm="defineApp",Ie="app",wn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Ie&&s.getInitializer()?.getText()===t)||t===Ie&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Ie),Nm=e=>{if(e===void 0||!Jo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Ie;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Ie;if(r.isVariableDeclaration(t))return wn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&wn(e.getSourceFile(),s)},Pm="AppBuilder",Wi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},wm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Pm&&s.getDeclarations().some(n=>Wi(n))},Im=e=>e.getText()===bm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Wi(t)),qi=(e,t,s=new Set)=>{const n=tt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(Im(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return Nm(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return qi(e,a.getInitializer(),s)}}return!1},ji=(e,t)=>{const s=Zt(t.getExpression());return s?.member==="deliveryAuthorization"&&(qi(e,s.object)||wm(s.object))},Cm=new Map([["defineContainer",{keys:Em,signal:"containerEgressPolicy"}],["defineStep",{keys:ym,signal:"workflowRollback"}],["stream",{keys:Am,signal:"durableStreams"}]]),Tm=(e,t)=>{const s=Cm.get(Ui(t));if(s!==void 0)return t.getArguments().some(n=>Sm(xm(e,n),s.keys))?s.signal:void 0},Om=(e,t)=>vm[Ui(t)]??(ji(e,t)?"deliveryAuthorization":void 0),km=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Ho(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=Tm(o,c)??Om(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>Hn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Jt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Xe(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>ji(i,o))}return n},Rm=(e,t)=>{const s=Go();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Yo(i,s))return!0}return!1},Fm="createWorker",Lm="extend",In=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Cn=e=>{const t=[],s=In(L(e,"backupCron"));s!==void 0&&t.push(s);const n=L(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=In(i.getNameNode());o!==void 0&&t.push(o)}return t},Dm=e=>{const t=C(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Fm)return r.isObjectLiteralExpression(s)?Cn(s):[];if(t!==Lm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Mn(s.getBody());return n===void 0?[]:Cn(n)},_m=(e,t)=>{const s=[];for(const{filePath:n}of et(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...Dm(o))}return[...new Set(s)]},Hi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Hi(e.inner)},Mm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Hi(n);return i!==void 0&&t.has(i)}))},zm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new R("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new R("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},$m=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Id(s,t),a=hm(s,t),c=Oo(s,t),{queues:l,topics:u}=Zo(s,t),f=ta(n),p=Wo(s,t);zm(c,p);const m=qo(s,t),x=sa(s,t),M=jo(s,t,c,p),K=_m(s,t),P=km(s,t,si(n)),V=ea(s,t),ee=Rm(s,t),w=Qo(s,t);w.browser=w.browser||V.usesSandboxBrowser;const U=Me(n,e.target),Q=na(w,U,{agents:p.length>0,commitOrderedTables:i.tables.some(b=>b.commitOrdered===!0),cronTriggers:M.length>0,crossShardFanout:i.tables.some(b=>ua(b)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(b=>b.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(b=>b.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(b=>b.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Mm(i),secretValues:ee,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(b=>b.schedules!==void 0)}),F=Q.usage,z=Uo(F),te=Q.signals.vectorStore!==!1,se=Q.signals.services===!1?[]:f,re=ti(n),oe=re??new Set,B=oe.has("lunorash");dm(i,re,{hasVectors:te,scheduler:F.scheduler||M.length>0,storage:F.storage||x.rules.length>0||Object.keys(ni(i)).length>0,usage:F});const k=_(v(t,"flags.ts")),W=_(v(t,"notify.ts"));return{agents:p,capabilities:z,containers:m,crons:M,dataModelContent:ma(i),declaredDependencies:re,dependencies:oe,entryCronTriggers:K,env:a,featureUsage:F,hasFlags:k,hasNotify:W,identity:o,platformGate:{...Q,diagnostics:[...ia(n,e.target),...Q.diagnostics,...ra(U,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[oa(U)]:[],...P.socketRoutes&&P.deliveryAuthorization?[aa(U)]:[]]},queues:l,serverContent:pa({agents:p,capabilities:z,containers:m,env:a,hasVectors:te,hasFlags:k,hasNotify:W,identity:o,queues:l,schema:i,services:se,storageRuleBuckets:x.rules.map(b=>b.bucket),topics:u,useUmbrella:B,workflows:c}),services:se,storageRulesMetadata:x,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:B,workflows:c}},Gi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Km=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},Bm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Vm=/^[\w$]+:[\w$]+$/u,Um=(e,t)=>{const s=Bn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Tn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Wm=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Tn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Xt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Tn(s):void 0}}},qm=(e,t,s)=>({schedule:{argKeys:Wm(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),jm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return Um(s,n);if((s==="runAfter"||s==="runAt")&&Km(t)){const l=Bn(i)??(r.isStringLiteral(i)&&Vm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...qm(s,n,o)}}const a=Bm.get(s),c=a===void 0?void 0:Gi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Hm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Yi=e=>Dr.isOptionalChain(e.compilerNode),Gm=(e,t)=>r.isIfStatement(t)?!N(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?N(e,t.getStatement()):r.isForStatement(t)?N(e,t.getStatement())||N(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:le(t)?t.getFirstAncestor(le)!==void 0:r.isConditionalExpression(t)?!N(e,t.getCondition()):r.isBinaryExpression(t)?!N(e,t.getLeft())&&Hm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Yi(t)?!N(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&og(s)),Ym=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&N(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(le);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&N(o.getFirstAncestor(le),i))===!0},Qm=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&N(e,t.getStatement())||r.isForStatement(t)&&(N(e,t.getStatement())||N(t.getIncrementor(),e)),Jm=(e,t)=>{if(Yi(e)||t==="schedule"&&Ym(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Gm(s,i)){if(!Qm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},On=(e,t,s)=>{if(s===void 0)return;const n=Jm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Xm=(e,t)=>[...O(e,t,(s,n)=>On(s,n,jm(s))),...ae(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Gi(s,"services");return On(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Zm=new Set(["boolean","number","object","string"]),eh=e=>{const t=e.getName();if(!Zm.has(t))return;const s=e.getExpression();return J(s,["flags"])||J(s,["flags","details"])?t:void 0},th=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=eh(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},sh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=th(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},nh=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||ha(o))return;const a=e.getSourceFile().getFilePath();if(va(i,e,a)){const c=Ea(i,e,a,0,new Set);return c===void 0&&xa(o),c}return o},ih=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Zr(t.getNameNode());return s===void 0||s==="namespace"}),rh=(e,t)=>{for(const{filePath:s}of et(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||ih(a)))return i}}},oh="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",ah=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw de(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${oh}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},ch="room:",lh="__lunora_socket__:",dh=/^[A-Za-z]\w*$/u,kn=e=>dh.test(e),uh=e=>`${e}:`.startsWith(ch)||`${e}:`.startsWith(lh),Qi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Ji=e=>Qi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),Rn=e=>A(e),ps=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),fe=(e,t)=>{const s=de(e,`defineLiveStream ${t}`);return new R("LIVE_STREAM_NOT_LITERAL",s.message)},Xi=(e,t,s)=>{const n=ps(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw fe(n??e,`needs ${s} so codegen can read its topics`);if(Ji(i))throw fe(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},fh=(e,t)=>{const s=Rn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw fe(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Ji(n))throw fe(n,`cannot spread into or compute the keys of topic "${s}"`);if(!kn(s)||uh(s))throw new R("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(ps(n,"key")===void 0)return{fields:[],name:s};const a=Xi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>Rn(l)),c=a.find(l=>!kn(l));if(c!==void 0)throw new R("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},ph=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw fe(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Qi(n))throw fe(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=ps(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw fe(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Xi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>fh(a,l))}},gh=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new R("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},mh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},hh=(e,t)=>E(e,d.CallExpression).filter(s=>Hn(s,"defineLiveStream")).map(s=>{const n=mh(s),i=r.isVariableDeclaration(n)?nt(n,"binding"):void 0;if(i===void 0)throw new R("LIVE_STREAM_NOT_EXPORTED",de(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return ph(s,i,t)}),vh=(e,t)=>{const s=y(t).flatMap(n=>hh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return gh(s),s},Eh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,xh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Eh(e):!0,Zi=(e,t=!1)=>{for(const s of e.getProperties()){if(xh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Zi(n,!0))return!0}return!1},Sh=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of ii(n))for(const o of ns(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Zi(a)))return!0}}return!1},Ah=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=qe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=qe(a);c!==void 0&&s.push({column:c,strategy:Qn(a),table:i})}}return s},yh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of ii(i))for(const a of ns(o))for(const c of Ah(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},bh=["providerSubscriptionId","state"],Nh=["providerEventId","processedAt"],Fn=(e,t)=>t.every(s=>s in e.shape),Ph=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Fn(t,bh)&&Fn(s,Nh)},wh=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Ih=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},Ch=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},Th="@lunora/privacy",er="userId",Ln=new Set(["user","users"]),Oh=e=>e.replaceAll("\\","/"),kh="privacy",Rh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),ct=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Te=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",gs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Fh=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},lt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Lh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Fh(s,"tables"),i=ct(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:gs(n).map(a=>Te(a)))t.datasets.set(o,i)},ms=8,Ee=(e,t=0)=>{if(t>ms)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ee(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ee(i,t+1)},Dh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:Ee(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?gs(n):[],o=new Set(i.map(a=>Te(a)));for(const a of wh)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?ct(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Te(a)==="user"&&t.userTables.add(c))}},Dn=(e,t,s)=>{t.datasets.set(ct(e.getArguments()[0])??s,s)},_h=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Te(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},tr=(e,t=0)=>{const s=Ee(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>ms)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?tr(i.getExpression(),t+1):[_h(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Mh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:tr(t)},zh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ee(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?gs(n):[])t.excluded.set(Te(i),r.isPropertyAssignment(i)?ct(i.getInitializer())??"":"")},$h=(e,t)=>{switch(lt(e)){case"actionCacheDataset":{Dn(e,t,"actionCache");break}case"authDataset":{Dh(e,t);break}case"defineDataset":{Lh(e,t);break}case"documentHistoryDataset":{Dn(e,t,"documentHistory");break}}},hs=e=>e!==void 0&&r.isCallExpression(e)&<(e)==="defineDataset",sr=e=>e!==void 0&&r.isCallExpression(e)&&Rh.has(lt(e)??""),Kh=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(hs(i)||sr(i))?n:void 0},nr=(e,t,s=0)=>{const n=Ee(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>ms)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!nr(i.getExpression(),t,s+1))return!1}else if(!hs(i)&&!sr(i)){const o=r.isIdentifier(i)?Kh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Bh=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||nr(t,s)?s:void 0},Vh=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if($h(i,t),lt(i)==="definePrivacy"){const o=Mh(i);zh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Bh(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>hs(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Uh=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),..._(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Oh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Wh=(e,t,s)=>{if(s?.has(Th)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Ln};const n={datasets:new Map,excluded:new Map,userTables:new Set(Ln)},i=[],o=[];for(const f of Uh(e,t)){const p=Vh(f,n);i.push(...p.declared),o.push(...p.privacyCalls)}const a=new Set;for(const f of o){for(const p of f.passed??[])a.add(p);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:Ih(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},ir=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&ir(n,t)),qh=(e,t)=>e.extensionKey!==kh&&(er in e.shape||Object.values(e.shape).some(s=>ir(s,t))),jh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${er}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Hh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>qh(o,t.userTables)).map(o=>o.name),[n]=Ch(s,t.classifications);if(n!==void 0)throw new R("PRIVACY_COVERAGE",jh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new R("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Gh=(e,t)=>{const s=ca(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Yh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),_n=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Qh="",Jh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Xh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Xt.Const?t.getInitializer():void 0},Ue=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ue(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Xh(e);if(n!==void 0)return Ue(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},Zh=(e,t)=>{if(Yh.has(e))return{method:e,tables:Ue(t)??[Qh]}},Rt=(e,t,s)=>e===void 0?void 0:{...e,fields:Jh(t,e.method,s)},ev=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Xt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},tv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=ev(n);if(i!==void 0)return _n.has(s)?Rt({method:s,tables:[i]},e,1):void 0;if($(n))return Rt(Zh(s,e.getArguments()[0]),e,2);if(_n.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Rt({method:s,tables:[n.getName()]},e,1)},sv=(e,t)=>O(e,t,(s,n)=>{const i=tv(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),nv=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),iv=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||q(s,"args")===void 0)return!1}return os(e,t).opaque},rv=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ie(a);c!==void 0&&iv(a,c.receiver)&&s.push(nv(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},ov=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...rv(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},av=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Je=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),rr=e=>!e.isAny(),or=e=>{const t=e.getType();if(!rr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:av.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},cv=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},ar={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},lv=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),dv={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},uv=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),fv={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},pv=(e,t,s)=>{if(!t.some(i=>jr(i)))return dv;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return uv.has(s.typeName)&&!n&&!t.some(i=>Ca(i))?fv:ar},cr=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:lv(u),p=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${p}`:p,title:"Procedure exists at runtime but is missing from the generated API"}},gv=(e,t,s)=>{const n=[];for(const i of Z(e)){const o=r.isIdentifier(i.getNameNode())?Lt(i):[i.getName()],c=o.some(u=>Je(s,t,u))||!cv(i)?void 0:or(i),[l=i.getName()]=o;c!==void 0&&n.push(cr(t,l,c,i.getStartLineNumber(),pv(i,o,c)))}return n},mv=(e,t,s)=>{if(Je(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=or(i.getExpression());o!==void 0&&n.push(cr(t,"default",o,i.getStartLineNumber(),ar))}return n},hv=(e,t,s)=>[...gv(e,t,s),...mv(e,t,s)],vv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Lt(n).some(i=>Je(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Lt(n).find(o=>Je(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Ev=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),xv=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...hv(c,l,s)),i.push(...vv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!rr(a.getType()))&&n.push(Ev(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Sv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},Av=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},yv=(e,t)=>O(e,t,(s,n)=>Sv(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:Av(s)}:void 0),lr=e=>e==="@lunora/workflow",bv=e=>new Set(e.getImportDeclarations().filter(t=>lr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),Nv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),Pv=(e,t)=>{const s=qn(e,"defineWorkflowEvent",lr),n=bv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!Nv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?nt(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new R("WORKFLOW_EVENT_NOT_LITERAL",de(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:I(t,e.getFilePath()),type:l.getLiteralValue()})}return i},wv=(e,t)=>{const s=y(t).flatMap(i=>Pv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new R("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},Iv=e=>{const t=zo(e,"compatibility_date"),s=$o(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:Ko(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
|
|
29
|
-
`},Cv=e=>`// Generated by @lunora/codegen. Do not edit.
|
|
30
|
-
// Serves the advisor procedure list to the app's Worker, which forwards it to a hosted Studio after the admin check.
|
|
31
|
-
const PROCEDURES = ${JSON.stringify(e)};
|
|
32
|
-
|
|
33
|
-
const ADVISOR_PROCEDURES_PATH = "/__lunora/advisor-procedures";
|
|
34
|
-
|
|
35
|
-
export default {
|
|
36
|
-
fetch(request: Request): Response {
|
|
37
|
-
if (new URL(request.url).pathname !== ADVISOR_PROCEDURES_PATH) {
|
|
38
|
-
return Response.json({ error: "not found" }, { status: 404 });
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
if (request.method !== "GET") {
|
|
42
|
-
return Response.json({ error: "GET only" }, { status: 405 });
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
return new Response(PROCEDURES, { headers: { "Content-Type": "application/json" }, status: 200 });
|
|
46
|
-
},
|
|
47
|
-
};
|
|
48
|
-
`,Tv=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":Cv(t),"wrangler.jsonc":Iv(e)}:{},Ov=(e,t)=>{for(const s of new Set([Xo(t),si(e)])){const n=s===void 0?[]:yo(s);if(s!==void 0&&n.length>0)throw new R("PROJECT_CONFIG_INVALID",`${kr(s)} is invalid:
|
|
49
|
-
${n.map(i=>` - ${i}`).join(`
|
|
50
|
-
`)}`)}},kv=(e,t,s)=>{for(const n of s)t[n]===void 0&&pe(v(e,n),{force:!0});for(const n of[...new Set(s.map(i=>Ze(v(e,i))))].toSorted((i,o)=>o.length-i.length))_(n)&&Yt(n).length===0&&pe(n,{recursive:!0})},Rv=(e,t)=>{for(const s of Yt(e,{recursive:!0,withFileTypes:!0})){const n=v(s.parentPath,s.name);s.isFile()&&t[Qt(e,n)]===void 0&&pe(n)}},Oe=(e,t)=>{_(e)&&Xe(e,"utf8")===t||Or(e,t,"utf8")},Fv=(e,t)=>{if(t===""){pe(e,{force:!0});return}Oe(e,t)},Lv=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){pe(s,{force:!0,recursive:!0});return}if(_(s))for(const n of Yt(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Qt(e,i)]===void 0&&pe(i)}for(const[n,i]of Object.entries(t))Gt(Ze(v(e,n)),{recursive:!0}),Oe(v(e,n),i)},Dv=(e,t,s,n)=>{const i=v(e,t);if(n!==void 0)kv(i,s,n);else if(Object.keys(s).length===0){pe(i,{force:!0,recursive:!0});return}else _(i)&&Rv(i,s);for(const[o,a]of Object.entries(s)){const c=v(i,o);Gt(Ze(c),{recursive:!0}),Oe(c,a)}},_v=e=>{try{const t=ka(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},We=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Mv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,zv=(e,t)=>{_(e)||Gt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Oe(v(e,n.name),n.content),s.push(n.name);break}case"directory":{Dv(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{Lv(e,n.files),s.push(...Object.keys(n.files));break}default:Fv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},$v=e=>{const t=_v(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=La({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=_a({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
|
|
51
|
-
`,openApiModuleContent:Da(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
|
|
52
|
-
`,openRpcModuleContent:Ma(i)}},Kv=".lunora-schema.json",Bv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Vv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new R("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new R("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new R("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},Uv=8,Wv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:p,useUmbrella:m,workflows:x}=e,M=()=>Aa(()=>{const w=io(l,a,{lazyFunctions:o}),U=uo(l,a);return{functions:w,httpRoutes:ya(l,a),mutators:U}});let{erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=M();no(y(a).map(w=>l.getSourceFileOrThrow(w)),w=>Qt(a,w.getFilePath())),Pn([...P,...ee].map(w=>w.filePath)),Pn(V.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const U=u?P:P.filter(B=>B.channel?.kind!=="room"&&B.lifecycle!=="socket"),Q=qa({agents:t,functions:U,httpRoutes:V,mutators:ee,useUmbrella:m,workflows:x}),F={agents:t,functions:U,lazyFunctions:o,migrations:c,mutators:ee,shapes:f,useUmbrella:m,usesSandbox:p},z=tc(F),te=sc(F),se=ja({functions:P,useUmbrella:m}),re=v(a,"_generated",ri),oe=[[s,Q],[i,se],[n,z],...Object.entries(te).map(([B,k])=>[v(re,B),k])];if(w>=Uv||oe.every(([B,k])=>Mv(l,B,k)))return{apiContent:Q,erased:K,functions:P,functionModulesContent:te,functionsContent:z,httpRoutes:V,internalContent:se,mutators:ee};for(const[B,k]of oe)We(l,B,k);({erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=M())}},qv=e=>{const t=Bv(),s=t?yt.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora");Ov(e.projectRoot,n);const i=bo(n),o=e.lazyFunctions===!0||i,a=No(n),c=v(n,"schema.ts");if(!_(c))throw new R("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??Mo(n);to(nh);const u=wa(l,c,e.projectRoot);Hh(u.tables,Wh(l,n,ti(e.projectRoot)));const{agents:f,capabilities:p,containers:m,crons:x,dataModelContent:M,dependencies:K,entryCronTriggers:P,env:V,featureUsage:ee,hasFlags:w,hasNotify:U,identity:Q,platformGate:F,queues:z,serverContent:te,services:se,storageRulesMetadata:re,topics:oe,usesSandbox:B,useUmbrella:k,workflows:W}=$m({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});ah(u,u.jurisdiction===void 0?void 0:rh(l,n));const b=v(n,"_generated"),dr=v(b,"dataModel.ts"),ur=v(b,"server.ts"),fr=v(b,"api.ts"),pr=v(b,"internal.ts"),gr=v(b,"functions.ts");We(l,dr,M),We(l,ur,te);const vs=Object.fromEntries(se.filter(g=>g.rpcEntrypoint!==void 0).flatMap(g=>Object.entries(ga(g,b))));for(const[g,At]of Object.entries(vs))We(l,v(b,g),At);const ke=Na(l,n),ue=Ia(l,n),dt=F.signals.typedWebSockets!==!1,{apiContent:Es,erased:mr,functions:j,functionModulesContent:xs,functionsContent:Ss,httpRoutes:ut,internalContent:As,mutators:ft}=Wv({agents:f,apiPath:fr,generatedFunctionsPath:gr,internalPath:pr,lazyFunctions:o,roomsSupported:dt,lunoraDirectory:n,migrations:ke,project:l,shapes:ue,useUmbrella:k,usesSandbox:B,workflows:W}),ys=Io(l,n),pt=Co(ys,u,[...j,...ut].map(g=>g.filePath)),Re=ys.length>0,xe=e.lint===!1&&!Re?void 0:{callEdges:Xm(l,n),inserts:ba(l,n),queries:Us(l,n,j),tableWrites:sv(l,n),workflowCalls:yv(l,n)},hr=Ra(xe?.queries??Us(l,n,j)),Se=e.lint===!1||xe===void 0?void 0:$g(l,n,{callSites:xe,containers:m,crons:x,functions:j,modules:pt,mutators:ft,queues:z,schema:u,shapes:ue,workflows:W,wranglerVariables:e.wranglerVariables}),bs=Se===void 0?[]:jg(e.projectRoot,[...Rr(Se,{source:"static"}),...xv(l,n,{byName:new Set([...W,...z,...f,...m].map(g=>g.exportName)),byPath:new Set([...j,...ft,...ue,...ke].map(g=>`${g.filePath}:${g.exportName}`))}),...ov(l,n),...Sa(mr,n),...za(z,e.wranglerQueueProducers)]),vr=Pa(l,n),Ns=yh(l,n);Vv(ue,Ns,Sh(l,n));const Er=w?sh(l,n):[],gt=F.signals.vectorStore!==!1,xr=la(Me(e.projectRoot,e.target),"deliveryAuthorization"),Ae=Gh(ee,{containerCount:m.length,cronCount:x.length,dependencies:K,hasPaymentTables:Ph(u.tables),queueCount:z.length,storageColumnCount:Object.keys(ni(u)).length,storageRuleCount:re.rules.length,vectorIndexCount:u.vectorIndexes.length,target:Me(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:W.length}),Ps=t?yt.now():0,mt=Fa(u,ke.map(g=>g.id)),ht=vh(l,n),ws=fa({advisories:bs.filter(g=>g.name!=="procedure_type_check_unavailable"),agents:f,capabilities:p,containers:m,env:V,flagKeys:Er,hasFlags:w,hasNotify:U,hasIpReaders:j.some(g=>g.readsIp===!0)||ue.some(g=>g.readsIp===!0),hasRooms:dt&&j.some(g=>g.channel?.kind==="room"),hasSensitiveArgs:f.length>0||j.some(g=>_o(g)),hasSecretValues:F.signals.secretValues===!0,hasSockets:dt&&j.some(g=>g.lifecycle==="socket"),lazyFunctions:o,hasVectors:gt,liveStreamDeclarations:ht,liveStreams:F.signals.liveStreams===!0,maskMetadata:Ns,mutators:ft,queues:z,rlsMetadata:vr,schema:u,schemaSnapshot:mt,shapes:ue,services:se,storageRules:re,studioFeatures:Ae,topics:oe,useUmbrella:k,workflowEvents:wv(l,n),workflows:W}),Is=Ua(ue,K.has("@lunora/db"),k),Cs=$a(m,u.jurisdiction),Ts=Ka(W,{lazy:o}),Os=Ba(f,{lazy:o}),ks=Va(z,e.wranglerQueueProducers),Rs=nc(ht,k),Fs=Ha(x),Sr=Ga(Ae.scheduler),Fe=da(Me(e.projectRoot,e.target)),Ar=Fe.supported?Ya(k):"",yr=Qa(u.tables,k,u.jurisdiction),br=Po(e.projectRoot)?Ja(k):"",Ls=Xa(u.vectorIndexes),Le=ec(u,k),Ds=Wa(K.has("@lunora/seed")),De=e.apiSpec??"openapi",vt=De==="openapi"||De==="both",Nr=Se?.procedureProtections??[],Pr=Se===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...Nr]},Et=`${JSON.stringify(Pr,void 0,2)}
|
|
53
|
-
`,xt=De==="openrpc"||De==="both",_s=Ta(K.has("@lunora/auth")),Ms=Oa({agentWorkflows:f.map(g=>g.className),capabilities:p,emailAgents:f.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:K.has("@lunora/cloudflare-access"),hasAuth:K.has("@lunora/auth"),hasFramework:K.has("@lunora/astro")||K.has("@lunora/svelte")||K.has("@lunora/vue")||_(v(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(g=>Zn(g)),hasHyperdriveGlobal:u.tables.some(g=>ei(g)),hasKvIntrospector:Ae.kv,hasNotify:U,hasQueue:z.some(g=>g.mode==="push"),liveStreams:F.signals.liveStreams===!0,liveStreamsWithheld:F.liveStreamsWithheld,liveStreamDeclarations:ht,hasAdminRevocations:Fe.supported,hasScheduler:Ae.scheduler,hasSourcedTables:u.tables.some(g=>g.externalSource!==void 0),hasStorage:Ae.storage,hasDeliveryAuthorization:xr,hasVectors:gt,hasWorkflow:W.length>0,identity:Q,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(g=>({name:g.name,shardMode:g.shardMode})),securityHeaders:wo(n),spaAssetsBindings:e.spaAssetsBindings,useUmbrella:k,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:Re,wantsOpenApi:vt,wantsOpenRpc:xt}),{openApiContent:zs,openApiModuleContent:$s,openRpcContent:Ks,openRpcModuleContent:Bs}=$v({functions:j,httpRoutes:ut,modules:pt,projectRoot:e.projectRoot,wantsArchitecture:Re}),ye=Re&&xe!==void 0?am({...xe,crons:x,functions:j,httpRoutes:ut,modules:pt,queues:z,schema:u,services:se,topics:oe,workflows:W}):void 0,St=v(n,Kv),wr=_(St),Ir=e.dryRun?[]:zv(b,[{content:Ms,kind:"always",name:"app.ts"},{content:M,kind:"always",name:"dataModel.ts"},{content:Es,kind:"always",name:"api.ts"},{content:As,kind:"always",name:"internal.ts"},{content:te,kind:"always",name:"server.ts"},{content:Ss,kind:"always",name:"functions.ts"},{files:xs,kind:"directory",name:ri},{content:ws,kind:"always",name:"shard.ts"},{content:Fs,kind:"always",name:"crons.ts"},{content:Ls,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:Cs,kind:"optional",name:"containers.ts"},{content:Ts,kind:"optional",name:"workflows.ts"},{content:Os,kind:"optional",name:"agents.ts"},{content:ks,kind:"optional",name:"queues.ts"},{content:Rs,kind:"optional",name:"live.ts"},{content:Sr,kind:"optional",name:"scheduler.ts"},{content:yr,kind:"optional",name:"shardRegistry.ts"},{content:Ar,kind:"optional",name:"adminRevocations.ts"},{content:br,kind:"optional",name:"durableObjects.ts"},{content:Ds,kind:"optional",name:"seed.ts"},{content:_s,kind:"optional",name:"authModule.ts"},{content:Is,kind:"optional",name:"collections.ts"},{files:vs,kind:"services"},{files:Tv(e.projectRoot,Et,a),kind:"directory",name:"companion",owned:Bo},{content:vt?zs:"",kind:"optional",name:"openapi.json"},{content:vt?$s:"",kind:"optional",name:"openapi.ts"},{content:xt?Ks:"",kind:"optional",name:"openrpc.json"},{content:xt?Bs:"",kind:"optional",name:"openrpc.ts"},{content:Et,kind:"optional",name:"advisor-procedures.json"},{content:ye===void 0?"":`${JSON.stringify(ye,void 0,2)}
|
|
54
|
-
`,kind:"optional",name:"architecture.json"},{content:ye===void 0?"":cm(ye),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!wr&&Oe(St,Fr(mt)),t){const g=yt.now(),At=Math.round(g-s),Cr=Math.round(Ps-s),Tr=Math.round(g-Ps);console.error(`@lunora/codegen: codegen took ${At.toString()}ms (discovery ${Cr.toString()}ms, emit ${Tr.toString()}ms)`)}return{advisories:bs,advisorContext:Se,agents:f,architecture:ye,containers:m,cronTriggers:[...new Set([...Za(x),...P])],generated:{advisorProceduresJson:Et,agents:Os,api:Es,app:Ms,authModule:_s,collections:Is,containers:Cs,crons:Fs,dataModel:M,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:xs,functions:Ss,internal:As,live:Rs,openApi:zs,openApiModule:$s,openRpc:Ks,openRpcModule:Bs,queues:ks,seed:Ds,server:te,shard:ws,vectors:Ls,workflows:Ts},migrations:ke,outputDirectory:b,platformDiagnostics:Fe.diagnostic===void 0?F.diagnostics:[...F.diagnostics,Fe.diagnostic],queues:z,indexReferences:hr,schemaSnapshot:mt,schemaSnapshotPath:St,schemaTables:u.tables,workflows:W,writtenFiles:Ir}},dx=e=>Br(()=>qv(e));export{Kv as SCHEMA_SNAPSHOT_FILENAME,Mo as createCodegenProject,px as findTsconfig,gx as refreshCodegenProject,dx as runCodegen,mx as tsconfigFingerprint};
|