@lunora/codegen 1.0.0-alpha.25 → 1.0.0-alpha.251
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/LICENSE.md +6 -0
- package/README.md +1 -1
- package/dist/index.d.mts +3734 -1247
- package/dist/index.d.ts +3734 -1247
- package/dist/index.mjs +1 -34
- package/dist/packem_shared/AGENTS_FILENAME-D8SgT3OR.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-BbW-W0N2.mjs +22 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-C13yKxas.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-vMWzRzRF.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-W5XQz_Po.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-DSXl0YM2.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-DqWOgC5Z.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-C1J_47et.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-Cr7Zzp6s.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-RGwht3Xu.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-qrQnFo7L.mjs +11 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
- package/dist/packem_shared/SHAPES_FILENAME-DRUFomCj.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-4-ib4HH-.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-SxfElVzK.mjs +3 -0
- package/dist/packem_shared/chain-mte5djRJ.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-CmcShAze.mjs +1 -0
- package/dist/packem_shared/context-property-calls-CWf9-6G5.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-DoSN_yc3.mjs +1 -0
- package/dist/packem_shared/discoverCrons-BEALHx1S.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-BcBzcG5x.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-CJHS4llq.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs +1 -0
- package/dist/packem_shared/discoverInserts-DpuLYPPd.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-B0w8gM0S.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-Dt7ywfZv.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-CNJV2BiP.mjs +1 -0
- package/dist/packem_shared/discoverQueries-BcdqjYky.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-mXBmPOGj.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-F4Cy-kSi.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-BnsPld5I.mjs +1 -0
- package/dist/packem_shared/discoverSchema-D5R60b4F.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-D3Ot9g5f.mjs +1 -0
- package/dist/packem_shared/emitAgents-DtZrevpx.mjs +1 -0
- package/dist/packem_shared/emitApi-DdW9RyGG.mjs +154 -0
- package/dist/packem_shared/emitApp-Cp0kB4-N.mjs +860 -0
- package/dist/packem_shared/emitCrons-BRKXFGFu.mjs +83 -0
- package/dist/packem_shared/emitDataModel-D3WuEZ4b.mjs +113 -0
- package/dist/packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs +15 -0
- package/dist/packem_shared/emitFunctions-BgNeOZt_.mjs +249 -0
- package/dist/packem_shared/emitServer-BOpHpi8r.mjs +370 -0
- package/dist/packem_shared/emitShard-HB5NPFdO.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-D48EXUVQ.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-Cl1CJFeh.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
- package/dist/packem_shared/index-D7dKfGPh.mjs +1 -0
- package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-nNIDOrlR.mjs +1 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/modules-DyCocr1e.mjs +1 -0
- package/dist/packem_shared/parse-validator-C6fHL7OS.mjs +1 -0
- package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
- package/dist/packem_shared/qualifiers-BhOL15WZ.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-CeQvSswr.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/shard-CyNCZP7J.mjs +1435 -0
- package/dist/packem_shared/shard-runtime-DMN3MgIM.mjs +321 -0
- package/dist/packem_shared/shared-DjUziztz.mjs +9 -0
- package/dist/packem_shared/sourceCapabilitySignals-oZFprILA.mjs +1 -0
- package/dist/packem_shared/unwrap-handler-return-DVY_kFF7.mjs +1 -0
- package/package.json +16 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
- package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-BullHnLo.mjs +0 -3265
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
- package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-D7MAVX3K.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BAcxxSdB.mjs +0 -1130
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
- package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-Bm56LsBb.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
- package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
- package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
- package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
- package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
- package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
- package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
- package/dist/packem_shared/emitApp-BUN7hhlY.mjs +0 -666
- package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
- package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
package/dist/index.mjs
CHANGED
|
@@ -1,34 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { CodegenDiagnosticError, diagnosticAt } from './packem_shared/CodegenDiagnosticError-DeblMkzO.mjs';
|
|
3
|
-
export { default as discoverAuthApiCalls } from './packem_shared/discoverAuthApiCalls-CoirYbg6.mjs';
|
|
4
|
-
export { CONTAINERS_FILENAME, discoverContainers } from './packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs';
|
|
5
|
-
export { default as discoverCrons } from './packem_shared/discoverCrons-Cev7RRAf.mjs';
|
|
6
|
-
export { FLAGS_FILENAME, discoverFlags } from './packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs';
|
|
7
|
-
export { discoverFunctions } from './packem_shared/discoverFunctions-BWMczzBx.mjs';
|
|
8
|
-
export { default as discoverHttpRoutes } from './packem_shared/discoverHttpRoutes-CfP6cMzt.mjs';
|
|
9
|
-
export { default as discoverInserts } from './packem_shared/discoverInserts-C7zxXkUf.mjs';
|
|
10
|
-
export { default as discoverMaskProcedures } from './packem_shared/discoverMaskProcedures-Cm81kwrb.mjs';
|
|
11
|
-
export { default as discoverMigrations } from './packem_shared/discoverMigrations-Bi5nJ0mJ.mjs';
|
|
12
|
-
export { MUTATORS_FILENAME, discoverMutators } from './packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs';
|
|
13
|
-
export { default as discoverNondeterministicCalls } from './packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs';
|
|
14
|
-
export { default as discoverQueries } from './packem_shared/discoverQueries-B0wGT-xe.mjs';
|
|
15
|
-
export { QUEUES_FILENAME, discoverQueues } from './packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs';
|
|
16
|
-
export { default as discoverR2sqlCalls } from './packem_shared/discoverR2sqlCalls-BVNMd428.mjs';
|
|
17
|
-
export { discoverRlsMetadata, default as discoverRlsProcedures } from './packem_shared/discoverRlsMetadata-BS9GOGC5.mjs';
|
|
18
|
-
export { default as discoverSchema } from './packem_shared/discoverSchema-KYq55qu3.mjs';
|
|
19
|
-
export { SHAPES_FILENAME, discoverShapes } from './packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs';
|
|
20
|
-
export { default as discoverStorageRulesMetadata } from './packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs';
|
|
21
|
-
export { WORKFLOWS_FILENAME, discoverWorkflows } from './packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs';
|
|
22
|
-
export { GENERATED_HEADER, emitApi, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers } from './packem_shared/GENERATED_HEADER-BullHnLo.mjs';
|
|
23
|
-
export { emitApp } from './packem_shared/emitApp-BUN7hhlY.mjs';
|
|
24
|
-
export { buildOpenApiDocument, emitOpenApi, emitOpenApiModule } from './packem_shared/buildOpenApiDocument-Bm56LsBb.mjs';
|
|
25
|
-
export { OPENRPC_VERSION, buildOpenRpcDocument, emitOpenRpc, emitOpenRpcModule } from './packem_shared/OPENRPC_VERSION-D7MAVX3K.mjs';
|
|
26
|
-
export { SCHEMA_SNAPSHOT_FILENAME, createCodegenProject, refreshCodegenProject, runCodegen } from './packem_shared/SCHEMA_SNAPSHOT_FILENAME-BAcxxSdB.mjs';
|
|
27
|
-
export { SCHEMA_SNAPSHOT_VERSION, SchemaSnapshotParseError, buildSchemaSnapshot, diffSchemaSnapshots, evaluateSchemaDrift, parseSchemaSnapshot, serializeSchemaSnapshot } from './packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs';
|
|
28
|
-
export { schemaFromIr } from './packem_shared/schemaFromIr-DTYsLBaA.mjs';
|
|
29
|
-
export { LUNORA_ERROR_CODES, validatorIrToJsonSchema } from './packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs';
|
|
30
|
-
export { LUNORA_SOLUTION_RULES, findLunoraSolution } from './packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs';
|
|
31
|
-
|
|
32
|
-
const VERSION = "0.0.0";
|
|
33
|
-
|
|
34
|
-
export { VERSION };
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-BbW-W0N2.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as g,discoverAgents as C}from"./packem_shared/AGENTS_FILENAME-D8SgT3OR.mjs";import{listLunoraSourceFiles as R}from"./packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs";import{default as _}from"./packem_shared/discoverAuthApiCalls-DoSN_yc3.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-C13yKxas.mjs";import{default as F}from"./packem_shared/discoverCrons-BEALHx1S.mjs";import{sourceCapabilitySignals as D}from"./packem_shared/sourceCapabilitySignals-oZFprILA.mjs";import{FLAGS_FILENAME as U,discoverFlags as b}from"./packem_shared/FLAGS_FILENAME-W5XQz_Po.mjs";import{default as y}from"./packem_shared/discoverFunctions-BcBzcG5x.mjs";import{default as k}from"./packem_shared/discoverHttpRoutes-CJHS4llq.mjs";import{default as W}from"./packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs";import{default as V}from"./packem_shared/discoverInserts-DpuLYPPd.mjs";import{d as Q}from"./packem_shared/index-D7dKfGPh.mjs";import{default as w}from"./packem_shared/discoverMigrations-Dt7ywfZv.mjs";import{MUTATORS_FILENAME as Y,discoverMutators as X}from"./packem_shared/MUTATORS_FILENAME-DqWOgC5Z.mjs";import{default as $}from"./packem_shared/discoverNondeterministicCalls-CNJV2BiP.mjs";import{NOTIFY_FILENAME as re,discoverNotifyCalls as oe,discoverNotifyConfig as te}from"./packem_shared/NOTIFY_FILENAME-C1J_47et.mjs";import{default as ae}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{default as me}from"./packem_shared/discoverQueries-BcdqjYky.mjs";import{QUEUES_FILENAME as de,discoverQueues as pe}from"./packem_shared/QUEUES_FILENAME-RGwht3Xu.mjs";import{default as ne}from"./packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs";import{default as xe}from"./packem_shared/discoverRlsProcedures-F4Cy-kSi.mjs";import{default as Ee}from"./packem_shared/discoverRlsMetadata-mXBmPOGj.mjs";import{discoverSandboxUsage as Ae}from"./packem_shared/discoverSandboxUsage-BnsPld5I.mjs";import{default as Ne}from"./packem_shared/discoverSchema-D5R60b4F.mjs";import{readServiceBindings as Ce,resolveServiceBindings as Oe}from"./packem_shared/readServiceBindings-CeQvSswr.mjs";import{SHAPES_FILENAME as Te,discoverShapes as _e}from"./packem_shared/SHAPES_FILENAME-DRUFomCj.mjs";import{default as Le}from"./packem_shared/discoverStorageRulesMetadata-D3Ot9g5f.mjs";import{WORKFLOWS_FILENAME as he,discoverWorkflows as Fe}from"./packem_shared/WORKFLOWS_FILENAME-4-ib4HH-.mjs";import{emitApp as De}from"./packem_shared/emitApp-Cp0kB4-N.mjs";import{isD1GlobalTable as Ue,isHyperdriveGlobalTable as be}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as ye,emitOpenApi as je,emitOpenApiModule as ke}from"./packem_shared/buildOpenApiDocument-SxfElVzK.mjs";import{OPENRPC_VERSION as We,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-Cr7Zzp6s.mjs";import{DEFAULT_TARGET as qe,platformMatrixIds as we,readProjectTarget as Je,resolveCodegenTarget as Ye}from"./packem_shared/DEFAULT_TARGET-vMWzRzRF.mjs";import{loadProjectConfig as Ze,readProjectConfigLiterals as $e}from"./packem_shared/loadProjectConfig-nNIDOrlR.mjs";import{SCHEMA_SNAPSHOT_FILENAME as rr,createCodegenProject as or,findTsconfig as tr,refreshCodegenProject as sr,runCodegen as ar}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-qrQnFo7L.mjs";import{SchemaSnapshotParseError as mr,buildSchemaSnapshot as fr,evaluateSchemaDrift as dr,parseSchemaSnapshot as pr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as nr}from"./packem_shared/fingerprintSchemaSources-Cl1CJFeh.mjs";import{schemaFromIr as xr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Er,validatorIrToJsonSchema as ur}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as vr,SDK_TARGETS as Nr,generateSdk as gr}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as Or,secretKindOf as Rr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs";import{default as Lr}from"./packem_shared/emitFunctions-BgNeOZt_.mjs";import{default as hr}from"./packem_shared/emitServer-BOpHpi8r.mjs";import{e as Pr}from"./packem_shared/shard-CyNCZP7J.mjs";import{G as Gr}from"./packem_shared/shared-DjUziztz.mjs";import{MESSAGE_SOLUTIONS as br,findSolutionByMessage as Hr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as jr,findProjectConfigFile as kr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{s as Wr,t as Kr,u as Vr}from"./packem_shared/shard-runtime-DMN3MgIM.mjs";import{emitApi as Qr,emitCollections as qr}from"./packem_shared/emitApi-DdW9RyGG.mjs";import{emitCrons as Jr,emitScheduler as Yr,emitVectors as Xr,emitWranglerCronTriggers as Zr}from"./packem_shared/emitCrons-BRKXFGFu.mjs";import{emitDataModel as eo}from"./packem_shared/emitDataModel-D3WuEZ4b.mjs";import{isTypedSchema as oo}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{g as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,qe as DEFAULT_TARGET,U as FLAGS_FILENAME,Gr as GENERATED_HEADER,Er as LUNORA_ERROR_CODES,br as LUNORA_SOLUTION_RULES,Y as MUTATORS_FILENAME,re as NOTIFY_FILENAME,We as OPENRPC_VERSION,jr as PROJECT_CONFIG_FILENAMES,de as QUEUES_FILENAME,rr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,vr as SDK_LANGUAGES,Nr as SDK_TARGETS,Te as SHAPES_FILENAME,mr as SchemaSnapshotParseError,e as VERSION,he as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,Ke as buildOpenRpcDocument,fr as buildSchemaSnapshot,or as createCodegenProject,c as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,C as discoverAgents,_ as discoverAuthApiCalls,M as discoverContainers,F as discoverCrons,b as discoverFlags,y as discoverFunctions,k as discoverHttpRoutes,W as discoverHyperdriveCalls,V as discoverInserts,Q as discoverMaskProcedures,w as discoverMigrations,X as discoverMutators,$ as discoverNondeterministicCalls,oe as discoverNotifyCalls,te as discoverNotifyConfig,me as discoverQueries,pe as discoverQueues,ne as discoverR2sqlCalls,Ee as discoverRlsMetadata,xe as discoverRlsProcedures,Ae as discoverSandboxUsage,Ne as discoverSchema,_e as discoverShapes,Le as discoverStorageRulesMetadata,Fe as discoverWorkflows,Wr as emitAgents,Qr as emitApi,De as emitApp,qr as emitCollections,Kr as emitContainers,Jr as emitCrons,eo as emitDataModel,_r as emitDrizzleSchema,Lr as emitFunctions,je as emitOpenApi,ke as emitOpenApiModule,Ve as emitOpenRpc,ze as emitOpenRpcModule,Yr as emitScheduler,hr as emitServer,Pr as emitShard,Xr as emitVectors,Vr as emitWorkflows,Zr as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,dr as evaluateSchemaDrift,Hr as findLunoraSolution,kr as findProjectConfigFile,tr as findTsconfig,nr as fingerprintSchemaSources,m as formatAdvisories,gr as generateSdk,Ue as isD1GlobalTable,be as isHyperdriveGlobalTable,oo as isTypedSchema,f as lintSchema,R as listLunoraSourceFiles,Ze as loadProjectConfig,pr as parseSchemaSnapshot,we as platformMatrixIds,ae as readPackageDependencies,$e as readProjectConfigLiterals,Je as readProjectTarget,Ce as readServiceBindings,Or as redact,sr as refreshCodegenProject,Ye as resolveCodegenTarget,Oe as resolveServiceBindings,ar as runCodegen,xr as schemaFromIr,Rr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,D as sourceCapabilitySignals,d as toAdvisorContext,ur as validatorIrToJsonSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as p}from"node:fs";import{join as f}from"node:path";import{agentDefaultName as d,agentClassName as b,voiceBindingName as N,voiceClassName as y}from"@lunora/agent/naming";import{LunoraError as m}from"@lunora/errors";import{Node as s,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapToCallExpression as A,findObjectProperty as c,stringPropertyFor as w}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const h="agents.ts",E=o=>{const n=o.getSymbol();if(!n)return o.getText()==="defineAgent";for(const t of n.getDeclarations())if(s.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/agent"?!1:t.getNameNode().getText()==="defineAgent";return!1},P=w("agent"),v=(o,n,t)=>{if(o.getKind()===u.TrueKeyword)return!0;if(o.getKind()===u.FalseKeyword)return!1;throw l(o,`agent "${n}": \`${t}\` must be a static boolean literal — it is deploy configuration codegen writes into the ctx.agents wiring spec`)},T=(o,n)=>{const t=o.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))throw l(o,`agent "${n}": defineAgent must be passed an inline object literal`);const e={className:b(n),exportName:n,name:d(n)},i=c(t,"name");i&&s.isPropertyAssignment(i)&&(e.name=P(i.getInitializerOrThrow(),n,"name"));const r=c(t,"publicRun");r&&s.isPropertyAssignment(r)&&v(r.getInitializerOrThrow(),n,"publicRun")&&(e.publicRun=!0);const a=c(t,"voice");if(a&&s.isPropertyAssignment(a)){const g=a.getInitializerOrThrow();if(!s.isObjectLiteralExpression(g))throw l(g,`agent "${n}": \`voice\` must be an inline object literal — its presence tells codegen to emit the voice-session Durable Object`);e.voice=!0,e.voiceBindingName=N(n),e.voiceClassName=y(n)}return c(t,"onEmail")&&(e.onEmail=!0),e},I=o=>{const n=[];for(const t of o.getVariableDeclarations()){if(!t.isExported())continue;const e=A(t.getInitializer());if(!e)continue;const i=e.getExpression();if(!s.isIdentifier(i)||!E(i))continue;const r=t.getNameNode();if(!s.isIdentifier(r))throw l(r,"defineAgent exports must be plain named exports (no destructuring)");n.push(T(e,r.getText()))}return n},x=o=>{const n=new Map,t=new Map;for(const e of o){const i=n.get(e.name);if(i!==void 0)throw new m("DUPLICATE_AGENT_NAME",`Duplicate agent name "${e.name}": produced by both "${i}" and "${e.exportName}". Deployed agent names must be unique across the project.`,{status:500});n.set(e.name,e.exportName);const r=t.get(e.className);if(r!==void 0)throw new m("DUPLICATE_AGENT_CLASS",`Duplicate agent class "${e.className}": produced by both "${r}" and "${e.exportName}". Agent export names must yield unique generated class names.`,{status:500});t.set(e.className,e.exportName)}},O=(o,n)=>{const t=f(n,h);if(!p(t))return[];const e=o.getSourceFile(t)??o.addSourceFileAtPath(t),i=I(e);return i.sort((r,a)=>r.exportName.localeCompare(a.exportName)),x(i),i};export{h as AGENTS_FILENAME,O as discoverAgents};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const n=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@lunora/cloudflare-access",serverCtxField:`
|
|
2
|
+
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
3
|
+
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`,shardBinding:"bespoke",tier:"every"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai",requiredPackage:"@lunora/ai",serverCtxField:`
|
|
4
|
+
readonly ai: import("@lunora/ai").LunoraAi;`,shardBinding:"bespoke",tier:"action"},{appMethod:{configKey:"aiSearch",doc:"Override the AI Search namespace binding backing `ctx.aiSearch` (defaults to `env.AI_SEARCH`).",method:"aiSearch"},contextProperty:"aiSearch",key:"aiSearch",moduleSpecifier:"@lunora/bindings/ai-search",requiredPackage:"@lunora/bindings",serverCtxField:'\n /** Cloudflare AI Search namespace (`ai_search_namespaces`): `.get(name)` an instance, then `search` / `chatCompletions`. Billed, non-deterministic network I/O — available only in actions. */\n readonly aiSearch: import("@lunora/bindings/ai-search").AiSearch;',shardBinding:{binding:{envName:"AI_SEARCH"},clientType:"AiSearch",missingMessage:"ctx.aiSearch: no AI Search binding found. Add an `ai_search_namespaces` binding (env.AI_SEARCH) to wrangler.jsonc, or point `defineApp().aiSearch((env) => …)` at yours.",stubMethods:["chatCompletions","create","delete","get","list","search"],syncStubMethods:["get"]},tier:"action"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",requiredPackage:"@lunora/bindings",serverCtxField:`
|
|
5
|
+
/** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
|
|
6
|
+
readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,shardBinding:{binding:{bindingType:"AnalyticsEngineDatasetLike",envName:"ANALYTICS",factory:{name:"createAnalytics"}},clientType:"AnalyticsClient",missingMessage:"ctx.analytics: no Analytics Engine binding found. Add an `analytics_engine_datasets` binding (env.ANALYTICS) to wrangler.jsonc, or pass `analytics` to createShardDO().",stubMethods:["track","writeDataPoint"],syncStubMethods:["track","writeDataPoint"]},tier:"every"},{appMethod:{configKey:"artifacts",doc:"Override the Artifacts binding backing `ctx.artifacts` (defaults to `env.ARTIFACTS`).",method:"artifacts"},contextProperty:"artifacts",key:"artifacts",moduleSpecifier:"@lunora/bindings/artifacts",requiredPackage:"@lunora/bindings",serverCtxField:'\n /** Cloudflare Artifacts repos (create/import/fork, Git tokens, read commits and files). Non-deterministic — available only in actions. Writes go through `git push` with a token, not this client. */\n readonly artifacts: import("@lunora/bindings/artifacts").ArtifactsClient;',shardBinding:{binding:{bindingType:"ArtifactsBindingLike",envName:"ARTIFACTS",factory:{name:"createArtifacts",option:"binding"}},clientType:"ArtifactsClient",missingMessage:'ctx.artifacts: no Artifacts binding found. Add an `artifacts` binding ({ binding: "ARTIFACTS", namespace }) to wrangler.jsonc, or point ctx.artifacts at another binding with defineApp().artifacts((env) => env.<BINDING>).',stubMethods:["authenticatedRemote","create","delete","import","info","list","withRepo"],syncStubMethods:["authenticatedRemote"]},tier:"action"},{appMethod:{configKey:"browser",doc:"Build the `ctx.browser` helper, e.g. `(env) => createBrowser({ binding: env.BROWSER, launch })`. REQUIRED: unlike the binding-backed capabilities, `ctx.browser` is not auto-constructed — without this thunk every method throws, because the generated worker deliberately stays free of the optional `@cloudflare/playwright` peer.",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",requiredPackage:"@lunora/browser",serverCtxField:`
|
|
7
|
+
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
8
|
+
readonly browser: import("@lunora/browser").Browser;`,shardBinding:{clientType:"Browser",missingMessage:"ctx.browser: provide a `browser` config thunk, e.g. `browser: (env) => createBrowser({ binding: env.BROWSER, launch })` with `import { launch } from '@cloudflare/playwright'`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.",stubMethods:["cancelCrawl","connect","content","crawl","crawlResult","launch","pdf","quickAction","scrape","screenshot","sessions"]},tier:"action"},{contextProperty:"containers",key:"container",moduleSpecifier:"@lunora/container"},{contextProperty:"flags",key:"flags",moduleSpecifier:"@lunora/flags"},{appMethod:{configKey:"sql",doc:"Wire the Hyperdrive SQL client backing `ctx.sql` — build it with `createHyperdrive` + `fromPostgresJs`/`fromNodePg`/`fromMysql2`.",method:"hyperdrive"},contextProperty:"sql",key:"hyperdrive",moduleSpecifier:"@lunora/hyperdrive",requiredPackage:"@lunora/hyperdrive",serverCtxField:`
|
|
9
|
+
/**
|
|
10
|
+
* External database access via Hyperdrive. Non-deterministic — available only in actions. Writes here are NOT tracked by Lunora live queries; subscriptions will not re-run on external DB changes.
|
|
11
|
+
*/
|
|
12
|
+
readonly sql: import("@lunora/hyperdrive").SqlClient;`,shardBinding:{clientType:"SqlClient",missingMessage:"ctx.sql: provide a `sql` config thunk that builds a SqlClient from your driver, e.g. `sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))`.",stubMethods:["query"]},tier:"action"},{appMethod:{configKey:"images",doc:"Override the Images binding backing `ctx.images` (defaults to `env.IMAGES`).",method:"images"},contextProperty:"images",key:"images",moduleSpecifier:"@lunora/bindings/images",requiredPackage:"@lunora/bindings",serverCtxField:`
|
|
13
|
+
/** Cloudflare Images transforms (resize/format/optimize). Non-deterministic — available only in actions. */
|
|
14
|
+
readonly images: import("@lunora/bindings/images").Images;`,shardBinding:{binding:{bindingType:"ImagesBindingLike",envName:"IMAGES",factory:{name:"createImages",option:"binding"}},clientType:"Images",missingMessage:"ctx.images: no Images binding found. Add an `images` binding (env.IMAGES) to wrangler.jsonc, or pass `images` to createShardDO().",stubMethods:["info","transform"]},tier:"action"},{appMethod:{configKey:"kv",doc:"Override the Workers KV binding backing `ctx.kv` (defaults to `env.KV`).",method:"kv"},contextProperty:"kv",key:"kv",moduleSpecifier:"@lunora/bindings/kv",requiredPackage:"@lunora/bindings",serverCtxField:`
|
|
15
|
+
readonly kv: import("@lunora/bindings/kv").Kv;`,shardBinding:{binding:{bindingType:"KVNamespaceLike",envName:"KV",factory:{name:"createKv",option:"namespace"},unvouchableReads:["get","getRaw","getWithMetadata","list"]},clientType:"Kv",missingMessage:"ctx.kv: no KV binding found. Add a `kv_namespaces` binding (env.KV) to wrangler.jsonc, or pass `kv` to createShardDO().",stubMethods:["delete","get","getRaw","getWithMetadata","list","put"]},tier:"every"},{key:"mail",moduleSpecifier:"@lunora/mail"},{contextProperty:"notify",key:"notify",moduleSpecifier:"@lunora/notify"},{appMethod:{configKey:"payment",doc:"Wire the payment options backing `ctx.payments`.",method:"payment"},contextProperty:"payments",key:"payments",moduleSpecifier:"@lunora/payment",requiredPackage:"@lunora/payment"},{appMethod:{configKey:"x402",doc:"Wire the x402 agent-wallet pay rail backing `ctx.x402` — a payment-enabled `fetch` that answers `402` challenges under a mandatory spend policy (ActionCtx-only; spends real funds).",method:"x402"},contextProperty:"x402",key:"x402",moduleSpecifier:"@lunora/x402/pay",requiredPackage:"@lunora/x402",serverCtxField:`
|
|
16
|
+
readonly x402: import("@lunora/x402/pay").X402Pay;`,shardBinding:"bespoke",tier:"action"},{contextProperty:"pipelines",key:"pipelines",moduleSpecifier:"@lunora/bindings/pipelines",requiredPackage:"@lunora/bindings",serverCtxField:`
|
|
17
|
+
/** Pipelines ingestion sink (durable, R2-backed). Fire-and-forget and batched; do not read it back in-handler. */
|
|
18
|
+
readonly pipelines: import("@lunora/bindings/pipelines").PipelineClient;`,shardBinding:{binding:{bindingType:"PipelineBindingLike",envName:"PIPELINES",factory:{name:"createPipelines",option:"binding"}},clientType:"PipelineClient",missingMessage:"ctx.pipelines: no Pipelines binding found. Add a `pipelines` binding (env.PIPELINES) to wrangler.jsonc, or pass `pipelines` to createShardDO().",stubMethods:["send"]},tier:"action"},{appMethod:{configKey:"r2sql",doc:"Wire the R2 SQL client backing `ctx.r2sql` — build it with `createR2Sql({ accountId, apiToken, bucket })` (defaults to env `R2_SQL_TOKEN` / `R2_SQL_ACCOUNT_ID` / `R2_SQL_BUCKET`).",method:"r2sql"},contextProperty:"r2sql",key:"r2sql",moduleSpecifier:"@lunora/bindings/r2sql",requiredPackage:"@lunora/bindings",serverCtxField:`
|
|
19
|
+
/**
|
|
20
|
+
* R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
|
|
21
|
+
*/
|
|
22
|
+
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,shardBinding:"bespoke",tier:"action"},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],a=n,r=n.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),o=a.map(({contextProperty:e,key:i,moduleSpecifier:t})=>({contextProperty:e,key:i,moduleSpecifier:t})),s=e=>new Set(a.filter(i=>e[i.key]).map(i=>i.key));export{r as APP_METHOD_CAPABILITIES,a as CAPABILITIES,o as CAPABILITY_PROBES,s as usedCapabilities};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as L}from"node:fs";import{join as P}from"node:path";import{containerClassName as T,containerBindingName as A,DURABLE_OBJECT_POLICY_FORBIDDEN_KEYS as j,isManagedImage as I,isCloudflareRegistryDigest as O,normalizeContainerImage as b}from"@lunora/container";import{SyntaxKind as d,Node as o}from"ts-morph";import{diagnosticAt as a}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{propertyKeyName as y,stringPropertyFor as k,findObjectProperty as p,symbolConstInitializer as C}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const D="containers.ts",M=t=>{const e=t.getSymbol();if(!e)return t.getText()==="defineContainer";for(const r of e.getDeclarations())if(o.isImportSpecifier(r))return r.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/container"?!1:r.getNameNode().getText()==="defineContainer";return!1},f=k("container"),h=(t,e,r)=>{if(o.isNumericLiteral(t))return t.getLiteralValue();throw a(t,`container "${e}": \`${r}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},E=(t,e)=>{if(o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t))return b(t.getLiteralValue());if(o.isObjectLiteralExpression(t)){const r=p(t,"registry");if(r&&o.isPropertyAssignment(r)){const i=r.getInitializerOrThrow();return b({registry:f(i,e,"image.registry")})}const n=p(t,"build");if(n&&o.isPropertyAssignment(n)){const i=n.getInitializerOrThrow();return b({build:f(i,e,"image.build")})}}throw a(t,`container "${e}": \`image\` must be a static string path, { registry: "…" }, or { build: "…" } literal`)},_=new Set(["buildArgs","image","images","instanceType","maxInstances","name","rollout","sandbox","schedulingPolicy"]),F=new Set(["gracePeriodSeconds","stepPercentage"]),v=t=>{let e=t;for(;o.isAsExpression(e)||o.isSatisfiesExpression(e)||o.isTypeAssertion(e)||o.isParenthesizedExpression(e);)e=e.getExpression();return e},B=(t,e)=>{const r=i=>{let s=i;for(;o.isPropertyAccessExpression(s)||o.isElementAccessExpression(s)||o.isParenthesizedExpression(s);)s=s.getExpression();return s===i?void 0:s},n=i=>i!==void 0&&o.isIdentifier(i)&&i.getSymbol()===t;return e.getDescendants().some(i=>{if(o.isBinaryExpression(i)){const s=i.getOperatorToken().getKind();return s>=d.FirstAssignment&&s<=d.LastAssignment&&n(r(i.getLeft()))}if(o.isPrefixUnaryExpression(i)||o.isPostfixUnaryExpression(i)){const s=i.getOperatorToken();return(s===d.PlusPlusToken||s===d.MinusMinusToken)&&n(r(i.getOperand()))}return o.isDeleteExpression(i)?n(r(i.getExpression())):o.isCallExpression(i)&&i.getExpression().getText()==="Object.assign"&&n(i.getArguments()[0])})},V=16,$=(t,e,r,n)=>{let i={name:r,symbol:t},s;for(let l=0;l<V;l+=1){const c=C(i.symbol);if(c===void 0||!o.isExpression(c))return s;if(s=v(c),o.isObjectLiteralExpression(s)&&i.symbol!==void 0&&B(i.symbol,e.getSourceFile()))throw a(e,`${n}: \`${i.name}\` is a const object that is written to elsewhere in this file, so its initializer is not the value the container runs with. Declare the settings where they are final.`);if(!o.isIdentifier(s))return s;i={name:s.getText(),symbol:s.getSymbol()}}return s},S=(t,e)=>{const r=v(t);return o.isIdentifier(r)?$(r.getSymbol(),r,r.getText(),e)??r:r},x=t=>{const e=t.getNonNullableType();return(e.isUnion()?e.getUnionTypes():[e]).flatMap(n=>n.getApparentType().getProperties().map(i=>i.getName()))},K=(t,e,r)=>{const n=t.getExpression().getType(),i=e==="every"||n.isAny()||n.isUnknown()?["its keys"]:[...new Set(x(n))].filter(s=>e.has(s)).map(s=>`\`${s}\``);if(i.length>0)throw a(t,`${r}: this spread can set ${i.join(", ")}, which codegen writes into wrangler.jsonc and so must read statically. Spread a module-scope \`const\` object literal, or write the keys inline.`)},R=(t,e,r)=>{const n=y(t),i=o.isShorthandPropertyAssignment(t)?$(t.getValueSymbol(),t,n,r):void 0;if(i!==void 0)return[n,i];if(e==="every"||e.has(n))throw a(t,`${r}: \`${n}\` is deploy configuration codegen writes into wrangler.jsonc, so it must be a static literal — inline it, or name a module-scope \`const\` initialized with one.`)},m=(t,e,r,n=new Set)=>{const i=[],s=new Set(n).add(t);for(const l of t.getProperties())if(o.isPropertyAssignment(l))i.push([y(l),S(l.getInitializerOrThrow(),r)]);else if(o.isSpreadAssignment(l))i.push(...U(l,e,r,s));else{const c=R(l,e,r);c!==void 0&&i.push(c)}return i},U=(t,e,r,n)=>{const i=S(t.getExpression(),r);if(!o.isObjectLiteralExpression(i))return K(t,e,r),[];if(n.has(i))throw a(t,`${r}: this spread refers back to an object it is part of, so it has no static value.`);return m(i,e,r,n)},z=(t,e)=>{if(!o.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`buildArgs\` must be a static object literal — it is deploy configuration codegen writes into wrangler.jsonc`);const r={};for(const[n,i]of m(t,"every",`container "${e}" buildArgs`))r[n]=f(i,e,`buildArgs.${n}`);return Object.keys(r).length>0?r:void 0},Y=(t,e)=>{if(!o.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`rollout\` must be a static object literal — it is deploy configuration codegen writes into wrangler.jsonc`);const r={};for(const[n,i]of m(t,F,`container "${e}" rollout`))(n==="gracePeriodSeconds"||n==="stepPercentage")&&(r[n]=h(i,e,`rollout.${n}`));return r.gracePeriodSeconds===void 0&&r.stepPercentage===void 0?void 0:r},w=t=>{if(o.isTrueLiteral(t))return!0;if(o.isFalseLiteral(t))return!1},q=t=>{if(o.isStringLiteral(t)||o.isNoSubstitutionTemplateLiteral(t)||o.isNumericLiteral(t))return t.getLiteralValue()},N=(t,e)=>{if(o.isStringLiteral(t))return t.getLiteralValue();if(o.isObjectLiteralExpression(t)){const r={};for(const n of t.getProperties()){if(!o.isPropertyAssignment(n))throw a(n,`container "${e}": \`instanceType\` must be an object of static number literals`);const i=y(n);if(i!=="diskMb"&&i!=="memoryMib"&&i!=="vcpu")throw a(n,`container "${e}": unknown \`instanceType\` field "${i}" — expected vcpu, memoryMib, or diskMb`);r[i]=h(n.getInitializerOrThrow(),e,`instanceType.${i}`)}return r}throw a(t,`container "${e}": \`instanceType\` must be a static string or { vcpu, memoryMib, diskMb } literal`)},H=(t,e)=>{if(!o.isObjectLiteralExpression(t))throw a(t,`container "${e}": \`images\` must be a static object literal — codegen writes it into wrangler.jsonc`);const r={};for(const[n,i]of m(t,"every",`container "${e}" images`)){const s=E(i,e);if(s.kind==="build")throw a(i,`container "${e}": \`images["${n}"]\` cannot be a Railpack { build } source — use a Dockerfile path or a { registry } reference`);if(s.kind==="registry"&&!O(s.reference))throw a(i,`container "${e}": \`images["${n}"].registry\` must be a digest-pinned (@sha256) reference under registry.cloudflare.com — push other registries' images there first`);r[n]=s}return r},J=(t,e)=>{const r=t.findLast(([i])=>i==="schedulingPolicy");if(r===void 0)return;const n=f(r[1],e,"schedulingPolicy");if(n!=="default"&&n!=="durable_object")throw a(r[1],`container "${e}": unknown \`schedulingPolicy\` "${n}" — use "default" or "durable_object"`);return n==="durable_object"?n:void 0},W=(t,e,r,n)=>{if(r!==void 0&&j.includes(t))throw a(e,`container "${n}": \`${t}\` is not supported with schedulingPolicy "durable_object"`);if(r===void 0&&t==="images")throw a(e,`container "${n}": \`images\` needs schedulingPolicy "durable_object"`)},X=(t,e,r,n)=>{const{base:i,policy:s}=r;switch(t){case"buildArgs":{i.buildArgs=z(e,n);break}case"enableInternet":{i.enableInternet=w(e);break}case"image":{r.scheduled||(s.image=E(e,n));break}case"images":{s.images=H(e,n);break}case"instanceType":{i.instanceType=N(e,n);break}case"maxInstances":{s.maxInstances=h(e,n,"maxInstances");break}case"name":{i.name=f(e,n,"name");break}case"rollout":{s.rollout=Y(e,n);break}case"sandbox":{const l=w(e);if(l===void 0)throw a(e,`container "${n}": \`sandbox\` must be a static true/false literal`);i.sandbox=l;break}case"sleepAfter":{i.sleepAfter=q(e);break}}},G=(t,e,r)=>{const n=t.findLast(([s])=>s==="image")?.[1];if(n===void 0||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();if(!Object.hasOwn(e??{},i)&&!I(i))throw a(n,`container "${r}": \`image\` "${i}" must name an entry of \`images\` or a Cloudflare-managed "cloudflare/…" image`)},Q=(t,e)=>{const r=t.getArguments()[0];if(!r||!o.isObjectLiteralExpression(r))throw a(t,`container "${e}": defineContainer must be passed an inline object literal`);const n=m(r,_,`container "${e}"`),i=J(n,e),s={base:{bindingName:A(e),className:T(e),exportName:e},policy:{},scheduled:i!==void 0};for(const[u,g]of n)W(u,g,i,e),X(u,g,s,e);const{base:l,policy:c}=s;if(i==="durable_object")return G(n,c.images,e),{...l,...c.images===void 0?{}:{images:c.images},schedulingPolicy:i};if(c.image===void 0)throw a(r,`container "${e}": defineContainer requires a static \`image\` property`);return{...l,image:c.image,...c.maxInstances===void 0?{}:{maxInstances:c.maxInstances},...c.rollout===void 0?{}:{rollout:c.rollout}}},Z=t=>{const e=[],r=new Map;for(const n of t.getVariableDeclarations()){if(!n.isExported())continue;const i=n.getInitializer();if(i?.getKind()!==d.CallExpression)continue;const s=i,l=s.getExpression();if(!o.isIdentifier(l)||!M(l))continue;const c=n.getNameNode();if(!o.isIdentifier(c))throw a(c,"defineContainer exports must be plain named exports (no destructuring)");const u=Q(s,c.getText()),g=r.get(u.bindingName);if(g!==void 0)throw a(c,`containers "${g}" and "${u.exportName}" both map to the binding ${u.bindingName} — rename one so each container gets its own Durable Object binding`);r.set(u.bindingName,u.exportName),e.push(u)}return e},oe=(t,e)=>{const r=P(e,D);if(!L(r))return[];const n=t.getSourceFile(r)??t.addSourceFileAtPath(r),i=Z(n);return i.sort((s,l)=>s.exportName.localeCompare(l.exportName)),i};export{D as CONTAINERS_FILENAME,oe as discoverContainers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";class a extends l{column;file;line;constructor(r,t,o,e){super("CODEGEN_DIAGNOSTIC",r,{location:{column:e,file:t,line:o},name:"CodegenDiagnosticError"}),this.file=t,this.line=o,this.column=e}}const m=(n,r,t)=>{const o=n.getSourceFile(),e=o.getFilePath(),s=n.getStartLineNumber(),{column:i}=o.getLineAndColumnAtPos(n.getStart()),g=`@lunora/codegen: ${r} (${e}:${s.toString()}:${i.toString()})`,c=new a(g,e,s,i);return t?Object.assign(c,t):c};export{a as CodegenDiagnosticError,m as diagnosticAt};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h,CELLD_CAPABILITIES as b}from"@lunora/platform";import{readProjectConfigLiterals as g}from"./loadProjectConfig-nNIDOrlR.mjs";const d="cloudflare",v=t=>{const{target:e}=g(t);return e!==void 0&&e.length>0?e:void 0},A=(t,e)=>e??v(t)??d,L=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=g(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${d}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${d}" }\`), or pass \`--target\`.`,target:d}]},u={celld:b,cloudflare:h,node:f},C=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),S={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:null},w=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","services","topics","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],m={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},y=(t,e,a)=>({level:"error",message:`${e.name} does not support ${m[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${m[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),k=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:c,target:i}=t;for(const s of w){if(c[s]!==!0)continue;const o=r.features[s]?.level;o!=="unsupported"&&o!==void 0||(a[s]=!1,!n.has(s)&&e.push(o==="unsupported"?y(s,r,i):T(s,r,i)))}},_=(t,e,a,r={})=>{const n={...t},c={...r},i=[],s=new Set;for(const[o,l]of Object.entries(S)){if(l===null||!t[o])continue;const p=e.features[l]?.level;p==="unsupported"?(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name} does not support "${o}" (ctx.${o}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${o} usage, or deploy to a target whose capability matrix marks "${l}" as native or emulated.`,target:a})):p===void 0&&(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${o}" (ctx.${o}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${l}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return k({diagnostics:i,gatedSignals:c,matrix:e,reported:s,signals:r,target:a}),{diagnostics:i,signals:c,usage:n}},E=(t,e,a={})=>{const r=u[e];return r===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],signals:{...a},usage:{...t}}:_(t,r,e,a)},I=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{S as CAPABILITY_TO_FEATURE,d as DEFAULT_TARGET,_ as gateAgainstMatrix,E as gatePlatformFeatures,C as platformMatrixIds,v as readProjectTarget,L as readTargetDiagnostics,A as resolveCodegenTarget,I as studioPlatformFor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as l}from"node:fs";import{join as p}from"node:path";import{Node as t}from"ts-morph";import{defaultExportExpression as g,propertyInitializer as f,findObjectProperty as c}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const d="flags.ts",u=new Set(["@lunora/flags/providers/flagship","lunorash/flags/flagship"]),m=e=>{const i=e.getSymbol();if(!i)return e.getText()==="flagshipProvider";for(const r of i.getDeclarations())if(t.isImportSpecifier(r))return u.has(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="flagshipProvider":!1;return!1},v=(e,i)=>{const r=c(e,i);if(!r||!t.isPropertyAssignment(r))return;const o=r.getInitializerOrThrow();if(t.isStringLiteral(o)||t.isNoSubstitutionTemplateLiteral(o))return o.getLiteralValue()},h=e=>{const i=e.getArguments()[0];if(i&&t.isObjectLiteralExpression(i)){const r=v(i,"binding");if(r!==void 0&&r.length>0)return{bindingName:r,mode:"binding",provider:"flagship"}}return{mode:"http",provider:"flagship"}},S=e=>f(e.getArguments()[0],"provider"),b=(e,i)=>{const r=p(i,d);if(!l(r))return;const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=g(o);if(!n||!t.isCallExpression(n))return{provider:"custom"};const s=S(n);if(s&&t.isCallExpression(s)){const a=s.getExpression();if(t.isIdentifier(a)&&m(a))return h(s)}return{provider:"custom"}};export{d as FLAGS_FILENAME,b as discoverFlags};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{G as s,I as n,a as t,d as p,i,p as o,r as d,e as E,c as I,b as T,u as c,v as y}from"./shared-DjUziztz.mjs";import"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";export{s as GENERATED_HEADER,n as IMPORT_PATH_RE,t as assertIdentifier,p as baseSpecifiers,i as isOptionalOnInsert,o as pascalCase,d as renderArgsType,E as renderInsertInterface,I as renderObjectKey,T as renderPropertyKey,c as unwrapOptional,y as validatorToType};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchemaFromNode as s,acceptsAbsent as i,objectSchemaFromNodes as o}from"@lunora/values";const c=/^-?\d+n$/u,N=t=>{if(t===void 0)return{};const e=t.trim();if(e==="true")return{const:!0};if(e==="false")return{const:!1};if(e==="null")return{const:null,type:"null"};if(e.startsWith('"')&&e.endsWith('"'))try{return{const:JSON.parse(e),type:"string"}}catch{return{const:e.slice(1,-1),type:"string"}}if(e.startsWith("'")&&e.endsWith("'"))return{const:e.slice(1,-1),type:"string"};if(c.test(e))return{const:e.slice(0,-1),format:"int64",type:"string"};const r=Number(e);return Number.isNaN(r)?{const:e}:{const:r}},n={constraints:()=>{},inner:t=>t.inner,isNullable:t=>t.column?.notNull===!1,keyChild:t=>t.keyType,kind:t=>t.kind,literalSchema:t=>N(t.literalValue),members:t=>t.members??[],shape:t=>t.shape??{},tableName:t=>t.tableName,valueChild:t=>t.valueType},O=t=>s(t,n),m=t=>o(t,n),a={...n,kind:t=>t.sourceText===void 0?n.kind(t):"from"},u=t=>i(t,a),R=["BAD_REQUEST","CONFLICT","COUNT_RLS_UNSUPPORTED","FORBIDDEN","FUNCTION_NOT_FOUND","INTERNAL","INTERNAL_SERVER_ERROR","METHOD_NOT_ALLOWED","NOT_FOUND","NOT_IMPLEMENTED","PAYLOAD_TOO_LARGE","TOO_MANY_REQUESTS","UNAUTHORIZED","UNPROCESSABLE","VALIDATION_ERROR"];export{R as LUNORA_ERROR_CODES,u as acceptsAbsentIr,N as literalConst,m as objectSchema,O as validatorIrToJsonSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as p}from"node:fs";import{join as l}from"node:path";import{Node as o,SyntaxKind as m}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as d}from"./module-specifiers-WF8iAydP.mjs";import{p as x}from"./parse-validator-C6fHL7OS.mjs";import{findObjectProperty as c}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{u as M}from"./unwrap-handler-return-DVY_kFF7.mjs";const y="mutators.ts",f=d,S=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineMutator";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return f(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineMutator":!1;return!1},N=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(m.ImportDeclaration);return i!==void 0&&f(i.getModuleSpecifierValue())}return!1},I=r=>{if(o.isIdentifier(r))return S(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(t)&&N(t)}return!1},b=r=>{const t=r.getArguments()[0];return t&&o.isObjectLiteralExpression(t)?t:void 0},A=r=>{const t=c(r,"args");if(!t||!o.isPropertyAssignment(t))return{};const e=t.getInitializer();return e&&o.isObjectLiteralExpression(e)?x(e):{}},E=r=>{const t=c(r,"server");if(!t||!o.isPropertyAssignment(t))return"unknown";const e=t.getInitializer();return!e||!(o.isArrowFunction(e)||o.isFunctionExpression(e))?"unknown":M(e)},F=r=>{const t=c(r,"owner");if(!t||!o.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&o.isStringLiteral(e)?e.getLiteralValue():void 0},P=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==m.CallExpression)continue;const n=i,a=n.getExpression();if(!I(a))continue;const s=e.getNameNode();if(!o.isIdentifier(s))throw g(s,"defineMutator exports must be plain named exports (no destructuring)");const u=b(n);t.push({args:A(u),exportName:s.getText(),filePath:"mutators",line:n.getStartLineNumber(),owner:F(u),returnType:E(u)})}return t},O=(r,t)=>{const e=l(t,y);if(!p(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=P(i);return n.sort((a,s)=>a.exportName.localeCompare(s.exportName)),n};export{y as MUTATORS_FILENAME,O as discoverMutators,I as isDefineMutatorCallee};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as x}from"node:fs";import{join as P}from"node:path";import{SyntaxKind as l,Node as c}from"ts-morph";import{listLunoraSourceFiles as p,lunoraRelativePath as g,defaultExportExpression as E,findObjectProperty as d,handlerOf as S}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{c as v}from"./classify-procedure-call-CmcShAze.mjs";const y="notify.ts",N=new Set(["chat","inApp","send","webhook"]),h=new Set(["broadcast","send"]),F=e=>{const t=e.getInitializer();if(!t||!c.isCallExpression(t))return;const o=v(t);if(!o)return;const s=S(t,o.receiver);return s?{exportName:e.getName(),handler:s,kind:o.kind}:void 0},m=e=>{const t=[];for(const o of e.getVariableStatements())if(o.isExported())for(const s of o.getDeclarations()){const r=F(s);r&&t.push(r)}return t},a=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=e.getExpression();if((t==="notify"||t==="push")&&c.isIdentifier(o)&&o.getText()==="ctx")return t;if(t==="push"&&a(o)==="notify")return"push"},A=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=a(e.getExpression());if(o==="notify"&&N.has(t))return`ctx.notify.${t}`;if(o==="push"&&h.has(t))return`ctx.push.${t}`},O=e=>c.isPropertyAccessExpression(e)?a(e.getExpression())==="push"&&h.has(e.getName()):!1,_=(e,t)=>{const o=[];for(const s of p(t)){const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),f=g(t,s);for(const n of m(r))if(!(n.kind!=="query"&&n.kind!=="mutation"))for(const i of n.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const u=A(i);u!==void 0&&o.push({callee:u,exportName:n.exportName,file:f,kind:n.kind,line:i.getStartLineNumber()})}}return o},b=(e,t)=>{for(const o of p(t)){const s=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const r of m(s))for(const f of r.handler.getDescendantsOfKind(l.PropertyAccessExpression))if(O(f))return!0}return!1},w=(e,t)=>{const o=P(t,y);if(!x(o))return;const s=e.getSourceFile(o)??e.addSourceFileAtPath(o),r=E(s);let f=!1,n=!1;if(r&&c.isCallExpression(r)){const i=r.getArguments()[0];i&&c.isObjectLiteralExpression(i)&&(f=d(i,"webPush")!==void 0,n=d(i,"fcm")!==void 0)}return{hasFcm:n,hasWebPush:f,usesPush:b(e,t)}};export{y as NOTIFY_FILENAME,_ as discoverNotifyCalls,w as discoverNotifyConfig};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{m}from"./modules-DyCocr1e.mjs";import{r as u}from"./json-data-Chfs2Cz5.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as l,objectSchema as d,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{G as R}from"./shared-DjUziztz.mjs";const h="1.3.2",g={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},f=(e,n)=>{const t=`${p(e.filePath)}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:i.map((r,a)=>({code:-32e3-a,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:d(e.args)}],result:{name:"result",schema:e.output?l(e.output):g},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},O=e=>{const n=e.version??"0.0.0",s=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream"),t=e.modules??[],r=s.map(o=>f(o,m(t,o.filePath))).toSorted((o,c)=>o.name.localeCompare(c.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:h}},E=e=>`${JSON.stringify(O(e),void 0,2)}
|
|
2
|
+
`,b=e=>`${R}export const openRpcSpec = ${u(e,"Record<string, unknown>")};
|
|
3
|
+
`;export{h as OPENRPC_VERSION,O as buildOpenRpcDocument,E as emitOpenRpc,b as emitOpenRpcModule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as i}from"node:fs";import{resolve as r}from"node:path";const f=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],c=n=>f.map(o=>r(n,o)).find(o=>i(o));export{f as PROJECT_CONFIG_FILENAMES,c as findProjectConfigFile};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as g}from"node:fs";import{join as b}from"node:path";import{LunoraError as f}from"@lunora/errors";import{queueDefaultName as y,queueBindingName as h}from"@lunora/queue";import{SyntaxKind as q,Node as a}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as d,stringPropertyFor as w}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const N="queues.ts",x=i=>{const t=e=>e==="defineQueue"||e==="defineSubscription"||e==="defineTopic",o=i.getSymbol();if(!o){const e=i.getText();return t(e)?e:void 0}for(const e of o.getDeclarations()){if(!a.isImportSpecifier(e))continue;if(e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue")return;const r=e.getNameNode().getText();return t(r)?r:void 0}},p=w("queue"),E=(i,t,o)=>{if(a.isNumericLiteral(i))return i.getLiteralValue();throw c(i,`queue "${t}": \`${o}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},S=(i,t)=>{const o=d(i,"name");if(!o||!a.isPropertyAssignment(o))return;const e=p(o.getInitializerOrThrow(),t,"name");if(e.length===0)throw c(o,`queue "${t}": \`name\` must be a non-empty string when provided`);return e},l=(i,t,o)=>{const e={bindingName:h(t),exportName:t,mode:"push",name:S(i,t)??y(t),...o===void 0?{}:{topic:o},tuning:{}},r=d(i,"mode");if(r&&a.isPropertyAssignment(r)){if(o!==void 0)throw c(r,`subscription "${t}": \`mode\` is not allowed — a subscription is always a push consumer`);const s=p(r.getInitializerOrThrow(),t,"mode");if(s!=="push"&&s!=="pull")throw c(r,`queue "${t}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(s)})`);e.mode=s}const n=d(i,"deadLetterQueue");n&&a.isPropertyAssignment(n)&&(e.tuning.deadLetterQueue=p(n.getInitializerOrThrow(),t,"deadLetterQueue"));for(const s of["maxBatchSize","maxBatchTimeout","maxRetries","retryDelay"]){const u=d(i,s);u&&a.isPropertyAssignment(u)&&(e.tuning[s]=E(u.getInitializerOrThrow(),t,s))}return e},v=(i,t)=>{const o=i.getArguments()[0];if(!o||!a.isObjectLiteralExpression(o))throw c(i,`queue "${t}": defineQueue must be passed an inline object literal`);return l(o,t,void 0)},$=(i,t,o)=>{const[e,r]=i.getArguments();if(!e||!a.isIdentifier(e)||!o.has(e.getText()))throw c(e??i,`subscription "${t}": the first argument must name a \`defineTopic()\` export of lunora/queues.ts`);if(!r||!a.isObjectLiteralExpression(r))throw c(i,`subscription "${t}": defineSubscription must be passed an inline object literal`);return l(r,t,e.getText())},I=i=>{const t=[];for(const o of i.getVariableDeclarations()){if(!o.isExported())continue;const e=o.getInitializer();if(e?.getKind()!==q.CallExpression)continue;const r=e,n=r.getExpression(),s=a.isIdentifier(n)?x(n):void 0;if(s===void 0)continue;const u=o.getNameNode();if(!a.isIdentifier(u))throw c(u,`${s} exports must be plain named exports (no destructuring)`);t.push({call:r,exportName:u.getText(),factory:s})}return t},P=i=>{const t=I(i),o=new Set(t.filter(n=>n.factory==="defineTopic").map(n=>n.exportName)),e=[];for(const n of t)n.factory==="defineQueue"?e.push(v(n.call,n.exportName)):n.factory==="defineSubscription"&&e.push($(n.call,n.exportName,o));const r=[...o].map(n=>({exportName:n}));return{queues:e,topics:r}},T=i=>{const t=new Map,o=new Map;for(const e of i){const r=t.get(e.name);if(r!==void 0)throw new f("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${e.name}": produced by both "${r}" and "${e.exportName}". Deployed queue names must be unique across the project.`,{status:500});t.set(e.name,e.exportName);const n=o.get(e.bindingName);if(n!==void 0)throw new f("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${e.bindingName}": produced by both "${n}" and "${e.exportName}". Queue export names must yield unique binding names.`,{status:500});o.set(e.bindingName,e.exportName)}},A=(i,t)=>{const o=b(t,N);if(!g(o))return{queues:[],topics:[]};const e=i.getSourceFile(o)??i.addSourceFileAtPath(o),{queues:r,topics:n}=P(e),s=r.toSorted((u,m)=>u.exportName.localeCompare(m.exportName));return T(s),{queues:s,topics:n.toSorted((u,m)=>u.exportName.localeCompare(m.exportName))}},j=(i,t)=>A(i,t).queues;export{N as QUEUES_FILENAME,A as discoverQueueDeclarations,j as discoverQueues};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{existsSync as w,mkdirSync as rn,readFileSync as cs,writeFileSync as on,rmSync as an}from"node:fs";import{join as h,dirname as he}from"node:path";import{performance as Ke}from"node:perf_hooks";import{runAdvisor as cn}from"@lunora/advisor";import{LunoraError as U}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as ln,Project as Ot}from"ts-morph";import{serializeSchemaSnapshot as un}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as dn}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as fn}from"./loadProjectConfig-nNIDOrlR.mjs";import{a as Rt,d as pn,r as gn}from"./modules-DyCocr1e.mjs";import{QUEUES_FILENAME as mn,discoverQueueDeclarations as hn}from"./QUEUES_FILENAME-RGwht3Xu.mjs";import{WORKFLOWS_FILENAME as vn,discoverWorkflows as xn}from"./WORKFLOWS_FILENAME-4-ib4HH-.mjs";import{r as En}from"./json-data-Chfs2Cz5.mjs";import{s as be}from"./paths-C-9fwEgQ.mjs";import{G as Sn}from"./shared-DjUziztz.mjs";import{CAPABILITIES as yn,usedCapabilities as An}from"./CAPABILITY_PROBES-BbW-W0N2.mjs";import{isD1GlobalTable as ls,isHyperdriveGlobalTable as us}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bn}from"./AGENTS_FILENAME-D8SgT3OR.mjs";import{discoverContainers as Nn}from"./CONTAINERS_FILENAME-C13yKxas.mjs";import wn from"./discoverCrons-BEALHx1S.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as Ne}from"./module-specifiers-WF8iAydP.mjs";import{contextPropertiesRead as Pn,discoverFeatureUsage as In}from"./sourceCapabilitySignals-oZFprILA.mjs";import Tn from"./readPackageDependencies-C6h6FZuP.mjs";import{listLunoraSourceFiles as g,propertyKeyName as x,unwrapExpression as ne,listSecurityScanFiles as we,objectLiteralFromCallbackBody as ds,propertyInitializer as b,lunoraRelativePath as m,enclosingExportName as re,bindingKeyName as Pe,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as Cn,RUN_METHODS as fs,functionReferenceSegments as ps,limitNameOf as gs,optionsObjectLiteral as ms,isContextIdentifier as Ve,handlerOf as Fn,isDatabaseAccessor as k,readTargetOf as hs}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{discoverSandboxUsage as On}from"./discoverSandboxUsage-BnsPld5I.mjs";import{resolveServiceBindings as Rn}from"./readServiceBindings-CeQvSswr.mjs";import Ln from"./discoverStorageRulesMetadata-D3Ot9g5f.mjs";import{a as S,c as B,d as vs,e as kn}from"./classify-procedure-call-CmcShAze.mjs";import{i as Dn}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as Mn,resolveCodegenTarget as xs,readTargetDiagnostics as _n,studioPlatformFor as Kn}from"./DEFAULT_TARGET-vMWzRzRF.mjs";import{b as Es,e as $n}from"./shard-CyNCZP7J.mjs";import zn from"./emitServer-BOpHpi8r.mjs";import{emitDataModel as Un}from"./emitDataModel-D3WuEZ4b.mjs";import{r as Ie,s as Bn}from"./parse-validator-C6fHL7OS.mjs";import qn from"./discoverAuthApiCalls-DoSN_yc3.mjs";import{i as jn,a as Wn,e as Vn,b as Hn,d as Gn,c as Yn}from"./unwrap-handler-return-DVY_kFF7.mjs";import Qn from"./discoverFunctions-BcBzcG5x.mjs";import Xn from"./discoverHttpRoutes-CJHS4llq.mjs";import Jn from"./discoverHyperdriveCalls-Bkbh4tG7.mjs";import Zn from"./discoverInserts-DpuLYPPd.mjs";import{m as Ze,a as Ee,s as Ss,d as er}from"./index-D7dKfGPh.mjs";import{e as ys}from"./exported-procedure-chains-D48EXUVQ.mjs";import tr from"./discoverMigrations-Dt7ywfZv.mjs";import{MUTATORS_FILENAME as sr,isDefineMutatorCallee as nr,discoverMutators as rr}from"./MUTATORS_FILENAME-DqWOgC5Z.mjs";import or from"./discoverNondeterministicCalls-CNJV2BiP.mjs";import{discoverNotifyConfig as ir,discoverNotifyCalls as ar}from"./NOTIFY_FILENAME-C1J_47et.mjs";import cr from"./discoverQueries-BcdqjYky.mjs";import lr from"./discoverR2sqlCalls-30Wtbc0P.mjs";import ur from"./discoverRlsProcedures-F4Cy-kSi.mjs";import dr from"./discoverRlsMetadata-mXBmPOGj.mjs";import fr from"./discoverSchema-D5R60b4F.mjs";import{secretKindOf as pr,redact as gr,isHeuristicSecretKind as mr,isSecretishName as hr}from"./redact-Cy14LEnc.mjs";import{discoverShapes as vr}from"./SHAPES_FILENAME-DRUFomCj.mjs";import{emitApp as xr}from"./emitApp-Cp0kB4-N.mjs";import{buildOpenApiDocument as Er,emitOpenApiModule as Sr}from"./buildOpenApiDocument-SxfElVzK.mjs";import{buildOpenRpcDocument as yr,emitOpenRpcModule as Ar}from"./OPENRPC_VERSION-Cr7Zzp6s.mjs";import{buildSchemaSnapshot as br}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Nr,emitSeed as wr,emitApi as Pr}from"./emitApi-DdW9RyGG.mjs";import{t as Ir,u as Tr,s as Cr,v as Fr}from"./shard-runtime-DMN3MgIM.mjs";import{emitCrons as Or,emitScheduler as Rr,emitShardRegistry as Lr,emitVectors as kr,emitWranglerCronTriggers as Dr}from"./emitCrons-BRKXFGFu.mjs";import Mr from"./emitDrizzleSchema-Cv0HtLR3.mjs";import _r from"./emitFunctions-BgNeOZt_.mjs";const Lt={error:"ERROR",info:"INFO",warn:"WARN"},kt={ERROR:2,INFO:0,WARN:1},Kr=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),$r=(e,t)=>{const{advisor:s}=fn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,o=n!==void 0&&Object.hasOwn(Lt,n)?Lt[n]:void 0;return o===void 0?[...t,Kr(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(r=>kt[r.level]>=kt[o])},zr={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},As=mn.replace(/\.ts$/u,""),Ur="crons",Br=vn.replace(/\.ts$/u,""),te=(e,t)=>`${be(e)}:${t}`,$e=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},qr=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${zr[t.kind]}:${t.target}`};return{exportName:t.exportName,file:t.file,kind:t.kind,line:t.line,...s}}),...e.queries.map(t=>({exportName:t.exportName,file:t.file,kind:"read",line:t.line,...$e("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({exportName:t.exportName,file:t.file,kind:"write",line:t.line,...$e("table",t.table,"written table")})),...e.workflowCalls.map(t=>({exportName:t.exportName,file:t.file,kind:"start",line:t.line,...$e("workflow",t.workflow,"workflow name")}))],jr=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{exportName:t.exportName,file:As,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,o=s??n;return{exportName:t.name,file:Ur,from:`cron:${t.name}`,kind:"trigger",line:0,...o===void 0?{reason:"the cron has no target"}:{to:o}}})],Wr=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),ze=(e,t)=>t===void 0?e:{...e,module:t},Vr=e=>{const t=new Map,s=new Map,n=Wr(e.modules),o=(r,a)=>{t.set(r.id,r),a!==void 0&&s.set(a,r.id)};for(const r of e.functions){const a=te(r.filePath,r.exportName),c=`${be(r.filePath)}.${r.exportName}`;o(ze({detail:r.kind,id:`function:${a}`,kind:"function",name:c},Rt(e.modules,r.filePath)),a)}for(const r of e.httpRoutes){const a=te(r.filePath,r.exportName);o(ze({id:`http:${a}`,kind:"http",name:`${r.method} ${r.path}`},Rt(e.modules,r.filePath)),a)}for(const r of e.schema.tables)o(ze({id:`table:${r.name}`,kind:"table",name:r.name},n.get(r.name)));for(const r of e.queues){const a=r.topic===void 0?{}:{detail:"subscription"};o({...a,id:`queue:${r.exportName}`,kind:"queue",name:r.exportName},te(As,r.exportName))}for(const r of e.topics)o({id:`topic:${r.exportName}`,kind:"topic",name:r.exportName});for(const r of e.workflows)o({id:`workflow:${r.exportName}`,kind:"workflow",name:r.exportName},te(Br,r.exportName));for(const r of e.crons)o({detail:r.cron,id:`cron:${r.name}`,kind:"cron",name:r.name});for(const r of e.services){const a=r.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:r.entrypoint===void 0?a:`${a} · ${r.entrypoint}`,id:`service:${r.name}`,kind:"service",name:r.worker})}return{nodes:t,sites:s}},Hr=e=>e===""?"inside a non-exported helper":e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Gr=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=e.from??t.get(te(e.file,e.exportName));return n===void 0?{reason:Hr(e.exportName)}:s.has(e.to)?{drawn:{from:n,kind:e.kind,to:e.to}}:{reason:`${e.to} is not declared`}},Ue=e=>`${e.from}|${e.kind}|${e.to}`,Yr=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Qr=e=>{const{nodes:t,sites:s}=Vr(e),n=new Map,o=new Map;for(const r of[...jr(e),...qr(e)]){const a=Gr(r,s,t);if("drawn"in a)n.set(Ue(a.drawn),a.drawn);else{const c={file:r.file,kind:r.kind,line:r.line,reason:a.reason};o.set(Yr(c),c)}}return{edges:[...n.values()].toSorted((r,a)=>Ue(r).localeCompare(Ue(a))),nodes:[...t.values()].toSorted((r,a)=>r.id.localeCompare(a.id)),modules:e.modules.map(r=>({...r.description===void 0?{}:{description:r.description},...r.installed===!0?{installed:!0}:{},...r.ownsFolder===!1?{ownsFolder:!1}:{},name:r.name,tables:[...r.tables]})),unresolved:[...o.values()].toSorted((r,a)=>r.file.localeCompare(a.file)||r.line-a.line),version:1}},Xr=e=>`${Sn}export const architecture = ${En(e,"Record<string, unknown>")};
|
|
2
|
+
`,Jr=(e,t)=>{if(!(!t||e.jurisdiction!=="fedramp"))throw new U("CODEGEN_DIAGNOSTIC",'@lunora/codegen: the schema pins data to the "fedramp" jurisdiction, but this app uses Cloudflare Artifacts (`ctx.artifacts`), which supports only the "eu" and "us" jurisdictions. Repo data would be stored outside the declared residency. Remove the `ctx.artifacts` usage, or pin the schema to a jurisdiction Artifacts supports.')},Dt=(e,t="api")=>{const s=new Map;for(const n of e){const o=be(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 U("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})}}},Zr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>ls(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=>us(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?[]:yn)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)},eo=(e,t,s={})=>{if(t===void 0)return;const n=Zr(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
3
|
+
`);throw new U("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
4
|
+
${o}
|
|
5
|
+
|
|
6
|
+
Install them with your package manager, then re-run codegen.`)},to="env.ts",so=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Ne(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},no=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&&Ne(n.getModuleSpecifierValue())}return!1},ro=e=>{if(i.isIdentifier(e))return so(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&no(t)}return!1},oo=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!ro(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ae(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},io=(e,t)=>{const s=h(t,to);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=oo(n);if(o.length!==0){if(o.length>1)throw ae(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},bs="identity.ts",ao=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Ne(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},co=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&&Ne(n.getModuleSpecifierValue())}return!1},lo=e=>{if(i.isIdentifier(e))return ao(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&co(t)}return!1},uo=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!lo(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ae(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},fo=(e,t)=>{const s=h(t,bs);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=uo(n);if(o.length!==0){if(o.length>1)throw ae(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},po=new Set(["allowedHosts","deniedHosts","interceptHttps"]),go=(e,t)=>{const s=ne(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return ne(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},mo=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(x(s));if(!i.isPropertyAssignment(s)||!t.has(x(s)))return!1;const n=ne(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),ho=new Set(["durable"]),vo=new Set(["rollback"]),xo=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},Eo=new Map([["defineContainer",{keys:po,signal:"containerEgressPolicy"}],["defineStep",{keys:vo,signal:"workflowRollback"}],["stream",{keys:ho,signal:"durableStreams"}]]),So=(e,t)=>{const s=Eo.get(xo(t));if(s!==void 0)return t.getArguments().some(n=>mo(go(e,n),s.keys))?s.signal:void 0},yo=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Pn(o).has("secrets"));for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=So(o,r);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},Ao="createWorker",bo="extend",Mt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,_t=e=>{const t=[],s=Mt(b(e,"backupCron"));s!==void 0&&t.push(s);const n=b(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=Mt(o.getNameNode());r!==void 0&&t.push(r)}return t},No=e=>{const t=S(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Ao)return i.isObjectLiteralExpression(s)?_t(s):[];if(t!==bo||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=ds(s.getBody());return n===void 0?[]:_t(n)},wo=(e,t)=>{const s=[];for(const{filePath:n}of we(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...No(r))}return[...new Set(s)]},Ns=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Ns(e.inner)},Po=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=Ns(n);return o!==void 0&&t.has(o)}))},Io=(e,t)=>{const s=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const r=s.get(o.name);if(r!==void 0)throw new U("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${r} and agent "${o.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(o.className);if(a!==void 0)throw new U("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${a} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},To=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=fo(s,t),a=io(s,t),c=xn(s,t),{queues:u,topics:d}=hn(s,t),p=Rn(n),v=bn(s,t);Io(c,v);const y=Nn(s,t),L=Ln(s,t),D=wn(s,t,c,v),M=wo(s,t),A=yo(s,t),I=On(s,t),$=In(s,t);$.browser=$.browser||I.usesSandboxBrowser;const q=Mn($,xs(n,e.target),{agents:v.length>0,commitOrderedTables:o.tables.some(P=>P.commitOrdered===!0),cronTriggers:D.length>0,crossShardFanout:o.tables.some(P=>Dn(P)),containerEgressPolicy:A.containerEgressPolicy,containerRuntimeScheduling:y.some(P=>P.schedulingPolicy==="durable_object"),containerSandboxTools:y.some(P=>P.sandbox===!0),durableStreams:A.durableStreams,globalTables:o.tables.some(P=>P.shardMode==="global"),queues:u.length>0,relationGraph:Po(o),secrets:A.secrets,services:p.length>0,topics:d.length>0,vectorStore:o.vectorIndexes.length>0,workerLoaders:I.usesSandboxLoader,workflowRollback:A.workflowRollback,workflowSchedules:c.some(P=>P.schedules!==void 0)}),T=q.usage,G=An(T),J=q.signals.vectorStore!==!1,Z=q.signals.services===!1?[]:p,Y=Tn(n),ce=Y??new Set,z=ce.has("lunorash");eo(o,Y,{hasVectors:J,scheduler:T.scheduler||D.length>0,storage:T.storage||L.rules.length>0||Object.keys(Es(o)).length>0,usage:T});const O=w(h(t,"flags.ts")),R=w(h(t,"notify.ts"));return{agents:v,capabilities:G,containers:y,crons:D,dataModelContent:Un(o),declaredDependencies:Y,dependencies:ce,entryCronTriggers:M,env:a,featureUsage:T,hasFlags:O,hasNotify:R,identity:r,platformGate:{...q,diagnostics:[..._n(n,e.target),...q.diagnostics]},queues:u,serverContent:zn({agents:v,capabilities:G,containers:y,env:a,hasVectors:J,hasFlags:O,hasNotify:R,identity:r,queues:u,schema:o,generatedDirectory:h(t,"_generated"),services:Z,storageRuleBuckets:L.rules.map(P=>P.bucket),topics:d,useUmbrella:z,workflows:c}),services:Z,storageRulesMetadata:L,topics:d,usesSandbox:I.usesSandboxBrowser||I.usesSandboxContainer||I.usesSandboxFs,useUmbrella:z,workflows:c}},ws=new Set(["delete","get","head","options","patch","post","put"]),Co=new Set(["handler","stream"]),Fo=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Kt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Oo=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ws.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()}},Ro=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)||ws.has(n.getName()))break;s=n.getExpression()}return Oo(s)},Lo=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Kt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Kt.has(s.getText()))return!0}return!1},ko=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Co.has(n.getName()))return;const o=Ro(s);if(!o||!Fo.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&Lo(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Do=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=ko(o,t);r&&s.push(r)}return s},Mo=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Do(o,m(t,n)))}return s},_o=e=>{const t=e.getText(),s=n=>{const o=n.getNameNode();return i.isIdentifier(o)&&o.getText()===t};for(const n of e.getAncestors())if(!(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)&&!i.isFunctionDeclaration(n)))for(const o of n.getParameters()){const r=o.getDescendantsOfKind(l.BindingElement).find(a=>s(a));if(r!==void 0)return r}},Ko=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isObjectBindingPattern(s))return;const n=s.getParent();if(i.isBindingElement(n)){t=n;continue}return i.isParameterDeclaration(n)?Pe(t):void 0}},$t=(e,t)=>{const s=e.getParent();if(i.isPropertyAccessExpression(s)&&s.getNameNode()===e||i.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=_o(e);return n!==void 0&&Ko(n)===t},et=(e,t)=>i.isIdentifier(e)?$t(e,t):e.getDescendantsOfKind(l.Identifier).some(s=>$t(s,t)),Be=e=>et(e,"ctx"),$o=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},He=e=>et(e,"args"),_=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),u=a.getStart();c!==void 0&&u<n&&u>r&&(o=c,r=u)}return o},K=e=>{if(He(e))return!0;const t=_(e);return t!==void 0&&He(t)},zo=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=_(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},W=e=>{if(Be(e))return!0;const t=_(e);if(t!==void 0&&Be(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(l.Identifier)).some(o=>{const r=_(o);return r!==void 0&&Be(r)})},ve=(e,t)=>et(e,t),Uo=(e,t)=>{if(ve(e,t))return!0;const s=_(e);if(s!==void 0&&ve(s,t))return!0;const n=$o(e);if(n!==void 0){const o=_(n);return o!==void 0&&ve(o,t)}return!1},E=e=>re(e)||"<module>",Bo=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",qo=(e,t)=>{if(!Bo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!K(s)||W(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},jo=(e,t)=>F(e,t,qo),Wo=new Set(["generateText","streamText"]),Vo=new Set(["messages","prompt","system"]),Ho=[{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"]}],Go=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of Ho)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Yo=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Go(t);if(s!==void 0)return s}},Qo=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=Pe(r),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Xo=e=>{if(He(e))return!0;const t=Qo(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Jo=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Vo.has(x(t)))continue;const s=t.getInitializer();if(s!==void 0&&Xo(s))return!0}return!1},Zo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());if(o===void 0||!Wo.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(S(c.getExpression())==="tool"&&(a=Yo(c),a!==void 0))break;a!==void 0&&s.push({exportName:E(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Jo(r)})}return s},ei=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Zo(o,m(t,n)))}return s},ti=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},si=(e,t)=>{if(!ti(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!K(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},ni=(e,t)=>F(e,t,si),tt=(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=Ie(s.getExpression());return n===void 0||tt(n,t)})}finally{t.delete(e)}},ri=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=C(t,"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:Ie(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:tt(o)}},oi=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)?Ie(r):void 0;a===void 0?s=!0:(t.push(a),s||=tt(a))}n=o.getExpression()}return{objects:t,opaque:s}},st=(e,t)=>t?oi(t):ri(e),Ps=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=Ie(s.getExpression());return n===void 0?[]:Ps(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[x(s)]:[]})}finally{t.delete(e)}},ii=e=>e.flatMap(t=>Ps(t,new Set)),ai=new Set(["check","length","max"]),Ge=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},ci=e=>[e,...e.getDescendants()].filter(t=>Ge(t)!==void 0),li=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(ai.has(s.getName()))return!0;t=n}},ui=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=ci(r),c=x(o);a.some(u=>Ge(u)==="any")?t.push(c):a.some(u=>Ge(u)==="string"&&!li(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},di=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=B(s);if(n?.visibility!=="public")return;const{objects:o}=st(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=ui(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},fi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=di(o,t);r&&s.push(r)}return s},pi=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...fi(o,m(t,n)))}return s},qe=e=>e?.getKind()===l.TrueKeyword,gi=e=>e?.getKind()===l.FalseKeyword,mi=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,hi=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),vi=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),xi=e=>e!==void 0&&i.isCallExpression(e)&&hi.has(S(e.getExpression())??""),Ei=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Si=e=>{const t=b(e,"advanced"),s=b(e,"emailAndPassword"),n=b(e,"session");return{analyzable:!0,disableCsrfCheck:qe(b(t,"disableCSRFCheck")),emailPasswordEnabled:qe(b(s,"enabled")),requireEmailVerification:qe(b(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:vi(b(e,"plugins"))&&xi(b(e,"database")),secureCookiesDisabled:gi(b(t,"useSecureCookies")),sessionFreshAgeZero:mi(b(n,"freshAge")),trustedOriginsWildcard:Ei(b(e,"trustedOrigins"))}},yi=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Ai=(e,t)=>{if(S(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?Si(s):yi();return{exportName:E(e),file:t,line:e.getStartLineNumber(),...o}},bi=(e,t)=>Cn(e,t,Ai),Ni=(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},wi=(e,t,s)=>{const n=Ni(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!K(o)||W(o))&&!(s.requireUnmodifiedReach===!0&&!zo(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:n}},Pi=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=wi(o,t,s);r&&n.push(r)}return n},Te=(e,t,s)=>{const n=[];for(const o of g(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Pi(r,m(t,o),s))}return n},Ii=new Set(["content","pdf","scrape","screenshot"]),Ti=(e,t)=>Te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ii}),Is=e=>{const t=ps(e);return t===void 0?void 0:`${be(t.slice(0,-1).join("/"))}:${String(t.at(-1))}`},Ts=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Ci=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},Fi=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Oi=(e,t)=>{const s=Is(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:"the function reference is not a static api.* / internal.* chain"}:void 0},Ri=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,o]=e.getArguments();if(fs.has(s))return Oi(s,n);if((s==="runAfter"||s==="runAt")&&Ci(t)){const c=Is(o);return c===void 0?{kind:"schedule",reason:"the scheduled function is not a static api.* / internal.* chain"}:{kind:"schedule",target:c}}const r=Fi.get(s),a=r===void 0?void 0:Ts(t,r.surface);return r===void 0||a===void 0?void 0:{kind:r.kind,target:a}},Li=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Ri(a);c!==void 0&&s.push({...c,exportName:re(a),file:r,line:a.getStartLineNumber()})}for(const a of o.getDescendantsOfKind(l.PropertyAccessExpression)){const c=Ts(a,"services");c!==void 0&&s.push({exportName:re(a),file:r,kind:"invoke",line:a.getStartLineNumber(),target:c})}}return s},ki=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Di=new Set(["RateLimiter"]),Mi=new Set(["extend"]),zt="lunora",_i=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Cs=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=x(o);t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(x(o))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Ye=e=>e&&i.isObjectLiteralExpression(e)?Cs(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Ki=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&ds(t.getBody());return s?Cs(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},$i=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());o!==void 0&&(ki.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ye(n.getArguments()[0])}):Mi.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ki(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=S(n.getExpression());o===void 0||!Di.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ye(n.getArguments()[0])})}return s},zi=(e,t)=>{for(const s of _i){const n=h(t,s);if(!w(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))S(a.getExpression())===zt&&r.push({callee:zt,file:s,line:a.getStartLineNumber(),...Ye(a.getArguments()[0])});return r}return[]},Ui=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of we(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...$i(r,n))}return s.push(...zi(e,he(t))),s},Ut="ctx.containers.",Bi=e=>{if(!e.startsWith(Ut))return!1;const t=e.slice(Ut.length);return t.length>0&&!t.includes(".")},qi=(e,t)=>Te(e,t,{argIndex:0,matchReceiver:Bi,methods:new Set(["get"])}),ji=new Set(["allow","deny","setAllowed"]),Wi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=C(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Vi=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Wi(e)))return{detail:"enableInternet: true",exportName:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Hi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!ji.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Gi=(e,t)=>Vi(e,t)??Hi(e,t),Yi=(e,t)=>F(e,t,Gi),Qi=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Xi=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Qi.has(s)?s:void 0},Ji=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=x(n);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(x(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Zi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of we(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Xi(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?Ji(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},ea=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ta=new Set(["dbRateLimit","rateLimit"]),sa=e=>{const t=ms(e);if(!t)return!1;const s=C(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},na=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const n=ea.get(s);if(n!==void 0)return{callee:s,exportName:E(e),failOpen:sa(e.getArguments()[n]),file:t,limitName:ta.has(s)?gs(e):"",line:e.getStartLineNumber()}},ra=(e,t)=>F(e,t,na),oa=new Set(["boolean","number","object","string"]),ia=e=>{const t=e.getName();if(!oa.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ve(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ve(n.getExpression()))return t},aa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=ia(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},ca=(e,t)=>{const s=new Map;for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=aa(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))},la=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=B(t);if(s?.kind!=="query")return;const n=Fn(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},Bt=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},ua=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=Bt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=Bt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},da=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=ua(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},fa=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=la(o);r&&s.push(...da(r,t))}return s},pa=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...fa(o,m(t,n)))}return s},ga=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ve(t.getExpression())},ma=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},ha=(e,t)=>{if(!ga(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=ma(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:E(e),file:t,key:o,line:e.getStartLineNumber()}},va=(e,t)=>F(e,t,ha),xa=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"||jn(r))return;const a=e.getSourceFile().getFilePath();if(Wn(o,e,a)){const c=Vn(o,e,a,0,new Set);return c===void 0&&Hn(r),c}return r},Ea=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Sa=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},ya=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))Ea(a)&&s.push({file:r,indexName:Sa(a),line:a.getStartLineNumber()})}return s},oe=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Fs=e=>{const t=e.getArguments()[0],s=oe(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=C(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?oe(n.getInitializer()):void 0},Aa=new Set(["delete","get","head","options","patch","post","put"]),ba=new Set(["handler","stream"]),Na=new Set(["runAction","runMutation"]),wa=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),ie=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Os=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(Pe(s)===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},qt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:Os(s,"ctx")},jt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:Os(s,"request")},Wt=(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(Na.has(a)&&ie(c,t))return a;if(wa.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&ie(c.getExpression(),t))return`db.${a}`}},Vt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&ie(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!ie(n.getInitializer(),t))){for(const r of o.getElements())if(Pe(r)==="auth")return!0}}return!1},Pa=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Ia=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&ie(n.getExpression(),t)},Ta=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],Rs=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Ta(s)},Ca=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?Rs(t,a.getText()):[]}return[]},Fa=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=Rs(s,t.getText());return n.length>0?n:Ca(t,s)},Ht=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>Ia(o,t)&&Fa(o).some(r=>Pa.test(r)))},Oa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ba.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(Aa.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},Ra=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=oe(e.getArguments()[0]),u=c&&qt(c,!0);if(!c||u===void 0||Ht(c,jt(c,!0)))return;const d=Wt(c,u);return d===void 0?void 0:{exportName:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Vt(c,u),sideEffect:d}}const n=Oa(e);if(n===void 0)return;const o=oe(e.getArguments()[0]),r=o&&qt(o,!1);if(!o||r===void 0||Ht(o,jt(o,!1)))return;const a=Wt(o,r);return a===void 0?void 0:{exportName:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Vt(o,r),sideEffect:a}},La=(e,t)=>F(e,t,Ra),ka=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Da=new Set(["append","set"]),Ls=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Gt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>ka.has(S(n.getExpression())??"")&&ve(n,t)),Ma=(e,t)=>{if(Gt(e,t))return!0;const s=_(e);return s!==void 0&&Gt(s,t)},Qe=(e,t)=>Uo(e,t)&&!Ma(e,t),_a=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=_(e);return t!==void 0&&i.isNewExpression(t)&&S(t.getExpression())==="Headers"},Se=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=_(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},nt=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Qe(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Ls(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Qe(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:x(n),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=Se(n.getExpression());o!==void 0&&nt(o,t,s)}},ks=(e,t)=>{const s=Se(e);if(s===void 0)return;const n=C(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=Se(n.getInitializer());o!==void 0&&nt(o,"response-init",t)},Ka=(e,t)=>{const s=S(e.getExpression());if(s==="Response")ks(e.getArguments()[1],t);else if(s==="Headers"){const n=Se(e.getArguments()[0]);n!==void 0&&nt(n,"headers-ctor",t)}},$a=(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"){ks(e.getArguments()[1],t);return}if(Da.has(n)&&_a(o)){const r=e.getArguments()[1];r!==void 0&&Qe(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Ls(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},za=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ka(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))$a(s,t)},Ua=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=oe(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 za(n,{exportName:E(e),relativePath:t,requestName:r.getText(),rows:a}),a},Ba=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Ua(n,t));return s},qa=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ba(o,m(t,n)))}return s},ja=new Set(["auth","context.auth","ctx.auth"]),Wa="userId",Va=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(x(s))}return t},Ha=(e,t)=>{const s=h(t,bs);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(S(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Va(r):void 0}},Yt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return ja.has(e.getExpression().getText())?e:void 0},Ga=e=>{if(i.isPropertyAccessExpression(e)&&Yt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Yt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Ya=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=Ga(o);r!==void 0&&n.push({declared:r===Wa||s.has(r),exportName:E(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Qa=(e,t)=>{const s=Ha(e,t);if(s===void 0)return[];const n=[];for(const o of g(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Ya(r,m(t,o),s))}return n},Xa=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=b(s,"key");if(!(!n||!K(n)||W(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},Ja=(e,t)=>F(e,t,Xa),Za=e=>{if(i.isComputedPropertyName(e)){const t=e.getExpression();return i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return i.isStringLiteral(e)?e.getLiteralValue():e.getText()},ec=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=Za(t.getNameNode());return s===void 0||s==="namespace"}),tc=(e,t)=>{for(const{filePath:s}of we(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){const r=o.getExpression(),[a]=o.getArguments();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||ec(a)))return o}}},sc="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",nc=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ae(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${sc}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},rc=new Set(["delete","get","getRaw","getWithMetadata","put"]),oc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return Te(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:rc}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},ic=new Set(["queue","send"]),Qt=new Set(["bcc","cc","to"]),ac=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ic.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},cc=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Qt.has(x(t))&&K(n)&&!W(n)}if(!i.isPropertyAssignment(t)||!Qt.has(x(t)))return!1;const s=t.getInitializer();return s!==void 0&&K(s)&&!W(s)}):!1,lc=(e,t)=>{const s=ac(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!cc(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},uc=(e,t)=>F(e,t,lc),dc=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,fc=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?dc(e):!0,Ds=(e,t=!1)=>{for(const s of e.getProperties()){if(fc(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||Ds(n,!0))return!0}return!1},pc=(e,t)=>{for(const s of g(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of ys(n))for(const r of Ze(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||Ds(a)))return!0}}return!1},gc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=Ee(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=Ee(a);c!==void 0&&s.push({column:c,strategy:Ss(a),table:o})}}return s},mc=(e,t)=>{const s=new Map;for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of ys(o))for(const a of Ze(r))for(const c of gc(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},hc=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=Ee(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=Ee(u);if(d===void 0)continue;const p=Ss(u);p!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:p,table:a})}}return o},vc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?B(s):void 0;return n?.receiver?Ze(n.receiver).flatMap(o=>hc(o,e.getName(),t)):[]},xc=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...vc(c,r))}return s},Ec=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return k(s)},Sc=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=C(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},yc=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return nr(s.getExpression())?s:void 0},Ac=e=>{const t=yc(e),s=t===void 0?void 0:Sc(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Ec(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},bc=e=>e.getVariableDeclarations().flatMap(t=>Ac(t)),Nc=(e,t)=>{const s=h(t,sr);if(!w(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return bc(n)},wc=new Set(["delete","get","patch"]),Pc=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Ic=new Set(["auth","identity","session","user"]),Tc=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Cc=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():""},Fc=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},Oc=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Rc=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Lc=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Oc(s.getExpression(),t)&&Rc(s.getThenStatement())),kc=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!wc.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}},Dc=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},Mc=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Dc(s)==="ctx")),_c=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Tc.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Kc=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Pc.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Ic.has(t.getName()))return!0}return Mc(e)||_c(e)},$c=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=B(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=Fs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&vs(n.receiver,"use","rls"),a=Kc(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const p=Cc(d);if(p===void 0)continue;const v=Fc(d);if(v===void 0||c.has(v)||!Lc(o,v))continue;const y=kc(o,v);y!==void 0&&(c.add(v),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:y,table:p,usesRls:r,visibility:n.visibility}))}return u},zc=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...$c(c,r))}return s},Uc=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Bc=new Set(["insert","insertManyUnsafe","patch","replace"]),qc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Bc.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},jc=(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},Xt=(e,t)=>{if(i.isPropertyAccessExpression(e)){const s=e.getExpression();return i.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(i.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return i.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&i.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Wc=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(i.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!i.isVariableDeclarationList(c)||c.getDeclarationKind()!==ln.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(o=u,r=d)}return o},Vc=(e,t)=>{if(Xt(e,t))return!0;const s=Wc(e);return s!==void 0&&Xt(s,t)},Hc=(e,t,s,n,o)=>{const r=[];for(const a of e.getProperties()){let c,u;if(i.isPropertyAssignment(a)?(c=x(a),u=a.getInitializer()):i.isShorthandPropertyAssignment(a)&&(c=x(a),u=a.getNameNode()),!(c===void 0||u===void 0||!Uc.has(c))&&K(u)&&!W(u)){const d=E(s),p=o(d)===c&&Vc(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...p&&{ownerScoped:!0}})}}return r},Gc=(e,t,s)=>{const n=qc(e.getExpression());if(n===void 0)return[];const o=e.getArguments()[1];return o?jc(o,n).flatMap(r=>Hc(r,n,e,t,s)):[]},Yc=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of Gc(o,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Qc=(e,t,s=[],n=[])=>{const o=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of g(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=m(t,a);o.push(...Yc(c,u,d=>r.get(`${u}:${d}`)??{}))}return o},Xc=["providerSubscriptionId","state"],Jc=["providerEventId","processedAt"],Jt=(e,t)=>t.every(s=>s in e.shape),Zc=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Jt(t,Xc)&&Jt(s,Jc)},el=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),tl=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,sl=e=>{const t=C(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?tl(t.getInitializer()):void 0},nl=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!el.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?sl(n):void 0;return{callee:s,exportName:E(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},rl=(e,t)=>F(e,t,nl),ol=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),il=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},al=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=C(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const o=n.getInitializer();if(o&&(i.isArrowFunction(o)||i.isFunctionExpression(o)))return o},Ms=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},_s=(e,t)=>e===t||e.startsWith(`${t}.`),Ks=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Zt=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)},$s=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Zt(s));return i.isIdentifier(e)&&Zt(e)&&t.push(e),t},cl=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},ll=e=>{const t=Ms(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},ul=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:ll(e),o=new Set,r=a=>Ks(a).some(c=>n.some(u=>_s(c.getText(),u)))?!0:$s(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 cl(a))o.add(u)}return{names:o,prefixes:n}},dl=(e,t)=>Ks(e).some(s=>t.prefixes.some(n=>_s(s.getText(),n)))?!0:$s(e).some(s=>t.names.has(s.getText())),fl=e=>{const t=ps(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},pl=(e,t,s)=>{const n=Ms(e,0);if(n===void 0)return[];const o=ul(e,t,n),r=new Set([n,...o.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(l.CallExpression)){const u=c.getExpression();if(!i.isPropertyAccessExpression(u)||!fs.has(u.getName())||!r.has(u.getExpression().getText()))continue;const d=c.getArguments()[1];if(!d||!dl(d,o))continue;const p=fl(c.getArguments()[0]);p!==void 0&&a.push({dispatchKind:t,file:s,handlerExport:E(c),line:c.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return a},gl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=il(n),r=o===void 0?void 0:ol.get(o);if(r===void 0)continue;const a=al(n,r);a!==void 0&&s.push(...pl(a,o==="defineWorkflow"?"workflow":"queue",t))}return s},ml=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...gl(o,m(t,n)))}return s},es={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},ts=new Set(["account","credential","member","passkey","session","user"]),hl=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),vl=e=>{const s=hl(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return ts.has(s)||ts.has(n)},xl=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},El=(e,t)=>{const{objects:s,opaque:n}=st(e,t);return ii(s).some(o=>xl(o))?!0:n?void 0:!1},Sl=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!C(t,"captcha"),usesRateLimit:!!C(t,"rateLimit")}},yl=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},xe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Al=e=>{const t=yl(e),s=t?S(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Sl(t);return{...xe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in es?{...xe,[es[s]]:!0}:xe},bl=e=>{const t={...xe};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=Al(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},Nl=new Set(["insert","insertMany","insertManyUnsafe","replace"]),wl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Nl.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:vl(o.getLiteralText())},Pl=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Il=new Set(["queues","scheduler","topics","workflows"]),Tl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Pl.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Il.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Cl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return k(s)},zs=new Set(["generateObject","generateText","streamObject","streamText"]),Fl=e=>{const t=S(e.getExpression());return t!==void 0&&zs.has(t)},Ol=e=>{const t=S(e.getExpression());if(t===void 0||!zs.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!C(s,"maxOutputTokens")},Rl=new Set(["log","span","trace"]),Ll=new Set(["ai"]),kl=new Set(["email","mail"]),Dl=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),je=(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"}),Ml=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),_l=new Set(["every","filter","flatMap","forEach","map","some"]),Kl=new Set(["all","allSettled","race"]),$l=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(_l.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&Kl.has(n))return t},zl=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(Ml.has(t.getKind())){const s=$l(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Ul=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}},Bl=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}},ql=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Dl.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=Bl(n);r&&(t=!0,!zl(r)&&!Ul(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},jl=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"}),ss="lunora-advisor-exempt",Wl=/^[\s*/]+/u,Vl=/[\w-]/u,Hl=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
7
|
+
`);for(const n of s.split(`
|
|
8
|
+
`)){const o=n.replace(Wl,"");if(!o.startsWith(ss))continue;const r=o.slice(ss.length);if(Vl.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:""}},Gl=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=C(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Yl=(e,t)=>{const s=Gl(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)},Ql=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(wl(u)&&(r=!0),Tl(u)&&(t=!0),Cl(u)&&(o=!0),Fl(u)&&(s=!0),Ol(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=ql(e);return{callsMail:je(e,kl),emitsEvent:je(e,Rl),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||je(e,Ll),throwsBareError:jl(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},Xl=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=B(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?bl(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Yl(e,s);return{...r?Ql(r):{},...Hl(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:El(s,n.receiver),kind:n.kind,visibility:n.visibility}},Jl=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Xl(o,t);r&&s.push(r)}return s},Zl=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Jl(o,m(t,n)))}return s},eu=new Set(["dbRateLimit","rateLimit"]),tu=e=>i.isArrowFunction(e)?e.getBody():e,su=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},Us=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Bs=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const o=n.getParent();return!(i.isPropertyAccessExpression(o)&&o.getNameNode()===n)})},nu=(e,t)=>K(e)||t!==void 0&&Bs(e,t).some(s=>Us(s)),ru=(e,t)=>t===void 0?W(e):Bs(e,t).some(s=>!Us(s)),ou=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!eu.has(s))return;const n=b(ms(e.getArguments()[2]),"key");if(!n)return;const o=tu(n),r=su(n);if(!(!nu(o,r)||ru(o,r)))return{callee:s,exportName:E(e),file:t,limitName:gs(e),line:e.getStartLineNumber()}},iu=(e,t)=>F(e,t,ou),au=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),cu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!au.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()},lu=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()}},uu=e=>{let t=ne(e)??e;for(;i.isAwaitExpression(t);)t=ne(t.getExpression())??t.getExpression();return t},qs=(e,t=!1)=>{const s=uu(e);if(i.isIdentifier(s)){if(t)return;const n=_(s);return n===void 0?void 0:qs(n,!0)}if(i.isCallExpression(s))return cu(s)??lu(s)},du=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},fu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=B(s);if(n?.kind!=="query")return[];const o=Fs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&kn(n.receiver,"output"),a=n.receiver!==void 0&&vs(n.receiver,"use","mask"),c=new Set,u=[];for(const d of du(o)){const p=qs(d);p===void 0||c.has(p)||(c.add(p),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:p,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},pu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...fu(c,r))}return s},gu=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(x(s));return t},mu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?B(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=hs(r);if(a===void 0)continue;const c=gu(b(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},hu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...mu(c,r))}return s},ye=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ye(e.getLeft()),s=ye(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},vu=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&&ye(t)!==void 0},xu=/(?:^|\/)__tests__\//u,Eu=/\.(?:spec|test)$/u,Su=e=>xu.test(e)||Eu.test(e),yu=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return x(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Au=(e,t,s)=>mr(e)?!Su(s)&&hr(yu(t)):!0,bu=(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(vu(r))continue;const a=ye(r);if(a===void 0)continue;const c=pr(a);if(c===void 0||!Au(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:gr(a)}))}return s},Nu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...bu(o,m(t,n)))}return s},wu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?B(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=hs(r);if(a===void 0)continue;const c=b(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&K(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},Pu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...wu(c,r))}return s},Iu=new Set(["query","unsafe"]),Tu=e=>{if(!i.isPropertyAccessExpression(e)||!Iu.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"},Cu=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Fu=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Ou=(e,t)=>{if(!Tu(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Cu(s)))return{exportName:Fu(e),file:t,line:s.getStartLineNumber()}},Ru=(e,t)=>F(e,t,Ou),Lu=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],ku=e=>{for(const[t,s]of Lu)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Du=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=ku(a);c!==void 0&&s.push({file:m(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Mu=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),_u=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return Te(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Mu,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Ku=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),$u=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,zu=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=x(o);t.push(r),r==="expiresInSeconds"&&(s=$u(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(x(o))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Uu=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ku.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},Bu=(e,t)=>{const s=Uu(e.getExpression());if(s!==void 0)return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...zu(e.getArguments()[s.optionsIndex])}},qu=(e,t)=>F(e,t,Bu),ju=(e,t)=>{const s=Kn(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Wu=new Set(["delete","hardDelete","patch","replace","restore"]),Vu=new Set(["insertMany","insertManyUnsafe","patchWhere"]),Hu=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),ns=(e,t)=>{const n=e.getProperty("__table")?.getTypeAtLocation(t)?.getLiteralValue();return typeof n=="string"?n:""},Gu=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return"";const o=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return o===void 0?"":ns(o,e)}return ns(s,e)},Yu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),[o]=e.getArguments();if(k(n))return Vu.has(s)?{method:s,table:o!==void 0&&i.isStringLiteral(o)?o.getLiteralText():""}:Wu.has(s)||s==="deleteMany"||s==="patchMany"?{method:s,table:o===void 0?"":Gu(o,s)}:void 0;if(Hu.has(s)&&i.isPropertyAccessExpression(n)&&k(n.getExpression()))return{method:s,table:n.getName()}},Qu=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){const c=Yu(a),u=c===void 0?"":re(a);c!==void 0&&u!==""&&s.push({exportName:u,file:r,line:a.getStartLineNumber(),method:c.method,table:c.table})}}return s},Xu=(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"}),Ju=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||C(s,"args")===void 0)return!1}return st(e,t).opaque},Zu=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=B(a);c!==void 0&&Ju(a,c.receiver)&&s.push(Xu(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},ed=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...Zu(o,m(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},td=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ce=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),js=e=>!e.isAny(),rt=e=>{const t=e.getType();if(!js(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:td.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Ws=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Vs={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."},sd=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.`}),nd={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."},ot=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,p=d===void 0?o:sd(d),v=c===void 0?p.remediation:`${c} ${p.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 — ${p.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};\`. ${v}`:v,title:"Procedure exists at runtime but is missing from the generated API"}},rd=(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(Ce(s,t,a)||!Ws(r))continue;const c=rt(r);c!==void 0&&n.push(ot(t,a,c,r.getStartLineNumber(),Vs))}return n},od=(e,t,s)=>{if(Ce(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=rt(o.getExpression());r!==void 0&&n.push(ot(t,"default",r,o.getStartLineNumber(),Vs))}return n},id=(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(Ce(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!Ws(c))continue;const u=rt(c);u!==void 0&&n.push(ot(t,a,u,r.getStartLineNumber(),nd))}return n},ad=(e,t,s)=>[...rd(e,t,s),...od(e,t,s),...id(e,t,s)],cd=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Ce(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})),ld=({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"}),ud=(e,t,s)=>{const n=[],o=[];for(const a of g(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=m(t,a);n.push(...ad(c,u,s)),o.push(...cd(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!js(a.getType()))&&n.push(ld(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},dd=new Set(["when","where"]),We=new Set(["definePolicy","defineShape"]),fd=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return We.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 We.has(o)?o:void 0}const s=t.getText();return We.has(s)?s:void 0},pd=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Hs=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(pd(e))return"empty-object";if(i.isParenthesizedExpression(e))return Hs(e.getExpression())}},it=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),gd=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>it(t)===e),Gs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>it(t)===e),md=e=>{const t=gd(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Gs(e).length>0},hd=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>it(t)===e),Xe=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()==="",vd=(e,t)=>Xe(e)||Xe(t),xd=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),rs=e=>!Xe(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Ed=(e,t,s)=>{const n=xd.get(e);if(n!==void 0)return vd(t,s)?n==="positive"?"negative":"positive":rs(t)||rs(s)?void 0:n},se=e=>{if(i.isParenthesizedExpression(e))return se(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Ed(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=se(e.getLeft()),o=se(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},os=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}}},Sd=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},yd=e=>i.isReturnStatement(e)?e.getExpression()??e:e,Ad=e=>{const t=[];for(const s of Gs(e)){const n=se(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of hd(e)){const n=se(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?os(s.getThenStatement()):os(s.getElseStatement())??Sd(s);o!==void 0&&t.push(yd(o))}return t},bd=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Nd=(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)||!dd.has(x(r)))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&md(a))for(const c of Ad(a)){const u=Hs(c);u!==void 0&&o.push({exportName:bd(e),file:s,form:u,key:x(r),line:c.getStartLineNumber(),owner:t})}}return o},wd=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=fd(n);o!==void 0&&s.push(...Nd(n,o,t))}return s},Pd=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wd(o,m(t,n)))}return s},Id=new Set(["query","upsert","upsertNow"]),Td=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Id.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Cd=(e,t)=>{const s=Td(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=b(n,"namespace");if(!(!o||!K(o)||W(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},Fd=(e,t)=>F(e,t,Cd),Od=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"},Rd=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Ld=(e,t)=>{const s=[];for(const n of g(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=m(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Od(a))continue;const c=re(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Rd(a)})}}return s},kd=".lunora-schema.json",Je=(e,t)=>{w(e)&&cs(e,"utf8")===t||on(e,t,"utf8")},Dd=(e,t)=>{if(t===""){an(e,{force:!0});return}Je(e,t)},Md=e=>{const t=h(e,"package.json");if(w(t))try{const s=JSON.parse(cs(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},_d=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Kd=e=>{let t=w(e)?e:he(e);for(;t&&t!==he(t);){const s=h(t,"tsconfig.json");if(w(s))return s;t=he(t)}},is=e=>e.replaceAll("\\","/"),$d=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new U("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 U("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 U("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)},as=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,zd=8,Ud=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:p}=e,v=()=>Yn(()=>{const A=Qn(a,o),I=rr(a,o);return{functions:A,httpRoutes:Xn(a,o),mutators:I}});let{erased:y,value:{functions:L,httpRoutes:D,mutators:M}}=v();Dt([...L,...M].map(A=>A.filePath)),Dt(D.filter(A=>A.stream).map(A=>A.filePath),"http-stream");for(let A=1;;A+=1){const I=Pr({agents:t,functions:L,httpRoutes:D,mutators:M,useUmbrella:d,workflows:p}),$=_r({agents:t,functions:L,migrations:r,mutators:M,shapes:c,useUmbrella:d,usesSandbox:u});if(A>=zd||as(a,s,I)&&as(a,n,$))return{apiContent:I,erased:y,functions:L,functionsContent:$,httpRoutes:D,mutators:M};Ae(a,s,I),Ae(a,n,$),{erased:y,value:{functions:L,httpRoutes:D,mutators:M}}=v()}},Bd=e=>{const t=Kd(e);return t?new Ot({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ot({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Zf=(e,t)=>{const s=g(t),n=h(t,"schema.ts");w(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=>is(c))),r=is(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)}}},ep=e=>{const t=_d(),s=t?Ke.now():0,n=h(e.projectRoot,e.lunoraDirectory??"lunora"),o=h(n,"schema.ts");if(!w(o))throw new U("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??Bd(n);Bn(xa);const a=fr(r,o,e.projectRoot),{agents:c,capabilities:u,containers:d,crons:p,dataModelContent:v,dependencies:y,entryCronTriggers:L,env:D,featureUsage:M,hasFlags:A,hasNotify:I,identity:$,platformGate:q,queues:T,serverContent:G,services:J,storageRulesMetadata:Z,topics:Y,usesSandbox:ce,useUmbrella:z,workflows:O}=To({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target});nc(a,a.jurisdiction===void 0?void 0:tc(r,n)),Jr(a,M.artifacts);const R=h(n,"_generated"),P=h(R,"dataModel.ts"),Ys=h(R,"server.ts"),Qs=h(R,"api.ts"),Xs=h(R,"functions.ts");Ae(r,P,v),Ae(r,Ys,G);const le=tr(r,n),Q=vr(r,n),{apiContent:at,erased:Js,functions:j,functionsContent:ct,httpRoutes:Fe,mutators:ue}=Ud({agents:c,apiPath:Qs,generatedFunctionsPath:Xs,lunoraDirectory:n,migrations:le,project:r,shapes:Q,useUmbrella:z,usesSandbox:ce,workflows:O}),lt=pn(r,n),Oe=gn(lt,a,[...j,...Fe].map(f=>f.filePath)),de=lt.length>0,V=e.lint===!1&&!de?void 0:{inserts:Zn(r,n),queries:cr(r,n),tableWrites:Qu(r,n),workflowCalls:Ld(r,n)},fe=e.lint===!1||V===void 0?void 0:dn({adminRoutes:Mo(r,n),aiRawRuns:jo(r,n),aiToolSideEffects:ei(r,n),argumentDerivedFetches:ni(r,n),argumentValidators:pi(r,n),authApiCalls:qn(r,n),authConfigs:bi(r,n),browserUrlAccesses:Ti(r,n),configCalls:Ui(r,n),containerKeyAccesses:qi(r,n),containerOverrides:Yi(r,n),containers:d,exportSinks:Zi(r,n),staleMigrationImports:Du(r,n),failOpenGuards:ra(r,n),flagReads:pa(r,n),flagSecurityDefaults:va(r,n),geoIndexUsages:ya(r,n),httpActionGuards:La(r,n),httpHeaderWrites:qa(r,n),hyperdriveCalls:Jn(r,n),identityClaimReads:Qa(r,n),imageDeliveryUrlAccesses:Ja(r,n),inserts:V.inserts,kvKeyAccesses:oc(r,n,j),mailRecipientAccesses:uc(r,n),maskProcedures:er(r,n),maskStrategies:xc(r,n),mutatorWrites:Nc(r,n),nondeterministicCalls:or(r,n),normalizeIdAuthorizations:zc(r,n),notifyCalls:ar(r,n),notifyConfig:ir(r,n),mutators:ue,ownerFieldWrites:Qc(r,n,j,ue),unrestrictedWhereBranches:Pd(r,n),paymentWebhooks:rl(r,n),privilegedDispatches:ml(r,n),procedureProtections:Zl(r,n),queries:V.queries,queues:T,r2sqlCalls:lr(r,n),ratelimitKeySelectors:iu(r,n),rawRowReturns:pu(r,n),relationLoads:hu(r,n),rlsProcedures:ur(r,n),schema:a,secretLiterals:Nu(r,n),modules:Oe,shapes:Q,softDeleteReads:Pu(r,n),sqlInterpolations:Ru(r,n),storageKeyAccesses:_u(r,n,j),storageUploads:qu(r,n),tableWrites:V.tableWrites,vectorNamespaceAccesses:Fd(r,n),workflowCalls:V.workflowCalls,workflows:O,wranglerVariables:e.wranglerVariables}),ut=fe===void 0?[]:$r(e.projectRoot,[...cn(fe,{source:"static"}),...ud(r,n,{byName:new Set([...O,...T,...c,...d].map(f=>f.exportName)),byPath:new Set([...j,...ue,...Q,...le].map(f=>`${f.filePath}:${f.exportName}`))}),...ed(r,n),...Gn(Js,n)]),Zs=dr(r,n),dt=mc(r,n);$d(Q,dt,pc(r,n));const en=A?ca(r,n):[],Re=q.signals.vectorStore!==!1,ee=ju(M,{containerCount:d.length,cronCount:p.length,dependencies:y,hasPaymentTables:Zc(a.tables),queueCount:T.length,storageColumnCount:Object.keys(Es(a)).length,storageRuleCount:Z.rules.length,vectorIndexCount:a.vectorIndexes.length,target:xs(e.projectRoot,e.target),vectorStoreSupported:Re,workflowCount:O.length}),ft=t?Ke.now():0,Le=br(a,le.map(f=>f.id)),pt=$n({advisories:ut.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:fe?.procedureProtections??[],agents:c,capabilities:u,containers:d,env:D,flagKeys:en,hasFlags:A,hasNotify:I,hasVectors:Re,maskMetadata:dt,mutators:ue,queues:T,rlsMetadata:Zs,schema:a,schemaSnapshot:Le,shapes:Q,services:J,storageRules:Z,studioFeatures:ee,topics:Y,useUmbrella:z,workflows:O}),gt=Nr(Q,y.has("@lunora/db"),z),mt=Ir(d,a.jurisdiction),ht=Tr(O),vt=Cr(c),xt=Fr(T),Et=Or(p),tn=Rr(ee.scheduler),sn=Lr(a.tables,z),St=kr(a.vectorIndexes),pe=Mr(a,z),yt=wr(y.has("@lunora/seed")),ge=e.apiSpec??"openapi",ke=ge==="openapi"||ge==="both",De=ge==="openrpc"||ge==="both",At=xr({capabilities:u,emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({className:f.className,exportName:f.exportName})),hasAccess:y.has("@lunora/cloudflare-access"),hasAuth:y.has("@lunora/auth"),hasFramework:y.has("@lunora/astro")||y.has("@lunora/svelte")||y.has("@lunora/vue")||w(h(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(f=>ls(f)),hasHyperdriveGlobal:a.tables.some(f=>us(f)),hasKvIntrospector:ee.kv,hasNotify:I,hasQueue:T.some(f=>f.mode==="push"),hasScheduler:ee.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:ee.storage,hasVectors:Re,hasWorkflow:O.length>0,identity:$,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(f=>({name:f.name,shardMode:f.shardMode})),useUmbrella:z,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsArchitecture:de,wantsOpenApi:ke,wantsOpenRpc:De}),bt=Md(e.projectRoot),Nt=de?Oe:[],wt=Er({functions:j,httpRoutes:Fe,modules:Nt,version:bt}),Pt=yr({functions:j,modules:Nt,version:bt}),It=`${JSON.stringify(wt,void 0,2)}
|
|
9
|
+
`,Tt=`${JSON.stringify(Pt,void 0,2)}
|
|
10
|
+
`,me=de&&V!==void 0?Qr({...V,callEdges:Li(r,n),crons:p,functions:j,httpRoutes:Fe,modules:Oe,queues:T,schema:a,services:J,topics:Y,workflows:O}):void 0,Ct=Sr(wt),Ft=Ar(Pt),Me=h(n,kd),nn=w(Me),_e=[];if(!e.dryRun){w(R)||rn(R,{recursive:!0});const f=(H,X)=>{Je(h(R,H),X),_e.push(H)},N=(H,X)=>{Dd(h(R,H),X),X!==""&&_e.push(H)};f("app.ts",At),f("dataModel.ts",v),f("api.ts",at),f("server.ts",G),f("functions.ts",ct),f("shard.ts",pt),f("crons.ts",Et),f("vectors.ts",St),f("drizzle.global.ts",pe.global),f("drizzle.shard.ts",pe.shard),N("containers.ts",mt),N("workflows.ts",ht),N("agents.ts",vt),N("queues.ts",xt),N("scheduler.ts",tn),N("shardRegistry.ts",sn),N("seed.ts",yt),N("collections.ts",gt),N("openapi.json",ke?It:""),N("openapi.ts",ke?Ct:""),N("openrpc.json",De?Tt:""),N("openrpc.ts",De?Ft:""),N("architecture.json",me===void 0?"":`${JSON.stringify(me,void 0,2)}
|
|
11
|
+
`),N("architecture.ts",me===void 0?"":Xr(me)),(!nn||e.updateSchemaBaseline===!0)&&Je(Me,un(Le))}if(t){const f=Ke.now(),N=Math.round(f-s),H=Math.round(ft-s),X=Math.round(f-ft);console.error(`@lunora/codegen: codegen took ${N.toString()}ms (discovery ${H.toString()}ms, emit ${X.toString()}ms)`)}return{advisories:ut,advisorContext:fe,agents:c,containers:d,cronTriggers:[...new Set([...Dr(p),...L])],generated:{agents:vt,api:at,app:At,collections:gt,containers:mt,crons:Et,dataModel:v,drizzleGlobal:pe.global,drizzleShard:pe.shard,functions:ct,openApi:It,openApiModule:Ct,openRpc:Tt,openRpcModule:Ft,queues:xt,seed:yt,server:G,shard:pt,vectors:St,workflows:ht},migrations:le,outputDirectory:R,platformDiagnostics:q.diagnostics,queues:T,schemaSnapshot:Le,schemaSnapshotPath:Me,workflows:O,writtenFiles:_e}};export{kd as SCHEMA_SNAPSHOT_FILENAME,Bd as createCodegenProject,Kd as findTsconfig,Zf as refreshCodegenProject,ep as runCodegen};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const m=(e,t=2166136261)=>{let i=t;for(let o=0;o<e.length;o+=1)i^=e.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},S=e=>`${m(e,2166136261)}${m(e,16777619)}`,H=1;function w(e){const t={},i=Object.keys(e);i.sort();for(const o of i)t[o]=e[o];return t}const O=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,P=e=>S(O(e)),c=e=>typeof e=="object"&&e!==null,x=e=>c(e)&&c(e.fields)&&c(e.indexes)&&c(e.relations)&&typeof e.shardMode=="string",J=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!c(t)||t.version!==1||!c(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,r]of Object.entries(t.tables))if(!x(r))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},F=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,o)=>i===t.fields[o]),y=e=>e.unique!==void 0,p=({nullable:e,optional:t,refined:i,unique:o,...r})=>JSON.stringify(w(r)),g=e=>({form:JSON.stringify([p(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),v=e=>e.kind==="union"&&e.members?e.members.map(t=>g(t)):[g({...e,nullable:!1,optional:!1})],T=(e,t)=>{if(t.kind!=="union")return!1;const i=v(t);return v(e).every(o=>i.some(r=>r.form===o.form&&(o.refined||!r.refined)))},a=e=>{switch(e.kind){case"array":return`array(${e.of?a(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?a(e.key):"?"}, ${e.of?a(e.of):"?"})`;case"union":return(e.members??[]).map(t=>a(t)).join(" | ");default:return e.kind}},l=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),f=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),_=(e,t,i,o,r)=>{if(!(i.kind===o.kind&&(!r||p(i)===p(o))))return r&&T(i,o)?f(e,"widenedFieldShape",`field ${e}.${t} widened: ${a(i)} → ${a(o)} — every stored value stays valid`):i.kind!==o.kind?l(e,"changedFieldKind",`field ${e}.${t} changed type: ${i.kind} → ${o.kind} — add a data migration to convert existing values`):l(e,"changedFieldShape",`field ${e}.${t} changed shape: ${a(i)} → ${a(o)} — stored values were written against the old shape; add a data migration to convert them`)},j=(e,t,i,o)=>{const r=[];return i.unique!==o.unique&&r.push(o.unique===!0?l(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):f(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==o.nullable&&r.push(o.nullable===!0?f(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):l(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),i.refined!==o.refined&&r.push(o.refined===!0?l(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):f(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),r},q=(e,t,i,o)=>{const r=[],n=y(i)&&y(o),s=_(e,t,i,o,n);return s&&r.push(s),n&&r.push(...j(e,t,i,o)),i.optional&&!o.optional?r.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&o.optional&&r.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),r},E=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},A=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.fields)){const s=t.fields[r];s===void 0?o.push(E(e,r,n)):o.push(...q(e,r,s,n))}for(const r of Object.keys(t.fields))i.fields[r]===void 0&&o.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${r} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},M=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.indexes)){const s=t.indexes[r];if(s===void 0){o.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${r} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${r} on ${e}`,table:e,type:"addedIndex"});continue}F(s,n)||o.push({remediation:"code",severity:"breaking",summary:`index ${r} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const r of Object.keys(t.indexes))i.indexes[r]===void 0&&o.push({remediation:"code",severity:"breaking",summary:`removed index ${r} on ${e} — a query that used \`.withIndex("${r}")\` would break`,table:e,scope:"table",type:"removedIndex"})},C=(e,t,i,o)=>{for(const r of Object.keys(i.relations))t.relations[r]===void 0&&o.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${r}`,table:e,type:"addedRelation"});for(const r of Object.keys(t.relations))i.relations[r]===void 0&&o.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${r}`,table:e,type:"removedRelation"})},$="shardBy:_unknown_",u="global",I=(e,t)=>e===u&&t.startsWith(`${u}:`)||t===u&&e.startsWith(`${u}:`),R=(e,t,i)=>{if(t===i)return i!==$?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${$}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!I(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}},b=e=>e.memory!==void 0,k=e=>e.after??0,d=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,V=(e,t,i)=>{if(t===void 0&&i===void 0)return;const o=h=>({remediation:"backfill",scope:"table",severity:"breaking",summary:h,table:e,type:"changedTtlPolicy"}),r=h=>({remediation:"none",scope:"table",severity:"safe",summary:h,table:e,type:"changedTtlPolicy"});if(i===void 0)return r(`table ${e} dropped its TTL policy — its rows are no longer swept`);if(t===void 0)return o(`table ${e} gained a TTL policy ${d(i)} — every row already past the cutoff is deleted on the next alarm sweep; add a data migration to refresh or clear "${i.field}" on the rows written before it`);if(t.field!==i.field)return o(`table ${e} moved its TTL to a different column: ${d(t)} → ${d(i)} — rows are now expired by a column they were never written against; add a data migration to populate "${i.field}"`);const n=k(t),s=k(i);return s<n?o(`table ${e} shortened its TTL: ${d(t)} → ${d(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; add a data migration to refresh "${i.field}" on the rows that must survive`):s>n?r(`table ${e} lengthened its TTL: ${d(t)} → ${d(i)}`):void 0},L=(e,t,i)=>{const o=[];return t.memory!==i.memory&&o.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode"}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&o.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering"}:{remediation:"code",scope:"table",severity:"breaking",summary:`table ${e} is no longer .commitOrdered() — new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers before deploying`,table:e,type:"changedCommitOrdering"}),o},D=(e,t,i,o)=>{const r=R(e,t.shardMode,i.shardMode);if(r&&o.push(r),b(t)&&b(i)){o.push(...L(e,t,i));const n=V(e,t.ttl,i.ttl);n&&o.push(n)}A(e,t,i,o),M(e,t,i,o),C(e,t,i,o)},B=(e,t)=>{const i=[],o=e?.tables??{};for(const[r,n]of Object.entries(t.tables)){const s=o[r];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${r}`,table:r,type:"addedTable"});continue}D(r,s,n,i)}for(const r of Object.keys(o))t.tables[r]===void 0&&i.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${r} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:r,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const r=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${r} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:i}};export{H as SCHEMA_SNAPSHOT_VERSION,a as describeShape,q as diffExistingField,B as diffSchemaSnapshots,P as hashSchemaSnapshot,x as isValidTableSnapshot,J as parseSnapshotJson,O as serializeSchemaSnapshot,w as sortKeys};
|