@lunora/codegen 1.0.0-alpha.171 → 1.0.0-alpha.173

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -383,13 +383,17 @@ interface TableIR {
383
383
  * `tenantBy`) are not serialized, only their presence (`hasTenantBy`).
384
384
  */
385
385
  externalSource?: ExternalSourceIR;
386
+ /** Geospatial indexes declared inline via `.geoIndex(name, …)`. Optional so hand-built IR may omit it (discovery always sets it). */
387
+ geoIndexes?: ReadonlyArray<GeoIndexIR>;
386
388
  /**
387
389
  * Storage backend for a `.global()` table: `"d1"` (default) or
388
390
  * `"hyperdrive"` (a Postgres/MySQL database via Cloudflare Hyperdrive). Only
389
391
  * meaningful when `shardMode === "global"`; absent for sharded/root tables.
392
+ *
393
+ * Read it through `isD1GlobalTable` / `isHyperdriveGlobalTable` rather than
394
+ * comparing here — discovery normalises the absent case to `"d1"`, and only
395
+ * those predicates encode which comparison is right for hand-built IR.
390
396
  */
391
- /** Geospatial indexes declared inline via `.geoIndex(name, …)`. Optional so hand-built IR may omit it (discovery always sets it). */
392
- geoIndexes?: ReadonlyArray<GeoIndexIR>;
393
397
  globalBackend?: "d1" | "hyperdrive";
394
398
  indexes: ReadonlyArray<IndexIR>;
395
399
  /**
@@ -3392,6 +3396,10 @@ interface EmitAppOptions {
3392
3396
  * `@lunora/storage`, …) directly.
3393
3397
  */
3394
3398
  declare const emitApp: (rawOptions: EmitAppOptions) => string;
3399
+ /** A `.global()` table backed by D1 — the default when no `backend` is named. */
3400
+ declare const isD1GlobalTable: (table: TableIR) => boolean;
3401
+ /** A `.global({ backend: "hyperdrive" })` table — Postgres/MySQL via Cloudflare Hyperdrive. */
3402
+ declare const isHyperdriveGlobalTable: (table: TableIR) => boolean;
3395
3403
  /** Inputs the OpenAPI emitter needs from a codegen run. */
3396
3404
  interface OpenApiEmitInput {
3397
3405
  functions: ReadonlyArray<FunctionIR>;
@@ -3871,4 +3879,4 @@ declare const secretKindOf: (value: string) => string | undefined;
3871
3879
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
3872
3880
  declare const redact: (value: string) => string;
3873
3881
  declare const VERSION = "0.0.0";
3874
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftRemediation, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, listLunoraSourceFiles, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3882
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftRemediation, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isD1GlobalTable, isHyperdriveGlobalTable, isTypedSchema, lintSchema, listLunoraSourceFiles, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -383,13 +383,17 @@ interface TableIR {
383
383
  * `tenantBy`) are not serialized, only their presence (`hasTenantBy`).
384
384
  */
385
385
  externalSource?: ExternalSourceIR;
386
+ /** Geospatial indexes declared inline via `.geoIndex(name, …)`. Optional so hand-built IR may omit it (discovery always sets it). */
387
+ geoIndexes?: ReadonlyArray<GeoIndexIR>;
386
388
  /**
387
389
  * Storage backend for a `.global()` table: `"d1"` (default) or
388
390
  * `"hyperdrive"` (a Postgres/MySQL database via Cloudflare Hyperdrive). Only
389
391
  * meaningful when `shardMode === "global"`; absent for sharded/root tables.
392
+ *
393
+ * Read it through `isD1GlobalTable` / `isHyperdriveGlobalTable` rather than
394
+ * comparing here — discovery normalises the absent case to `"d1"`, and only
395
+ * those predicates encode which comparison is right for hand-built IR.
390
396
  */
391
- /** Geospatial indexes declared inline via `.geoIndex(name, …)`. Optional so hand-built IR may omit it (discovery always sets it). */
392
- geoIndexes?: ReadonlyArray<GeoIndexIR>;
393
397
  globalBackend?: "d1" | "hyperdrive";
394
398
  indexes: ReadonlyArray<IndexIR>;
395
399
  /**
@@ -3392,6 +3396,10 @@ interface EmitAppOptions {
3392
3396
  * `@lunora/storage`, …) directly.
3393
3397
  */
3394
3398
  declare const emitApp: (rawOptions: EmitAppOptions) => string;
3399
+ /** A `.global()` table backed by D1 — the default when no `backend` is named. */
3400
+ declare const isD1GlobalTable: (table: TableIR) => boolean;
3401
+ /** A `.global({ backend: "hyperdrive" })` table — Postgres/MySQL via Cloudflare Hyperdrive. */
3402
+ declare const isHyperdriveGlobalTable: (table: TableIR) => boolean;
3395
3403
  /** Inputs the OpenAPI emitter needs from a codegen run. */
3396
3404
  interface OpenApiEmitInput {
3397
3405
  functions: ReadonlyArray<FunctionIR>;
@@ -3871,4 +3879,4 @@ declare const secretKindOf: (value: string) => string | undefined;
3871
3879
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
3872
3880
  declare const redact: (value: string) => string;
3873
3881
  declare const VERSION = "0.0.0";
3874
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftRemediation, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, listLunoraSourceFiles, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3882
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftRemediation, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isD1GlobalTable, isHyperdriveGlobalTable, isTypedSchema, lintSchema, listLunoraSourceFiles, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as h}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as L}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as I,discoverFlags as F}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as P}from"./packem_shared/discoverFunctions-DB9G_XrW.mjs";import{default as G}from"./packem_shared/discoverHttpRoutes-S81Iv_iB.mjs";import{default as b}from"./packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs";import{default as y}from"./packem_shared/discoverInserts-COk-Sm_n.mjs";import{d as j}from"./packem_shared/index-D_Z8rX-f.mjs";import{default as V}from"./packem_shared/discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CTHlZ1j6.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-DkVVHe3U.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-CZh4jN4q.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-CPlxXagL.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-vJZq3yhb.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CwWRPb8N.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-DskdDbkM.mjs";import{default as xe}from"./packem_shared/discoverSchema-DoZtXwLg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-xhxu-mkS.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-BaSbufF2.mjs";import{G as Me,e as he,a as _e,b as Le,c as Te,d as Ie,f as Fe,g as De,h as Pe,i as Ue,j as Ge,k as He,l as be,m as ke}from"./packem_shared/emit-Lx7UkoGn.mjs";import{emitApp as We}from"./packem_shared/emitApp-Dt3j2KVX.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-CE9SDrBg.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as qe,emitOpenRpc as Be,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-DlF2XS7T.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-lPq34YeN.mjs";import{SCHEMA_SNAPSHOT_FILENAME as or,createCodegenProject as tr,findTsconfig as sr,refreshCodegenProject as ar,runCodegen as ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Dd78fHt4.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as fr,evaluateSchemaDrift as pr,parseSchemaSnapshot as cr}from"./packem_shared/SchemaSnapshotParseError-yrVM8bTa.mjs";import{schemaFromIr as lr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as xr,validatorIrToJsonSchema as Er}from"./packem_shared/LUNORA_ERROR_CODES-CW7-uASH.mjs";import{SDK_LANGUAGES as ur,SDK_TARGETS as vr,generateSdk as Nr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Or,secretKindOf as Rr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Mr,findSolutionByMessage as hr}from"@lunora/errors";import{isTypedSchema as Lr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,Xe as DEFAULT_TARGET,I as FLAGS_FILENAME,Me as GENERATED_HEADER,xr as LUNORA_ERROR_CODES,Mr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,we as OPENRPC_VERSION,se as QUEUES_FILENAME,or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ur as SDK_LANGUAGES,vr as SDK_TARGETS,Ae as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,qe as buildOpenRpcDocument,fr as buildSchemaSnapshot,tr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,R as discoverAuthApiCalls,h as discoverContainers,L as discoverCrons,F as discoverFlags,P as discoverFunctions,G as discoverHttpRoutes,b as discoverHyperdriveCalls,y as discoverInserts,j as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Re as discoverWorkflows,he as emitAgents,_e as emitApi,We as emitApp,Le as emitCollections,Te as emitContainers,Ie as emitCrons,Fe as emitDataModel,De as emitDrizzleSchema,Pe as emitFunctions,Ve as emitOpenApi,ze as emitOpenApiModule,Be as emitOpenRpc,Je as emitOpenRpcModule,Ue as emitServer,Ge as emitShard,He as emitVectors,be as emitWorkflows,ke as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,pr as evaluateSchemaDrift,hr as findLunoraSolution,sr as findTsconfig,m as formatAdvisories,Nr as generateSdk,Lr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,cr as parseSchemaSnapshot,Ze as platformMatrixIds,ee as readPackageDependencies,$e as readProjectTarget,Or as redact,ar as refreshCodegenProject,er as resolveCodegenTarget,ir as runCodegen,lr as schemaFromIr,Rr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Er as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as _}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as I,discoverFlags as F}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as P}from"./packem_shared/discoverFunctions-DB9G_XrW.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-S81Iv_iB.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs";import{default as k}from"./packem_shared/discoverInserts-COk-Sm_n.mjs";import{d as j}from"./packem_shared/index-D_Z8rX-f.mjs";import{default as V}from"./packem_shared/discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CTHlZ1j6.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-DkVVHe3U.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-CZh4jN4q.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-CPlxXagL.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-vJZq3yhb.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CwWRPb8N.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-DskdDbkM.mjs";import{default as xe}from"./packem_shared/discoverSchema-DoZtXwLg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-xhxu-mkS.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-BaSbufF2.mjs";import{G as Me,e as Te,a as he,b as _e,c as Le,d as Ie,f as Fe,g as De,h as Pe,i as Ge,j as Ue,k as be,l as He,m as ye}from"./packem_shared/emit-B2PLgxM0.mjs";import{emitApp as We}from"./packem_shared/emitApp-DN-9pbIM.mjs";import{isD1GlobalTable as Ke,isHyperdriveGlobalTable as Ve}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Qe,emitOpenApi as we,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-BlImTugs.mjs";import{OPENRPC_VERSION as Je,buildOpenRpcDocument as Ye,emitOpenRpc as Xe,emitOpenRpcModule as Ze}from"./packem_shared/OPENRPC_VERSION-B-7SyEfS.mjs";import{DEFAULT_TARGET as er,platformMatrixIds as rr,readProjectTarget as or,resolveCodegenTarget as tr}from"./packem_shared/DEFAULT_TARGET-lPq34YeN.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ar,createCodegenProject as ir,findTsconfig as mr,refreshCodegenProject as dr,runCodegen as fr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CjzGxonx.mjs";import{SchemaSnapshotParseError as cr,buildSchemaSnapshot as nr,evaluateSchemaDrift as lr,parseSchemaSnapshot as Sr}from"./packem_shared/SchemaSnapshotParseError-yrVM8bTa.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as ur,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-CW7-uASH.mjs";import{SDK_LANGUAGES as gr,SDK_TARGETS as Or,generateSdk as Rr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Mr,secretKindOf as Tr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as _r,findSolutionByMessage as Lr}from"@lunora/errors";import{isTypedSchema as Fr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,er as DEFAULT_TARGET,I as FLAGS_FILENAME,Me as GENERATED_HEADER,ur as LUNORA_ERROR_CODES,_r as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Je as OPENRPC_VERSION,se as QUEUES_FILENAME,ar as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,gr as SDK_LANGUAGES,Or as SDK_TARGETS,Ae as SHAPES_FILENAME,cr as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Qe as buildOpenApiDocument,Ye as buildOpenRpcDocument,nr as buildSchemaSnapshot,ir as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,R as discoverAuthApiCalls,T as discoverContainers,_ as discoverCrons,F as discoverFlags,P as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,k as discoverInserts,j as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Re as discoverWorkflows,Te as emitAgents,he as emitApi,We as emitApp,_e as emitCollections,Le as emitContainers,Ie as emitCrons,Fe as emitDataModel,De as emitDrizzleSchema,Pe as emitFunctions,we as emitOpenApi,qe as emitOpenApiModule,Xe as emitOpenRpc,Ze as emitOpenRpcModule,Ge as emitServer,Ue as emitShard,be as emitVectors,He as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,lr as evaluateSchemaDrift,Lr as findLunoraSolution,mr as findTsconfig,m as formatAdvisories,Rr as generateSdk,Ke as isD1GlobalTable,Ve as isHyperdriveGlobalTable,Fr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,Sr as parseSchemaSnapshot,rr as platformMatrixIds,ee as readPackageDependencies,or as readProjectTarget,Mr as redact,dr as refreshCodegenProject,tr as resolveCodegenTarget,fr as runCodegen,Er as schemaFromIr,Tr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,vr as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{G as m,U as r,n as o,e as n,a as l,b as A,c as E,d as S,f as g,g as p,h as C,o as c,p as d,i as u,j as D,k as f,l as h,m as G}from"./emit-B2PLgxM0.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./paths-C-9fwEgQ.mjs";export{m as GENERATED_HEADER,r as UMBRELLA_BASE_PACKAGES,o as buildStorageColumns,n as emitAgents,l as emitApi,A as emitCollections,E as emitContainers,S as emitCrons,g as emitDataModel,p as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,u as emitServer,D as emitShard,f as emitVectors,h as emitWorkflows,G as emitWranglerCronTriggers};
@@ -1,3 +1,3 @@
1
- import{G as c}from"./emit-Lx7UkoGn.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-CW7-uASH.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
1
+ import{G as c}from"./emit-B2PLgxM0.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-CW7-uASH.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
2
2
  `,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
@@ -0,0 +1,9 @@
1
+ import{existsSync as b,mkdirSync as Es,readFileSync as Dt,writeFileSync as Ss,rmSync as ys}from"node:fs";import{join as f,dirname as ee}from"node:path";import{performance as Ee}from"node:perf_hooks";import{runAdvisor as As}from"@lunora/advisor";import{LunoraError as D}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as at}from"ts-morph";import{serializeSchemaSnapshot as Ns}from"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{toAdvisorContext as bs}from"./formatAdvisories-CkEu1eye.mjs";import{s as Ps}from"./paths-C-9fwEgQ.mjs";import{C as te,n as kt,i as Is,f as ws,j as Ts,b as Cs,c as Fs,l as Os,e as Rs,o as Ls,d as Ds,k as ks,g as Ms,p as Ks,m as _s,a as zs,h as $s}from"./emit-B2PLgxM0.mjs";import{isD1GlobalTable as Mt,isHyperdriveGlobalTable as Kt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Us}from"./AGENTS_FILENAME-B78F7DuQ.mjs";import{discoverContainers as qs}from"./CONTAINERS_FILENAME-CQoUu7n7.mjs";import Bs from"./discoverCrons-CMu0sA8k.mjs";import{diagnosticAt as ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as le}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as h,unwrapExpression as j,listSecurityScanFiles as Te,objectLiteralFromCallbackBody as _t,propertyInitializer as N,lunoraRelativePath as E,collectCallRows as I,collectSecurityCallRows as Vs,limitNameOf as zt,isContextIdentifier as Ne,handlerOf as Ws,isDatabaseAccessor as k,readTargetOf as $t,enclosingExportName as js}from"./listLunoraSourceFiles-D4xthUf-.mjs";import Hs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as Gs}from"./QUEUES_FILENAME-Q3CF3uYr.mjs";import{discoverSandboxUsage as Ys}from"./discoverSandboxUsage-DskdDbkM.mjs";import Qs from"./discoverStorageRulesMetadata-xhxu-mkS.mjs";import{a as y,c as M,d as Ut,e as Xs}from"./classify-procedure-call-C8jbo0IJ.mjs";import{discoverWorkflows as Zs}from"./WORKFLOWS_FILENAME-BaSbufF2.mjs";import{gatePlatformFeatures as Js,resolveCodegenTarget as en}from"./DEFAULT_TARGET-lPq34YeN.mjs";import{i as L,a as z,e as S,r as tn,b as sn,s as ue,c as nn,f as rn,d as on}from"./queries-CPlxXagL.mjs";import{r as de,s as an}from"./parse-validator-tdRHHDzh.mjs";import cn from"./discoverAuthApiCalls-DoblmzUW.mjs";import ct from"./discoverFunctions-DB9G_XrW.mjs";import{i as ln,r as un,e as dn}from"./unwrap-handler-return-CmIWbykC.mjs";import lt from"./discoverHttpRoutes-S81Iv_iB.mjs";import fn from"./discoverHyperdriveCalls-DgAYcZRD.mjs";import gn from"./discoverInserts-COk-Sm_n.mjs";import{m as Ce,a as ne,s as qt,d as pn}from"./index-D_Z8rX-f.mjs";import{e as Bt}from"./exported-procedure-chains-C9FHwphy.mjs";import mn from"./discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as hn,isDefineMutatorCallee as xn,discoverMutators as ut}from"./MUTATORS_FILENAME-CTHlZ1j6.mjs";import vn from"./discoverNondeterministicCalls-DkVVHe3U.mjs";import{discoverNotifyConfig as En,discoverNotifyCalls as Sn}from"./NOTIFY_FILENAME-CZh4jN4q.mjs";import yn from"./discoverR2sqlCalls-6u0OKy2N.mjs";import An from"./discoverRlsProcedures-vJZq3yhb.mjs";import Nn from"./discoverRlsMetadata-CwWRPb8N.mjs";import bn from"./discoverSchema-DoZtXwLg.mjs";import{secretKindOf as Pn,redact as In,isHeuristicSecretKind as wn,isSecretishName as Tn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Cn}from"./SHAPES_FILENAME-Bvd5kgsF.mjs";import{emitApp as Fn}from"./emitApp-DN-9pbIM.mjs";import{buildOpenApiDocument as On,emitOpenApiModule as Rn}from"./buildOpenApiDocument-BlImTugs.mjs";import{buildOpenRpcDocument as Ln,emitOpenRpcModule as Dn}from"./OPENRPC_VERSION-B-7SyEfS.mjs";import{buildSchemaSnapshot as kn}from"./SchemaSnapshotParseError-yrVM8bTa.mjs";const dt=(e,t="api")=>{const s=new Map;for(const n of e){const o=Ps(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new D("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Mn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>Mt(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=>Kt(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`"}),o&&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 r===void 0?[]:te)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Kn=(e,t,s={})=>{if(t===void 0)return;const n=Mn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
2
+ `);throw new D("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
+ ${o}
4
+
5
+ Install them with your package manager, then re-run codegen.`)},_n="env.ts",zn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return le(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},$n=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&le(n.getModuleSpecifierValue())}return!1},Un=e=>{if(i.isIdentifier(e))return zn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&$n(t)}return!1},qn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Un(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ce(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Bn=(e,t)=>{const s=f(t,_n);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=qn(n);if(o.length!==0){if(o.length>1)throw ce(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},ft="ctx",Vt=e=>{const t=new Set,s=new Set([ft]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==ft)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},Vn=(e,t)=>{const s=Object.fromEntries(te.map(n=>[n.key,!1]));for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Vt(o);for(const c of te)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(te.every(c=>s[c.key]))break}return s},Wt="identity.ts",Wn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return le(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},jn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&le(n.getModuleSpecifierValue())}return!1},Hn=e=>{if(i.isIdentifier(e))return Wn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&jn(t)}return!1},Gn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Hn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ce(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Yn=(e,t)=>{const s=f(t,Wt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=Gn(n);if(o.length!==0){if(o.length>1)throw ce(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},Qn=(e,t)=>{const s=j(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return j(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},Xn=e=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!i.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||j(s)?.getText()!=="false"}),Zn=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Vt(o).has("secrets")),s.durableStreams||(s.durableStreams=o.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(i.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>Xn(Qn(o,u)))})),s.durableStreams&&s.secrets)break}return s},Jn="createWorker",er="extend",gt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,pt=e=>{const t=[],s=gt(N(e,"backupCron"));s!==void 0&&t.push(s);const n=N(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=gt(o.getNameNode());r!==void 0&&t.push(r)}return t},tr=e=>{const t=y(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Jn)return i.isObjectLiteralExpression(s)?pt(s):[];if(t!==er||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=_t(s.getBody());return n===void 0?[]:pt(n)},sr=(e,t)=>{const s=[];for(const{filePath:n}of Te(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...tr(r))}return[...new Set(s)]},nr=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new D("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new D("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(r.className);if(u!==void 0)throw new D("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},rr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=Yn(s,t),a=Bn(s,t),c=Zs(s,t),u=Gs(s,t),d=Us(s,t);nr(c,d);const v=qs(s,t),x=Qs(s,t),P=Bs(s,t,c,d),K=sr(s,t),g=Zn(s,t),T=Ys(s,t),F=Vn(s,t);F.browser=F.browser||T.usesSandboxBrowser;const B=Js(F,en(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(p=>p.commitOrdered===!0),cronTriggers:P.length>0,crossShardFanout:o.tables.some(p=>typeof p.shardMode=="object"),durableStreams:g.durableStreams,globalTables:o.tables.some(p=>p.shardMode==="global"),queues:u.length>0,secrets:g.secrets,vectorStore:o.vectorIndexes.length>0}),A=B.usage,O=B.signals.vectorStore!==!1,$=Hs(n),V=$??new Set,G=V.has("lunorash");Kn(o,$,{hasVectors:O,scheduler:A.scheduler||P.length>0,storage:A.storage||x.rules.length>0||Object.keys(kt(o)).length>0,usage:A});const _=b(f(t,"flags.ts")),C=b(f(t,"notify.ts"));return{agents:d,containers:v,crons:P,dataModelContent:ws(o),declaredDependencies:$,dependencies:V,entryCronTriggers:K,env:a,featureUsage:A,hasFlags:_,hasNotify:C,identity:r,platformGate:B,queues:u,serverContent:Is({agents:d,containers:v,env:a,hasAccessFacade:A.access,hasAi:A.ai,hasAnalytics:A.analytics,hasBrowser:A.browser,hasVectors:O,hasFlags:_,hasHyperdrive:A.hyperdrive,hasImages:A.images,hasKv:A.kv,hasNotify:C,hasPayments:A.payments,hasPipelines:A.pipelines,hasR2sql:A.r2sql,hasX402:A.x402,identity:r,queues:u,schema:o,storageRuleBuckets:x.rules.map(p=>p.bucket),useUmbrella:G,workflows:c}),storageRulesMetadata:x,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer||T.usesSandboxFs,useUmbrella:G,workflows:c}},jt=new Set(["delete","get","head","options","patch","post","put"]),or=new Set(["handler","stream"]),ir=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,mt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),ar=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!jt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},cr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||jt.has(n.getName()))break;s=n.getExpression()}return ar(s)},lr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(mt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&mt.has(s.getText()))return!0}return!1},ur=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!or.has(n.getName()))return;const o=cr(s);if(!o||!ir.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&lr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},dr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=ur(o,t);r&&s.push(r)}return s},fr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...dr(o,E(t,n)))}return s},gr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",pr=(e,t)=>{if(!gr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)||z(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},mr=(e,t)=>I(e,t,pr),hr=new Set(["generateText","streamText"]),xr=new Set(["messages","prompt","system"]),vr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Er=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of vr)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Sr=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Er(t);if(s!==void 0)return s}},yr=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Ar=e=>{if(tn(e))return!0;const t=yr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Nr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!xr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Ar(s))return!0}return!1},br=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());if(o===void 0||!hr.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=Sr(c),a!==void 0))break;a!==void 0&&s.push({exportName:S(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Nr(r)})}return s},Pr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...br(o,E(t,n)))}return s},Ir=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},wr=(e,t)=>{if(!Ir(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Tr=(e,t)=>I(e,t,wr),Fe=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=de(s.getExpression());return n===void 0||Fe(n,t)})}finally{t.delete(e)}},Cr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:de(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:Fe(o)}},Fr=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?de(r):void 0;a===void 0?s=!0:(t.push(a),s||=Fe(a))}n=o.getExpression()}return{objects:t,opaque:s}},Oe=(e,t)=>t?Fr(t):Cr(e),Ht=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=de(s.getExpression());return n===void 0?[]:Ht(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},Or=e=>e.flatMap(t=>Ht(t,new Set)),Rr=new Set(["check","length","max"]),be=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Lr=e=>[e,...e.getDescendants()].filter(t=>be(t)!==void 0),Dr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(Rr.has(s.getName()))return!0;t=n}},kr=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=Lr(r),c=o.getName();a.some(u=>be(u)==="any")?t.push(c):a.some(u=>be(u)==="string"&&!Dr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Mr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=M(s);if(n?.visibility!=="public")return;const{objects:o}=Oe(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=kr(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Kr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Mr(o,t);r&&s.push(r)}return s},_r=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Kr(o,E(t,n)))}return s},Se=e=>e?.getKind()===l.TrueKeyword,zr=e=>e?.getKind()===l.FalseKeyword,$r=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Ur=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),qr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&y(t.getExpression())==="scim"),Br=e=>e!==void 0&&i.isCallExpression(e)&&Ur.has(y(e.getExpression())??""),Vr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Wr=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:Se(N(t,"disableCSRFCheck")),emailPasswordEnabled:Se(N(s,"enabled")),requireEmailVerification:Se(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:qr(N(e,"plugins"))&&Br(N(e,"database")),secureCookiesDisabled:zr(N(t,"useSecureCookies")),sessionFreshAgeZero:$r(N(n,"freshAge")),trustedOriginsWildcard:Vr(N(e,"trustedOrigins"))}},jr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Hr=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?Wr(s):jr();return{exportName:S(e),file:t,line:e.getStartLineNumber(),...o}},Gr=(e,t)=>Vs(e,t,Hr),Yr=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Qr=(e,t,s)=>{const n=Yr(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!L(o)||z(o))&&!(s.requireUnmodifiedReach===!0&&!sn(o)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:n}},Xr=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=Qr(o,t,s);r&&n.push(r)}return n},fe=(e,t,s)=>{const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Xr(r,E(t,o),s))}return n},Zr=new Set(["content","pdf","scrape","screenshot"]),Jr=(e,t)=>fe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Zr}),eo=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),to=new Set(["RateLimiter"]),so=new Set(["extend"]),ht="lunora",no=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Gt=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Pe=e=>e&&i.isObjectLiteralExpression(e)?Gt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},ro=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&_t(t.getBody());return s?Gt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},oo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());o!==void 0&&(eo.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Pe(n.getArguments()[0])}):so.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...ro(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=y(n.getExpression());o===void 0||!to.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Pe(n.getArguments()[0])})}return s},io=(e,t)=>{for(const s of no){const n=f(t,s);if(!b(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===ht&&r.push({callee:ht,file:s,line:a.getStartLineNumber(),...Pe(a.getArguments()[0])});return r}return[]},ao=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Te(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...oo(r,n))}return s.push(...io(e,ee(t))),s},xt="ctx.containers.",co=e=>{if(!e.startsWith(xt))return!1;const t=e.slice(xt.length);return t.length>0&&!t.includes(".")},lo=(e,t)=>fe(e,t,{argIndex:0,matchReceiver:co,methods:new Set(["get"])}),uo=new Set(["allow","deny","setAllowed"]),fo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},go=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!fo(e)))return{detail:"enableInternet: true",exportName:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},po=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!uo.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},mo=(e,t)=>go(e,t)??po(e,t),ho=(e,t)=>I(e,t,mo),xo=new Set(["defineExportSink","r2Sink","webhookExportSink"]),vo=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return xo.has(s)?s:void 0},Eo=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},So=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Te(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=vo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?Eo(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},yo=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ao=new Set(["dbRateLimit","rateLimit"]),No=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},bo=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=yo.get(s);if(n!==void 0)return{callee:s,exportName:S(e),failOpen:No(e.getArguments()[n]),file:t,limitName:Ao.has(s)?zt(e):"",line:e.getStartLineNumber()}},Po=(e,t)=>I(e,t,bo),Io=new Set(["boolean","number","object","string"]),wo=e=>{const t=e.getName();if(!Io.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ne(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ne(n.getExpression()))return t},To=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=wo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},Co=(e,t)=>{const s=new Map;for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=To(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},Fo=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=M(t);if(s?.kind!=="query")return;const n=Ws(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},vt=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Oo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=vt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=vt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},Ro=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=Oo(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},Lo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Fo(o);r&&s.push(...Ro(r,t))}return s},Do=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Lo(o,E(t,n)))}return s},ko=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ne(t.getExpression())},Mo=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Ko=(e,t)=>{if(!ko(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=Mo(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:S(e),file:t,key:o,line:e.getStartLineNumber()}},_o=(e,t)=>I(e,t,Ko),zo=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 o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||ln(r))return;const a=e.getSourceFile().getFilePath();return un(o,e,a)?dn(o,e,a,0,new Set):r},$o=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Uo=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},qo=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))$o(a)&&s.push({file:r,indexName:Uo(a),line:a.getStartLineNumber()})}return s},H=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Yt=e=>{const t=e.getArguments()[0],s=H(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&i.isPropertyAssignment(n)?H(n.getInitializer()):void 0},Bo=new Set(["delete","get","head","options","patch","post","put"]),Vo=new Set(["handler","stream"]),Wo=new Set(["runAction","runMutation"]),jo=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),re=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Et=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return i.isIdentifier(n)?n.getText():void 0;if(i.isObjectBindingPattern(n)){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="ctx"){const a=o.getNameNode();return i.isIdentifier(a)?a.getText():void 0}}},St=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(Wo.has(a)&&re(c,t))return a;if(jo.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&re(c.getExpression(),t))return`db.${a}`}},yt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&re(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!re(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},Ho=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Vo.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(Bo.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},Go=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=H(e.getArguments()[0]),u=c&&Et(c,!0);if(!c||u===void 0)return;const d=St(c,u);return d===void 0?void 0:{exportName:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:yt(c,u),sideEffect:d}}const n=Ho(e);if(n===void 0)return;const o=H(e.getArguments()[0]),r=o&&Et(o,!1);if(!o||r===void 0)return;const a=St(o,r);return a===void 0?void 0:{exportName:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:yt(o,r),sideEffect:a}},Yo=(e,t)=>I(e,t,Go),Qo=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Xo=new Set(["append","set"]),Qt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",At=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Qo.has(y(n.getExpression())??"")&&rn(n,t)),Zo=(e,t)=>{if(At(e,t))return!0;const s=ue(e);return s!==void 0&&At(s,t)},Ie=(e,t)=>nn(e,t)&&!Zo(e,t),Jo=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ue(e);return t!==void 0&&i.isNewExpression(t)&&y(t.getExpression())==="Headers"},oe=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=ue(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Re=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Ie(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Qt(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Ie(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=oe(n.getExpression());o!==void 0&&Re(o,t,s)}},Xt=(e,t)=>{const s=oe(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=oe(n.getInitializer());o!==void 0&&Re(o,"response-init",t)},ei=(e,t)=>{const s=y(e.getExpression());if(s==="Response")Xt(e.getArguments()[1],t);else if(s==="Headers"){const n=oe(e.getArguments()[0]);n!==void 0&&Re(n,"headers-ctor",t)}},ti=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){Xt(e.getArguments()[1],t);return}if(Xo.has(n)&&Jo(o)){const r=e.getArguments()[1];r!==void 0&&Ie(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Qt(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},si=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))ei(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))ti(s,t)},ni=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=H(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return si(n,{exportName:S(e),relativePath:t,requestName:r.getText(),rows:a}),a},ri=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...ni(n,t));return s},oi=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ri(o,E(t,n)))}return s},ii=new Set(["auth","context.auth","ctx.auth"]),ai="userId",ci=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},li=(e,t)=>{const s=f(t,Wt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(y(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?ci(r):void 0}},Nt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return ii.has(e.getExpression().getText())?e:void 0},ui=e=>{if(i.isPropertyAccessExpression(e)&&Nt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Nt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},di=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=ui(o);r!==void 0&&n.push({declared:r===ai||s.has(r),exportName:S(o),file:t,key:r,line:o.getStartLineNumber()})}return n},fi=(e,t)=>{const s=li(e,t);if(s===void 0)return[];const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...di(r,E(t,o),s))}return n},gi=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!L(n)||z(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},pi=(e,t)=>I(e,t,gi),mi=new Set(["delete","get","getRaw","getWithMetadata","put"]),hi=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return fe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:mi}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},xi=new Set(["queue","send"]),bt=new Set(["bcc","cc","to"]),vi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!xi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Ei=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return bt.has(t.getName())&&L(n)&&!z(n)}if(!i.isPropertyAssignment(t)||!bt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&L(s)&&!z(s)}):!1,Si=(e,t)=>{const s=vi(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Ei(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},yi=(e,t)=>I(e,t,Si),Ai=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,Ni=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Ai(e):!0,Zt=(e,t=!1)=>{for(const s of e.getProperties()){if(Ni(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||Zt(n,!0))return!0}return!1},bi=(e,t)=>{for(const s of h(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Bt(n))for(const r of Ce(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||Zt(a)))return!0}}return!1},Pi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=ne(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=ne(a);c!==void 0&&s.push({column:c,strategy:qt(a),table:o})}}return s},Ii=(e,t)=>{const s=new Map;for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Bt(o))for(const a of Ce(r))for(const c of Pi(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},wi=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=ne(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=ne(u);if(d===void 0)continue;const v=qt(u);v!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:v,table:a})}}return o},Ti=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?M(s):void 0;return n?.receiver?Ce(n.receiver).flatMap(o=>wi(o,e.getName(),t)):[]},Ci=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ti(c,r))}return s},Fi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return k(s)},Oi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},Ri=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return xn(s.getExpression())?s:void 0},Li=e=>{const t=Ri(e),s=t===void 0?void 0:Oi(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Fi(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Di=e=>e.getVariableDeclarations().flatMap(t=>Li(t)),ki=(e,t)=>{const s=f(t,hn);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Di(n)},Mi=new Set(["delete","get","patch"]),Ki=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),_i=new Set(["auth","identity","session","user"]),zi=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),$i=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!k(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Ui=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},qi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Bi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Vi=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>qi(s.getExpression(),t)&&Bi(s.getThenStatement())),Wi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!Mi.has(o))continue;const r=n.getExpression();if(!(k(r)||i.isPropertyAccessExpression(r)&&k(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},ji=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},Hi=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>ji(s)==="ctx")),Gi=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>zi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Yi=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Ki.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&_i.has(t.getName()))return!0}return Hi(e)||Gi(e)},Qi=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=M(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=Yt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Ut(n.receiver,"use","rls"),a=Yi(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const v=$i(d);if(v===void 0)continue;const x=Ui(d);if(x===void 0||c.has(x)||!Vi(o,x))continue;const P=Wi(o,x);P!==void 0&&(c.add(x),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:P,table:v,usesRls:r,visibility:n.visibility}))}return u},Xi=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Qi(c,r))}return s},Zi=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Ji=new Set(["insert","insertManyUnsafe","patch","replace"]),ea=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ji.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},ta=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},sa=(e,t,s,n)=>{const o=[];for(const r of e.getProperties()){let a,c;i.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):i.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!Zi.has(a))&&L(c)&&!z(c)&&o.push({exportName:S(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return o},na=(e,t)=>{const s=ea(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?ta(n,s).flatMap(o=>sa(o,s,e,t)):[]},ra=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of na(o,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},oa=(e,t,s=[])=>{const n=[],o=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of h(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=E(t,r);n.push(...ra(a,c,u=>o.get(`${c}:${u}`)))}return n},ia=["providerSubscriptionId","state"],aa=["providerEventId","processedAt"],Pt=(e,t)=>t.every(s=>s in e.shape),ca=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Pt(t,ia)&&Pt(s,aa)},la=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ua=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,da=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ua(t.getInitializer()):void 0},fa=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!la.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?da(n):void 0;return{callee:s,exportName:S(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},ga=(e,t)=>I(e,t,fa),pa=new Set(["defineQueue","defineWorkflow"]),ma=new Set(["run","runAction","runMutation","runQuery"]),ha=new Set(["api","internal"]),xa=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},va=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},Jt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},es=(e,t)=>e===t||e.startsWith(`${t}.`),ts=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},It=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},ss=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>It(s));return i.isIdentifier(e)&&It(e)&&t.push(e),t},Ea=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Sa=e=>{const t=Jt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ya=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Sa(e),o=new Set,r=a=>ts(a).some(c=>n.some(u=>es(c.getText(),u)))?!0:ss(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of Ea(a))o.add(u)}return{names:o,prefixes:n}},Aa=(e,t)=>ts(e).some(s=>t.prefixes.some(n=>es(s.getText(),n)))?!0:ss(e).some(s=>t.names.has(s.getText())),Na=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!ha.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},ba=(e,t,s)=>{const n=Jt(e,0);if(n===void 0)return[];const o=ya(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!ma.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!Aa(u,o))continue;const d=Na(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:S(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},Pa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=xa(n);if(o===void 0||!pa.has(o))continue;const r=va(n);r!==void 0&&s.push(...ba(r,o==="defineQueue"?"queue":"workflow",t))}return s},Ia=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pa(o,E(t,n)))}return s},wt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Tt=new Set(["account","credential","member","passkey","session","user"]),wa=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Ta=e=>{const s=wa(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Tt.has(s)||Tt.has(n)},Ca=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Fa=(e,t)=>{const{objects:s,opaque:n}=Oe(e,t);return Or(s).some(o=>Ca(o))?!0:n?void 0:!1},Oa=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ra=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},se={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},La=e=>{const t=Ra(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Oa(t);return{...se,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in wt?{...se,[wt[s]]:!0}:se},Da=e=>{const t={...se};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=La(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},ka=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Ma=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ka.has(t.getName()))return!1;const s=t.getExpression();if(!k(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:Ta(o.getLiteralText())},Ka=new Set(["create","runAfter","runAt","send","sendBatch"]),_a=new Set(["queues","scheduler","workflows"]),za=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ka.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&_a.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},$a=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return k(s)},ns=new Set(["generateObject","generateText","streamObject","streamText"]),Ua=e=>{const t=y(e.getExpression());return t!==void 0&&ns.has(t)},qa=e=>{const t=y(e.getExpression());if(t===void 0||!ns.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Ba=new Set(["log","span","trace"]),Va=new Set(["ai"]),Wa=new Set(["email","mail"]),ja=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),ye=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),Ha=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Ga=new Set(["every","filter","flatMap","forEach","map","some"]),Ya=new Set(["all","allSettled","race"]),Qa=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Ga.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&Ya.has(n))return t},Xa=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ha.has(t.getKind())){const s=Qa(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Za=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Ja=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ec=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!ja.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=Ja(n);r&&(t=!0,!Xa(r)&&!Za(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},tc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Ct="lunora-advisor-exempt",sc=/^[\s*/]+/u,nc=/[\w-]/u,rc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
6
+ `);for(const n of s.split(`
7
+ `)){const o=n.replace(sc,"");if(!o.startsWith(Ct))continue;const r=o.slice(Ct.length);if(nc.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},oc=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},ic=(e,t)=>{const s=oc(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},ac=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Ma(u)&&(r=!0),za(u)&&(t=!0),$a(u)&&(o=!0),Ua(u)&&(s=!0),qa(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=ec(e);return{callsMail:ye(e,Wa),emitsEvent:ye(e,Ba),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||ye(e,Va),throwsBareError:tc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},cc=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=M(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?Da(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=ic(e,s);return{...r?ac(r):{},...rc(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:Fa(s,n.receiver),kind:n.kind,visibility:n.visibility}},lc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=cc(o,t);r&&s.push(r)}return s},uc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lc(o,E(t,n)))}return s},dc=new Set(["dbRateLimit","rateLimit"]),fc=e=>i.isArrowFunction(e)?e.getBody():e,gc=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!dc.has(s))return;const n=e.getArguments()[2];if(!n)return;const o=N(n,"key");if(!o)return;const r=fc(o);if(!(!L(r)||z(r)))return{callee:s,exportName:S(e),file:t,limitName:zt(e),line:e.getStartLineNumber()}},pc=(e,t)=>I(e,t,gc),mc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),hc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!mc.has(t.getName()))return;const s=t.getExpression();if(k(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&k(s.getExpression()))return s.getName()},xc=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&k(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},vc=e=>{let t=j(e)??e;for(;i.isAwaitExpression(t);)t=j(t.getExpression())??t.getExpression();return t},rs=(e,t=!1)=>{const s=vc(e);if(i.isIdentifier(s)){if(t)return;const n=ue(s);return n===void 0?void 0:rs(n,!0)}if(i.isCallExpression(s))return hc(s)??xc(s)},Ec=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Sc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=M(s);if(n?.kind!=="query")return[];const o=Yt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Xs(n.receiver,"output"),a=n.receiver!==void 0&&Ut(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Ec(o)){const v=rs(d);v===void 0||c.has(v)||(c.add(v),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:v,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},yc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sc(c,r))}return s},Ac=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Nc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?M(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=$t(r);if(a===void 0)continue;const c=Ac(N(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},bc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Nc(c,r))}return s},ie=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ie(e.getLeft()),s=ie(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Pc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ie(t)!==void 0},Ic=/(?:^|\/)__tests__\//u,wc=/\.(?:spec|test)$/u,Tc=e=>Ic.test(e)||wc.test(e),Cc=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Fc=(e,t,s)=>wn(e)?!Tc(s)&&Tn(Cc(t)):!0,Oc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(Pc(r))continue;const a=ie(r);if(a===void 0)continue;const c=Pn(a);if(c===void 0||!Fc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:In(a)}))}return s},Rc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Oc(o,E(t,n)))}return s},Lc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?M(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=$t(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&L(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},Dc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Lc(c,r))}return s},kc=new Set(["query","unsafe"]),Mc=e=>{if(!i.isPropertyAccessExpression(e)||!kc.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},Kc=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),_c=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",zc=(e,t)=>{if(!Mc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Kc(s)))return{exportName:_c(e),file:t,line:s.getStartLineNumber()}},$c=(e,t)=>I(e,t,zc),Uc=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],qc=e=>{for(const[t,s]of Uc)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Bc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=qc(a);c!==void 0&&s.push({file:E(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Vc=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Wc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return fe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Vc,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},jc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Hc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Gc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=Hc(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Yc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=jc.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Qc=(e,t)=>{const s=Yc(e.getExpression());if(s!==void 0)return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...Gc(e.getArguments()[s.optionsIndex])}},Xc=(e,t)=>I(e,t,Qc),Zc=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Jc=(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"}),el=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return Oe(e,t).opaque},tl=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=M(a);c!==void 0&&el(a,c.receiver)&&s.push(Jc(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},sl=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...tl(o,E(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},nl=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),ge=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),os=e=>!e.isAny(),Le=e=>{const t=e.getType();if(!os(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:nl.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},is=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},as={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."},rl=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.`}),ol={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},De=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,v=d===void 0?o:rl(d),x=c===void 0?v.remediation:`${c} ${v.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. 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 \`${u}\` but was not registered — ${v.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${x}`:x,title:"Procedure exists at runtime but is missing from the generated API"}},il=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(ge(s,t,a)||!is(r))continue;const c=Le(r);c!==void 0&&n.push(De(t,a,c,r.getStartLineNumber(),as))}return n},al=(e,t,s)=>{if(ge(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Le(o.getExpression());r!==void 0&&n.push(De(t,"default",r,o.getStartLineNumber(),as))}return n},cl=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(ge(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!is(c))continue;const u=Le(c);u!==void 0&&n.push(De(t,a,u,r.getStartLineNumber(),ol))}return n},ll=(e,t,s)=>[...il(e,t,s),...al(e,t,s),...cl(e,t,s)],ul=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>ge(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),dl=({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"}),fl=(e,t,s)=>{const n=[],o=[];for(const a of h(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=E(t,a);n.push(...ll(c,u,s)),o.push(...ul(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!os(a.getType()))&&n.push(dl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},gl=new Set(["when","where"]),Ae=new Set(["definePolicy","defineShape"]),pl=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return Ae.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return Ae.has(o)?o:void 0}const s=t.getText();return Ae.has(s)?s:void 0},ml=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,cs=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(ml(e))return"empty-object";if(i.isParenthesizedExpression(e))return cs(e.getExpression())}},ke=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),hl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ke(t)===e),ls=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ke(t)===e),xl=e=>{const t=hl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||ls(e).length>0},vl=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ke(t)===e),we=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",El=(e,t)=>we(e)||we(t),Sl=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Ft=e=>!we(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),yl=(e,t,s)=>{const n=Sl.get(e);if(n!==void 0)return El(t,s)?n==="positive"?"negative":"positive":Ft(t)||Ft(s)?void 0:n},W=e=>{if(i.isParenthesizedExpression(e))return W(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=yl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=W(e.getLeft()),o=W(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},Ot=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Al=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Nl=e=>i.isReturnStatement(e)?e.getExpression()??e:e,bl=e=>{const t=[];for(const s of ls(e)){const n=W(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of vl(e)){const n=W(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?Ot(s.getThenStatement()):Ot(s.getElseStatement())??Al(s);o!==void 0&&t.push(Nl(o))}return t},Pl=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Il=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!gl.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&xl(a))for(const c of bl(a)){const u=cs(c);u!==void 0&&o.push({exportName:Pl(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},wl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=pl(n);o!==void 0&&s.push(...Il(n,o,t))}return s},Tl=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wl(o,E(t,n)))}return s},Cl=new Set(["query","upsert","upsertMany"]),Fl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Cl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Ol=(e,t)=>{const s=Fl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=N(n,"namespace");if(!(!o||!L(o)||z(o)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},Rl=(e,t)=>I(e,t,Ol),Ll=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Dl=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},kl=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Ll(a))continue;const c=js(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Dl(a)})}}return s},Ml=".lunora-schema.json",w=(e,t)=>{b(e)&&Dt(e,"utf8")===t||Ss(e,t,"utf8")},R=(e,t)=>{if(t===""){ys(e,{force:!0});return}w(e,t)},Kl=e=>{const t=f(e,"package.json");if(b(t))try{const s=JSON.parse(Dt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},_l=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},zl=e=>{let t=b(e)?e:ee(e);for(;t&&t!==ee(t);){const s=f(t,"tsconfig.json");if(b(s))return s;t=ee(t)}},Rt=e=>e.replaceAll("\\","/"),$l=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new D("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), 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 r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new D("MASK_UNSUPPORTED",`defineShape "${r.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 "${r.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(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new D("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.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})}},ae=(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)},Lt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Ul=8,ql=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:v}=e;let x=ct(a,o),P=ut(a,o),K=lt(a,o);dt([...x,...P].map(g=>g.filePath)),dt(K.filter(g=>g.stream).map(g=>g.filePath),"http-stream");for(let g=1;;g+=1){const T=zs({agents:t,functions:x,httpRoutes:K,mutators:P,useUmbrella:d,workflows:v}),F=$s({agents:t,functions:x,migrations:r,mutators:P,shapes:c,useUmbrella:d,usesSandbox:u});if(g>=Ul||Lt(a,s,T)&&Lt(a,n,F))return{apiContent:T,functions:x,functionsContent:F,httpRoutes:K,mutators:P};ae(a,s,T),ae(a,n,F),x=ct(a,o),P=ut(a,o),K=lt(a,o)}},Bl=e=>{const t=zl(e);return t?new at({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new at({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},_u=(e,t)=>{const s=h(t),n=f(t,"schema.ts");b(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>Rt(c))),r=Rt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},zu=e=>{const t=_l(),s=t?Ee.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),o=f(n,"schema.ts");if(!b(o))throw new D("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??Bl(n);an(zo);const a=bn(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:v,dependencies:x,entryCronTriggers:P,env:K,featureUsage:g,hasFlags:T,hasNotify:F,identity:B,platformGate:A,queues:O,serverContent:$,storageRulesMetadata:V,usesSandbox:G,useUmbrella:_,workflows:C}=rr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),p=f(n,"_generated"),Me=f(p,"dataModel.ts"),Ke=f(p,"server.ts"),us=f(p,"api.ts"),ds=f(p,"functions.ts");ae(r,Me,v),ae(r,Ke,$);const Y=mn(r,n),U=Cn(r,n),{apiContent:_e,functions:q,functionsContent:ze,httpRoutes:fs,mutators:$e}=ql({agents:c,apiPath:us,generatedFunctionsPath:ds,lunoraDirectory:n,migrations:Y,project:r,shapes:U,useUmbrella:_,usesSandbox:G,workflows:C}),Q=e.lint===!1?void 0:bs({adminRoutes:fr(r,n),aiRawRuns:mr(r,n),aiToolSideEffects:Pr(r,n),argumentDerivedFetches:Tr(r,n),argumentValidators:_r(r,n),authApiCalls:cn(r,n),authConfigs:Gr(r,n),browserUrlAccesses:Jr(r,n),configCalls:ao(r,n),containerKeyAccesses:lo(r,n),containerOverrides:ho(r,n),containers:u,exportSinks:So(r,n),staleMigrationImports:Bc(r,n),failOpenGuards:Po(r,n),flagReads:Do(r,n),flagSecurityDefaults:_o(r,n),geoIndexUsages:qo(r,n),httpActionGuards:Yo(r,n),httpHeaderWrites:oi(r,n),hyperdriveCalls:fn(r,n),identityClaimReads:fi(r,n),imageDeliveryUrlAccesses:pi(r,n),inserts:gn(r,n),kvKeyAccesses:hi(r,n,q),mailRecipientAccesses:yi(r,n),maskProcedures:pn(r,n),maskStrategies:Ci(r,n),mutatorWrites:ki(r,n),nondeterministicCalls:vn(r,n),normalizeIdAuthorizations:Xi(r,n),notifyCalls:Sn(r,n),notifyConfig:En(r,n),ownerFieldWrites:oa(r,n,q),unrestrictedWhereBranches:Tl(r,n),paymentWebhooks:ga(r,n),privilegedDispatches:Ia(r,n),procedureProtections:uc(r,n),queries:on(r,n),queues:O,r2sqlCalls:yn(r,n),ratelimitKeySelectors:pc(r,n),rawRowReturns:yc(r,n),relationLoads:bc(r,n),rlsProcedures:An(r,n),schema:a,secretLiterals:Rc(r,n),shapes:U,softDeleteReads:Dc(r,n),sqlInterpolations:$c(r,n),storageKeyAccesses:Wc(r,n,q),storageUploads:Xc(r,n),vectorNamespaceAccesses:Rl(r,n),workflowCalls:kl(r,n),workflows:C,wranglerVariables:e.wranglerVariables}),Ue=Q===void 0?[]:[...As(Q,{source:"static"}),...fl(r,n,{byName:new Set([...C,...O,...c,...u].map(m=>m.exportName)),byPath:new Set([...q,...$e,...U,...Y].map(m=>`${m.filePath}:${m.exportName}`))}),...sl(r,n)],gs=Nn(r,n),qe=Ii(r,n);$l(U,qe,bi(r,n));const ps=T?Co(r,n):[],pe=A.signals.vectorStore!==!1,X=Zc(g,{containerCount:u.length,cronCount:d.length,dependencies:x,hasPaymentTables:ca(a.tables),queueCount:O.length,storageColumnCount:Object.keys(kt(a)).length,storageRuleCount:V.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:pe,workflowCount:C.length}),Be=t?Ee.now():0,me=kn(a,Y.map(m=>m.id)),Ve=Ts({advisories:Ue.filter(m=>m.name!=="procedure_type_check_unavailable"),advisorProcedures:Q?.procedureProtections??[],agents:c,containers:u,env:K,flagKeys:ps,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:T,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:F,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:pe,hasX402:g.x402,maskMetadata:qe,mutators:$e,queues:O,rlsMetadata:gs,schema:a,schemaSnapshot:me,shapes:U,storageRules:V,studioFeatures:X,useUmbrella:_,workflows:C}),We=Cs(U,x.has("@lunora/db"),_),je=Fs(u,a.jurisdiction),He=Os(C),Ge=Rs(c),Ye=Ls(O),Qe=Ds(d),Xe=ks(a.vectorIndexes),Z=Ms(a,_),Ze=Ks(x.has("@lunora/seed")),J=e.apiSpec??"openapi",he=J==="openapi"||J==="both",xe=J==="openrpc"||J==="both",Je=Fn({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:x.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:x.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:x.has("@lunora/astro")||x.has("@lunora/svelte")||x.has("@lunora/vue"),hasGlobal:a.tables.some(m=>Mt(m)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>Kt(m)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:X.kv,hasNotify:F,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:O.some(m=>m.mode==="push"),hasScheduler:X.scheduler,hasStorage:X.storage,hasVectors:pe,hasWorkflow:C.length>0,hasX402:g.x402,identity:B,jurisdiction:a.jurisdiction,tableNames:a.tables.map(m=>m.name),useUmbrella:_,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:he,wantsOpenRpc:xe}),et=Kl(e.projectRoot),tt=On({functions:q,httpRoutes:fs,version:et}),st=Ln({functions:q,version:et}),nt=`${JSON.stringify(tt,void 0,2)}
8
+ `,rt=`${JSON.stringify(st,void 0,2)}
9
+ `,ot=Rn(tt),it=Dn(st),ve=f(n,Ml),ms=b(ve);if(e.dryRun||(b(p)||Es(p,{recursive:!0}),w(f(p,"app.ts"),Je),w(Me,v),w(f(p,"api.ts"),_e),w(Ke,$),w(f(p,"functions.ts"),ze),w(f(p,"shard.ts"),Ve),w(f(p,"crons.ts"),Qe),w(f(p,"vectors.ts"),Xe),w(f(p,"drizzle.global.ts"),Z.global),w(f(p,"drizzle.shard.ts"),Z.shard),R(f(p,"containers.ts"),je),R(f(p,"workflows.ts"),He),R(f(p,"agents.ts"),Ge),R(f(p,"queues.ts"),Ye),R(f(p,"seed.ts"),Ze),R(f(p,"collections.ts"),We),R(f(p,"openapi.json"),he?nt:""),R(f(p,"openapi.ts"),he?ot:""),R(f(p,"openrpc.json"),xe?rt:""),R(f(p,"openrpc.ts"),xe?it:""),(!ms||e.updateSchemaBaseline===!0)&&w(ve,Ns(me))),t){const m=Ee.now(),hs=Math.round(m-s),xs=Math.round(Be-s),vs=Math.round(m-Be);console.error(`@lunora/codegen: codegen took ${hs.toString()}ms (discovery ${xs.toString()}ms, emit ${vs.toString()}ms)`)}return{advisories:Ue,advisorContext:Q,agents:c,containers:u,cronTriggers:[...new Set([..._s(d),...P])],generated:{agents:Ge,api:_e,app:Je,collections:We,containers:je,crons:Qe,dataModel:v,drizzleGlobal:Z.global,drizzleShard:Z.shard,functions:ze,openApi:nt,openApiModule:ot,openRpc:rt,openRpcModule:it,queues:Ye,seed:Ze,server:$,shard:Ve,vectors:Xe,workflows:He},migrations:Y,outputDirectory:p,platformDiagnostics:A.diagnostics,queues:O,schemaSnapshot:me,schemaSnapshotPath:ve,workflows:C}};export{Ml as SCHEMA_SNAPSHOT_FILENAME,Bl as createCodegenProject,zl as findTsconfig,_u as refreshCodegenProject,zu as runCodegen};
@@ -1,3 +1,3 @@
1
- import{G as S}from"./emit-Lx7UkoGn.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-CW7-uASH.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
1
+ import{G as S}from"./emit-B2PLgxM0.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-CW7-uASH.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
2
2
  `,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};