@lunora/codegen 1.0.0-alpha.239 → 1.0.0-alpha.240

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as 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{CodegenDiagnosticError as E,diagnosticAt as u}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as v,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs";import{listLunoraSourceFiles as C}from"./packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs";import{CONTAINERS_FILENAME as T,discoverContainers as _}from"./packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs";import{default as L}from"./packem_shared/discoverCrons-MfKw7IFf.mjs";import{FLAGS_FILENAME as I,discoverFlags as P}from"./packem_shared/FLAGS_FILENAME-BedPDCsR.mjs";import{default as G}from"./packem_shared/discoverFunctions-BsmX-sEq.mjs";import{default as b}from"./packem_shared/discoverHttpRoutes-BcXI9CNt.mjs";import{default as y}from"./packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs";import{default as k}from"./packem_shared/discoverInserts-CFJ3IVeI.mjs";import{d as z}from"./packem_shared/index-BoaHhVtM.mjs";import{default as V}from"./packem_shared/discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs";import{NOTIFY_FILENAME as X,discoverNotifyCalls as Z,discoverNotifyConfig as $}from"./packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs";import{default as re}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as te}from"./packem_shared/queries-B-f4jO-x.mjs";import{QUEUES_FILENAME as ae,discoverQueues as ie}from"./packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs";import{default as fe}from"./packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs";import{default as pe}from"./packem_shared/discoverRlsProcedures-BO4qC77y.mjs";import{default as ne}from"./packem_shared/discoverRlsMetadata-CPmAGL0W.mjs";import{discoverSandboxUsage as xe}from"./packem_shared/discoverSandboxUsage-CrjZ6yNg.mjs";import{default as Ee}from"./packem_shared/discoverSchema-D8DBDHEg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ve}from"./packem_shared/SHAPES_FILENAME-zJgzynXR.mjs";import{default as ge}from"./packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{emitApp as Te}from"./packem_shared/emitApp-BGhO5bhT.mjs";import{isD1GlobalTable as he,isHyperdriveGlobalTable as Le}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ie,emitOpenApi as Pe,emitOpenApiModule as De}from"./packem_shared/buildOpenApiDocument-nYvBhjxu.mjs";import{OPENRPC_VERSION as Ue,buildOpenRpcDocument as be,emitOpenRpc as He,emitOpenRpcModule as ye}from"./packem_shared/OPENRPC_VERSION-Cl6P9WGv.mjs";import{DEFAULT_TARGET as ke,platformMatrixIds as We,readProjectTarget as ze,resolveCodegenTarget as Ke}from"./packem_shared/DEFAULT_TARGET-DCpDuuUM.mjs";import{loadProjectConfig as Qe,readProjectConfigLiterals as qe}from"./packem_shared/loadProjectConfig-CKsFNgn3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Je,createCodegenProject as Be,findTsconfig as Ye,refreshCodegenProject as Xe,runCodegen as Ze}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BbHApV3q.mjs";import{SchemaSnapshotParseError as er,buildSchemaSnapshot as rr,evaluateSchemaDrift as or,parseSchemaSnapshot as tr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as ar}from"./packem_shared/fingerprintSchemaSources-L3nGKDQt.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as dr,validatorIrToJsonSchema as pr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as nr,SDK_TARGETS as lr,generateSdk as xr}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as Er,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as vr}from"./packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs";import{default as gr}from"./packem_shared/emitFunctions-BqAz1ssY.mjs";import{default as Or}from"./packem_shared/emitServer-BEo_fCY8.mjs";import{e as Mr}from"./packem_shared/shard-B3LMNjIg.mjs";import{G as _r}from"./packem_shared/shared-DjUziztz.mjs";import{MESSAGE_SOLUTIONS as Lr,findSolutionByMessage as Fr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Pr,findProjectConfigFile as Dr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{y as Ur,z as br,A as Hr}from"./packem_shared/shard-runtime-B_ppYvOf.mjs";import{emitApi as jr,emitCollections as kr}from"./packem_shared/emitApi-CJ9ziZnP.mjs";import{emitCrons as zr,emitScheduler as Kr,emitVectors as Vr,emitWranglerCronTriggers as Qr}from"./packem_shared/emitCrons-mkwWkn0R.mjs";import{emitDataModel as wr}from"./packem_shared/emitDataModel-D3WuEZ4b.mjs";import{isTypedSchema as Br}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{v as AGENTS_FILENAME,T as CONTAINERS_FILENAME,E as CodegenDiagnosticError,ke as DEFAULT_TARGET,I as FLAGS_FILENAME,_r as GENERATED_HEADER,dr as LUNORA_ERROR_CODES,Lr as LUNORA_SOLUTION_RULES,q as MUTATORS_FILENAME,X as NOTIFY_FILENAME,Ue as OPENRPC_VERSION,Pr as PROJECT_CONFIG_FILENAMES,ae as QUEUES_FILENAME,Je as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,nr as SDK_LANGUAGES,lr as SDK_TARGETS,Ae as SHAPES_FILENAME,er as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Ie as buildOpenApiDocument,be as buildOpenRpcDocument,rr as buildSchemaSnapshot,Be as createCodegenProject,c as describeErrorLevelFindings,u as diagnosticAt,s as diffSchemaSnapshots,N as discoverAgents,R as discoverAuthApiCalls,_ as discoverContainers,L as discoverCrons,P as discoverFlags,G as discoverFunctions,b as discoverHttpRoutes,y as discoverHyperdriveCalls,k as discoverInserts,z as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,Z as discoverNotifyCalls,$ as discoverNotifyConfig,te as discoverQueries,ie as discoverQueues,fe as discoverR2sqlCalls,ne as discoverRlsMetadata,pe as discoverRlsProcedures,xe as discoverSandboxUsage,Ee as discoverSchema,ve as discoverShapes,ge as discoverStorageRulesMetadata,Re as discoverWorkflows,Ur as emitAgents,jr as emitApi,Te as emitApp,kr as emitCollections,br as emitContainers,zr as emitCrons,wr as emitDataModel,vr as emitDrizzleSchema,gr as emitFunctions,Pe as emitOpenApi,De as emitOpenApiModule,He as emitOpenRpc,ye as emitOpenRpcModule,Kr as emitScheduler,Or as emitServer,Mr as emitShard,Vr as emitVectors,Hr as emitWorkflows,Qr as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,or as evaluateSchemaDrift,Fr as findLunoraSolution,Dr as findProjectConfigFile,Ye as findTsconfig,ar as fingerprintSchemaSources,m as formatAdvisories,xr as generateSdk,he as isD1GlobalTable,Le as isHyperdriveGlobalTable,Br as isTypedSchema,f as lintSchema,C as listLunoraSourceFiles,Qe as loadProjectConfig,tr as parseSchemaSnapshot,We as platformMatrixIds,re as readPackageDependencies,qe as readProjectConfigLiterals,ze as readProjectTarget,Er as redact,Xe as refreshCodegenProject,Ke as resolveCodegenTarget,Ze as runCodegen,mr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,d as toAdvisorContext,pr as validatorIrToJsonSchema};
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{CodegenDiagnosticError as E,diagnosticAt as u}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as v,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs";import{listLunoraSourceFiles as C}from"./packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-FxrdBeVt.mjs";import{CONTAINERS_FILENAME as T,discoverContainers as _}from"./packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs";import{default as L}from"./packem_shared/discoverCrons-MfKw7IFf.mjs";import{FLAGS_FILENAME as I,discoverFlags as P}from"./packem_shared/FLAGS_FILENAME-BedPDCsR.mjs";import{default as G}from"./packem_shared/discoverFunctions-BsmX-sEq.mjs";import{default as b}from"./packem_shared/discoverHttpRoutes-BcXI9CNt.mjs";import{default as y}from"./packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs";import{default as k}from"./packem_shared/discoverInserts-CFJ3IVeI.mjs";import{d as z}from"./packem_shared/index-BoaHhVtM.mjs";import{default as V}from"./packem_shared/discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-B6cKrN_m.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-CSQ_GDcA.mjs";import{NOTIFY_FILENAME as X,discoverNotifyCalls as Z,discoverNotifyConfig as $}from"./packem_shared/NOTIFY_FILENAME-Cri3NT5U.mjs";import{default as re}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as te}from"./packem_shared/queries-B-f4jO-x.mjs";import{QUEUES_FILENAME as ae,discoverQueues as ie}from"./packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs";import{default as fe}from"./packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs";import{default as pe}from"./packem_shared/discoverRlsProcedures-BO4qC77y.mjs";import{default as ne}from"./packem_shared/discoverRlsMetadata-CPmAGL0W.mjs";import{discoverSandboxUsage as xe}from"./packem_shared/discoverSandboxUsage-CrjZ6yNg.mjs";import{default as Ee}from"./packem_shared/discoverSchema-D8DBDHEg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ve}from"./packem_shared/SHAPES_FILENAME-zJgzynXR.mjs";import{default as ge}from"./packem_shared/discoverStorageRulesMetadata-D8VYflWt.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{emitApp as Te}from"./packem_shared/emitApp-BGhO5bhT.mjs";import{isD1GlobalTable as he,isHyperdriveGlobalTable as Le}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ie,emitOpenApi as Pe,emitOpenApiModule as De}from"./packem_shared/buildOpenApiDocument-nYvBhjxu.mjs";import{OPENRPC_VERSION as Ue,buildOpenRpcDocument as be,emitOpenRpc as He,emitOpenRpcModule as ye}from"./packem_shared/OPENRPC_VERSION-Cl6P9WGv.mjs";import{DEFAULT_TARGET as ke,platformMatrixIds as We,readProjectTarget as ze,resolveCodegenTarget as Ke}from"./packem_shared/DEFAULT_TARGET-DCpDuuUM.mjs";import{loadProjectConfig as Qe,readProjectConfigLiterals as qe}from"./packem_shared/loadProjectConfig-CKsFNgn3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Je,createCodegenProject as Be,findTsconfig as Ye,refreshCodegenProject as Xe,runCodegen as Ze}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-IOiezeVr.mjs";import{SchemaSnapshotParseError as er,buildSchemaSnapshot as rr,evaluateSchemaDrift as or,parseSchemaSnapshot as tr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as ar}from"./packem_shared/fingerprintSchemaSources-L3nGKDQt.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as dr,validatorIrToJsonSchema as pr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as nr,SDK_TARGETS as lr,generateSdk as xr}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as Er,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as vr}from"./packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs";import{default as gr}from"./packem_shared/emitFunctions-BqAz1ssY.mjs";import{default as Or}from"./packem_shared/emitServer-BEo_fCY8.mjs";import{e as Mr}from"./packem_shared/shard-BBv6VBmX.mjs";import{G as _r}from"./packem_shared/shared-DjUziztz.mjs";import{MESSAGE_SOLUTIONS as Lr,findSolutionByMessage as Fr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Pr,findProjectConfigFile as Dr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{y as Ur,z as br,A as Hr}from"./packem_shared/shard-runtime-CM5qthZc.mjs";import{emitApi as jr,emitCollections as kr}from"./packem_shared/emitApi-CJ9ziZnP.mjs";import{emitCrons as zr,emitScheduler as Kr,emitVectors as Vr,emitWranglerCronTriggers as Qr}from"./packem_shared/emitCrons-mkwWkn0R.mjs";import{emitDataModel as wr}from"./packem_shared/emitDataModel-D3WuEZ4b.mjs";import{isTypedSchema as Br}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{v as AGENTS_FILENAME,T as CONTAINERS_FILENAME,E as CodegenDiagnosticError,ke as DEFAULT_TARGET,I as FLAGS_FILENAME,_r as GENERATED_HEADER,dr as LUNORA_ERROR_CODES,Lr as LUNORA_SOLUTION_RULES,q as MUTATORS_FILENAME,X as NOTIFY_FILENAME,Ue as OPENRPC_VERSION,Pr as PROJECT_CONFIG_FILENAMES,ae as QUEUES_FILENAME,Je as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,nr as SDK_LANGUAGES,lr as SDK_TARGETS,Ae as SHAPES_FILENAME,er as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Ie as buildOpenApiDocument,be as buildOpenRpcDocument,rr as buildSchemaSnapshot,Be as createCodegenProject,c as describeErrorLevelFindings,u as diagnosticAt,s as diffSchemaSnapshots,N as discoverAgents,R as discoverAuthApiCalls,_ as discoverContainers,L as discoverCrons,P as discoverFlags,G as discoverFunctions,b as discoverHttpRoutes,y as discoverHyperdriveCalls,k as discoverInserts,z as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,Z as discoverNotifyCalls,$ as discoverNotifyConfig,te as discoverQueries,ie as discoverQueues,fe as discoverR2sqlCalls,ne as discoverRlsMetadata,pe as discoverRlsProcedures,xe as discoverSandboxUsage,Ee as discoverSchema,ve as discoverShapes,ge as discoverStorageRulesMetadata,Re as discoverWorkflows,Ur as emitAgents,jr as emitApi,Te as emitApp,kr as emitCollections,br as emitContainers,zr as emitCrons,wr as emitDataModel,vr as emitDrizzleSchema,gr as emitFunctions,Pe as emitOpenApi,De as emitOpenApiModule,He as emitOpenRpc,ye as emitOpenRpcModule,Kr as emitScheduler,Or as emitServer,Mr as emitShard,Vr as emitVectors,Hr as emitWorkflows,Qr as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,or as evaluateSchemaDrift,Fr as findLunoraSolution,Dr as findProjectConfigFile,Ye as findTsconfig,ar as fingerprintSchemaSources,m as formatAdvisories,xr as generateSdk,he as isD1GlobalTable,Le as isHyperdriveGlobalTable,Br as isTypedSchema,f as lintSchema,C as listLunoraSourceFiles,Qe as loadProjectConfig,tr as parseSchemaSnapshot,We as platformMatrixIds,re as readPackageDependencies,qe as readProjectConfigLiterals,ze as readProjectTarget,Er as redact,Xe as refreshCodegenProject,Ke as resolveCodegenTarget,Ze as runCodegen,mr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,d as toAdvisorContext,pr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as w,mkdirSync as Ls,readFileSync as $t,writeFileSync as Ds,rmSync as ks}from"node:fs";import{join as E,dirname as ae}from"node:path";import{performance as we}from"node:perf_hooks";import{runAdvisor as Ms}from"@lunora/advisor";import{LunoraError as K}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as Ks,Project as dt}from"ts-morph";import{serializeSchemaSnapshot as _s}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as zs}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as $s}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as Us}from"./paths-C-9fwEgQ.mjs";import{C as ce}from"./capabilities-DJJWVEtk.mjs";import{isD1GlobalTable as Ut,isHyperdriveGlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Bs}from"./AGENTS_FILENAME-DoPI92Wu.mjs";import{discoverContainers as qs}from"./CONTAINERS_FILENAME-B6TFs82W.mjs";import js from"./discoverCrons-MfKw7IFf.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as pe}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,bindingKeyName as Q,propertyKeyName as S,unwrapExpression as X,listSecurityScanFiles as me,objectLiteralFromCallbackBody as qt,propertyInitializer as b,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as Vs,limitNameOf as jt,optionsObjectLiteral as Vt,isContextIdentifier as Fe,handlerOf as Ws,isDatabaseAccessor as _,readTargetOf as Wt,enclosingExportName as Hs}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import Gs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as Ys}from"./QUEUES_FILENAME-CxkPcMH1.mjs";import{discoverSandboxUsage as Qs}from"./discoverSandboxUsage-CrjZ6yNg.mjs";import Xs from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as A,c as z,d as Ht,e as Zs}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as Js}from"./WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{gatePlatformFeatures as en,resolveCodegenTarget as Gt,readTargetDiagnostics as tn,studioPlatformFor as sn}from"./DEFAULT_TARGET-DCpDuuUM.mjs";import{b as Yt,e as nn}from"./shard-B3LMNjIg.mjs";import rn from"./emitServer-BEo_fCY8.mjs";import{emitDataModel as on}from"./emitDataModel-D3WuEZ4b.mjs";import{i as k,a as U,e as y,r as an,b as cn,s as he,c as ln,f as un,d as dn}from"./queries-B-f4jO-x.mjs";import{r as ve,s as fn}from"./parse-validator-C94Yiabo.mjs";import gn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as pn,a as mn,e as hn,b as vn,d as xn,c as En}from"./unwrap-handler-return-CoV_GK33.mjs";import Sn from"./discoverFunctions-BsmX-sEq.mjs";import yn from"./discoverHttpRoutes-BcXI9CNt.mjs";import An from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import bn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Me,a as ue,s as Qt,d as Nn}from"./index-BoaHhVtM.mjs";import{e as Xt}from"./exported-procedure-chains-CmCDiPBV.mjs";import Pn from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as wn,isDefineMutatorCallee as In,discoverMutators as Tn}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import Cn from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as Fn,discoverNotifyCalls as On}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import Rn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import Ln from"./discoverRlsProcedures-BO4qC77y.mjs";import Dn from"./discoverRlsMetadata-CPmAGL0W.mjs";import kn from"./discoverSchema-D8DBDHEg.mjs";import{secretKindOf as Mn,redact as Kn,isHeuristicSecretKind as _n,isSecretishName as zn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as $n}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as Un}from"./emitApp-BGhO5bhT.mjs";import{buildOpenApiDocument as Bn,emitOpenApiModule as qn}from"./buildOpenApiDocument-nYvBhjxu.mjs";import{buildOpenRpcDocument as jn,emitOpenRpcModule as Vn}from"./OPENRPC_VERSION-Cl6P9WGv.mjs";import{buildSchemaSnapshot as Wn}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Hn,emitSeed as Gn,emitApi as Yn}from"./emitApi-CJ9ziZnP.mjs";import{z as Qn,A as Xn,y as Zn,B as Jn}from"./shard-runtime-B_ppYvOf.mjs";import{emitCrons as er,emitScheduler as tr,emitVectors as sr,emitWranglerCronTriggers as nr}from"./emitCrons-mkwWkn0R.mjs";import rr from"./emitDrizzleSchema-Cv0HtLR3.mjs";import or from"./emitFunctions-BqAz1ssY.mjs";const ft={error:"ERROR",info:"INFO",warn:"WARN"},gt={ERROR:2,INFO:0,WARN:1},ir=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"}),ar=(e,t)=>{const{advisor:s}=$s(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,o=n!==void 0&&Object.hasOwn(ft,n)?ft[n]:void 0;return o===void 0?[...t,ir(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=>gt[r.level]>=gt[o])},pt=(e,t="api")=>{const s=new Map;for(const n of e){const o=Us(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 K("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})}}},cr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>Ut(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=>Bt(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?[]:ce)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)},lr=(e,t,s={})=>{if(t===void 0)return;const n=cr(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
1
+ import{existsSync as w,mkdirSync as Ls,readFileSync as $t,writeFileSync as Ds,rmSync as ks}from"node:fs";import{join as E,dirname as ae}from"node:path";import{performance as we}from"node:perf_hooks";import{runAdvisor as Ms}from"@lunora/advisor";import{LunoraError as K}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as Ks,Project as dt}from"ts-morph";import{serializeSchemaSnapshot as _s}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as zs}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as $s}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as Us}from"./paths-C-9fwEgQ.mjs";import{C as ce}from"./capabilities-DJJWVEtk.mjs";import{isD1GlobalTable as Ut,isHyperdriveGlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Bs}from"./AGENTS_FILENAME-DoPI92Wu.mjs";import{discoverContainers as qs}from"./CONTAINERS_FILENAME-B6TFs82W.mjs";import js from"./discoverCrons-MfKw7IFf.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as pe}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,bindingKeyName as Q,propertyKeyName as S,unwrapExpression as X,listSecurityScanFiles as me,objectLiteralFromCallbackBody as qt,propertyInitializer as b,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as Vs,limitNameOf as jt,optionsObjectLiteral as Vt,isContextIdentifier as Fe,handlerOf as Ws,isDatabaseAccessor as _,readTargetOf as Wt,enclosingExportName as Hs}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import Gs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as Ys}from"./QUEUES_FILENAME-CxkPcMH1.mjs";import{discoverSandboxUsage as Qs}from"./discoverSandboxUsage-CrjZ6yNg.mjs";import Xs from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as A,c as z,d as Ht,e as Zs}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as Js}from"./WORKFLOWS_FILENAME-B_ZJxRSx.mjs";import{gatePlatformFeatures as en,resolveCodegenTarget as Gt,readTargetDiagnostics as tn,studioPlatformFor as sn}from"./DEFAULT_TARGET-DCpDuuUM.mjs";import{b as Yt,e as nn}from"./shard-BBv6VBmX.mjs";import rn from"./emitServer-BEo_fCY8.mjs";import{emitDataModel as on}from"./emitDataModel-D3WuEZ4b.mjs";import{i as k,a as U,e as y,r as an,b as cn,s as he,c as ln,f as un,d as dn}from"./queries-B-f4jO-x.mjs";import{r as ve,s as fn}from"./parse-validator-C94Yiabo.mjs";import gn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as pn,a as mn,e as hn,b as vn,d as xn,c as En}from"./unwrap-handler-return-CoV_GK33.mjs";import Sn from"./discoverFunctions-BsmX-sEq.mjs";import yn from"./discoverHttpRoutes-BcXI9CNt.mjs";import An from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import bn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Me,a as ue,s as Qt,d as Nn}from"./index-BoaHhVtM.mjs";import{e as Xt}from"./exported-procedure-chains-CmCDiPBV.mjs";import Pn from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as wn,isDefineMutatorCallee as In,discoverMutators as Tn}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import Cn from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as Fn,discoverNotifyCalls as On}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import Rn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import Ln from"./discoverRlsProcedures-BO4qC77y.mjs";import Dn from"./discoverRlsMetadata-CPmAGL0W.mjs";import kn from"./discoverSchema-D8DBDHEg.mjs";import{secretKindOf as Mn,redact as Kn,isHeuristicSecretKind as _n,isSecretishName as zn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as $n}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as Un}from"./emitApp-BGhO5bhT.mjs";import{buildOpenApiDocument as Bn,emitOpenApiModule as qn}from"./buildOpenApiDocument-nYvBhjxu.mjs";import{buildOpenRpcDocument as jn,emitOpenRpcModule as Vn}from"./OPENRPC_VERSION-Cl6P9WGv.mjs";import{buildSchemaSnapshot as Wn}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Hn,emitSeed as Gn,emitApi as Yn}from"./emitApi-CJ9ziZnP.mjs";import{z as Qn,A as Xn,y as Zn,B as Jn}from"./shard-runtime-CM5qthZc.mjs";import{emitCrons as er,emitScheduler as tr,emitVectors as sr,emitWranglerCronTriggers as nr}from"./emitCrons-mkwWkn0R.mjs";import rr from"./emitDrizzleSchema-Cv0HtLR3.mjs";import or from"./emitFunctions-BqAz1ssY.mjs";const ft={error:"ERROR",info:"INFO",warn:"WARN"},gt={ERROR:2,INFO:0,WARN:1},ir=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"}),ar=(e,t)=>{const{advisor:s}=$s(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,o=n!==void 0&&Object.hasOwn(ft,n)?ft[n]:void 0;return o===void 0?[...t,ir(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=>gt[r.level]>=gt[o])},pt=(e,t="api")=>{const s=new Map;for(const n of e){const o=Us(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 K("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})}}},cr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>Ut(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=>Bt(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?[]:ce)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)},lr=(e,t,s={})=>{if(t===void 0)return;const n=cr(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
2
2
  `);throw new K("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${o}
4
4
 
@@ -1 +1 @@
1
- import"./json-data-Chfs2Cz5.mjs";import{u as m,o as r,y as i,m as n,z as o,p as g,l as u,B as F,t as p,n as l,A as f,s as d,q as k}from"./shard-runtime-B_ppYvOf.mjs";import"./shared-DjUziztz.mjs";export{m as buildDoTypeImports,r as emitAgentFragments,i as emitAgents,n as emitContainerFragments,o as emitContainers,g as emitPaymentFragments,u as emitQueueFragments,F as emitQueues,p as emitQueuesMetadataFragments,l as emitWorkflowFragments,f as emitWorkflows,d as emitWorkflowsMetadataFragments,k as emitX402Fragments};
1
+ import"./json-data-Chfs2Cz5.mjs";import{u as m,o as r,y as i,m as n,z as o,p as g,l as u,B as F,t as p,n as l,A as f,s as d,q as k}from"./shard-runtime-CM5qthZc.mjs";import"./shared-DjUziztz.mjs";export{m as buildDoTypeImports,r as emitAgentFragments,i as emitAgents,n as emitContainerFragments,o as emitContainers,g as emitPaymentFragments,u as emitQueueFragments,F as emitQueues,p as emitQueuesMetadataFragments,l as emitWorkflowFragments,f as emitWorkflows,d as emitWorkflowsMetadataFragments,k as emitX402Fragments};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as a}from"./shard-B3LMNjIg.mjs";import"./shard-runtime-B_ppYvOf.mjs";import"./shared-DjUziztz.mjs";export{a as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as a}from"./shard-BBv6VBmX.mjs";import"./shard-runtime-CM5qthZc.mjs";import"./shared-DjUziztz.mjs";export{a as default};
@@ -1,4 +1,4 @@
1
- import{LunoraError as qt}from"@lunora/errors";import{serializeSchemaSnapshot as Nt,hashSchemaSnapshot as Ft}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ut,isD1GlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as l}from"./json-data-Chfs2Cz5.mjs";import{r as N,e as Wt,a as jt,b as Ht,c as Vt,d as Kt,f as Gt,g as Qt,h as zt,i as Xt,j as Jt,k as Yt,l as Zt,m as er,n as tr,o as rr,p as ar,q as nr,s as sr,t as or,u as ir,v as dr,w as cr,x as lr}from"./shard-runtime-B_ppYvOf.mjs";import{u as Z,i as hr,G as ur,d as pr}from"./shared-DjUziztz.mjs";const mr=` /**
1
+ import{LunoraError as Mt}from"@lunora/errors";import{serializeSchemaSnapshot as Pt,hashSchemaSnapshot as qt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nt,isD1GlobalTable as Ft}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as l}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as Ut,a as Bt,b as Wt,c as jt,d as Ht,f as Vt,g as Kt,h as Gt,i as Qt,j as zt,k as Xt,l as Jt,m as Yt,n as Zt,o as er,p as tr,q as rr,s as ar,t as nr,u as sr,v as or,w as ir,x as dr}from"./shard-runtime-CM5qthZc.mjs";import{u as J,i as cr,G as lr,d as hr}from"./shared-DjUziztz.mjs";const ur=` /**
2
2
  * The bare writer every admin/maintenance entry point writes through.
3
3
  *
4
4
  * Admin and maintenance writes go through the SAME reactive-cache hooks as a
@@ -30,7 +30,7 @@ import{LunoraError as qt}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,m=(a="")=>` const writer = this.adminWriter(${a});`,gr=`${mr}
33
+ }`,m=(a="")=>` const writer = this.adminWriter(${a});`,pr=`${ur}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -225,11 +225,11 @@ ${m()}
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,br=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,aiBuild:t,aiContextField:o,containersBuild:d,containersContextField:g,databaseOptions:b,everyContextBuild:c,everyContextField:h,facadeBlock:f,globalDatabaseLine:O,notifyBuild:F,ormContextField:U,paymentsBuild:B,paymentsContextField:T,queuesBuild:E,queuesContextField:W,vectorsBuild:C,vectorsContextField:j,workflowsBuild:H,workflowsContextField:v})=>{const L=r.length>0,i=L?`
228
+ }`,mr=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:g,everyContextField:b,facadeBlock:c,globalDatabaseLine:h,notifyBuild:f,ormContextField:D,paymentsBuild:N,paymentsContextField:F,queuesBuild:U,queuesContextField:O,vectorsBuild:T,vectorsContextField:B,workflowsBuild:E,workflowsContextField:W})=>{const C=r.length>0,w=C?`
229
229
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
230
230
  // and attached only for an \`action\` so query/mutation ctx never carry them.
231
231
  if (isAction) {
232
- ${a}${r.map(y=>` ctx.${y} = ${y};`).join(`
232
+ ${a}${r.map(i=>` ctx.${i} = ${i};`).join(`
233
233
  `)}
234
234
  }
235
235
  `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
@@ -253,7 +253,7 @@ ${a}${r.map(y=>` ctx.${y} = ${y};`).join(`
253
253
  userId: this.getCurrentUserId(),
254
254
  };
255
255
  const { identity, ip, userId } = caller;
256
- ${C}${t}${c}${d}${H}${E}${e}
256
+ ${T}${g}${t}${E}${U}${e}
257
257
  // Which dispatch this ctx belongs to. Drives the two deferral facades
258
258
  // below and the \`ctx.run*\` caller guard; a ctx built for an
259
259
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -362,13 +362,13 @@ ${C}${t}${c}${d}${H}${E}${e}
362
362
  // so both write to the same trace.
363
363
  const span = this.makeDispatchSpan(traceAnchor, observability);
364
364
 
365
- ${O} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
365
+ ${h} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
366
366
  // adds aggregate counters (call count, total time, per-operation
367
367
  // breakdown) to the wide event rather than a span per call, so a
368
368
  // handler making hundreds of queries stays readable. See
369
369
  // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
370
- const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${b}), logFunctionPath, traceAnchor, observability);
371
- ${f}${B}
370
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
371
+ ${c}${N}
372
372
 
373
373
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
374
374
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -376,7 +376,7 @@ ${f}${B}
376
376
  // writing mutation's trace from the shared per-request field.
377
377
  const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
378
378
  const metrics = this.makeMetrics(logFunctionPath, observability);
379
- ${F}
379
+ ${f}
380
380
  // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
381
381
  // captured ONCE so the whole handler body sees a single stable value.
382
382
  // A \`query\` handler is re-run by every live subscription that reads it,
@@ -419,14 +419,14 @@ ${F}
419
419
  // to the handler so code that signs its own URLs (a copy-in
420
420
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
421
421
  // query and for a deferred dispatch, for the reasons given there.
422
- origin: requestOrigin,${U}
422
+ origin: requestOrigin,${D}
423
423
  scheduler,
424
424
  span,
425
425
  storage: contextStorage,
426
- trace,${j}${o}${h}${T}${g}${v}${W}${n}
426
+ trace,${B}${b}${F}${o}${W}${O}${n}
427
427
  };
428
- ${L?` const isAction = contextKind === "action";
429
- `:""}${i}
428
+ ${C?` const isAction = contextKind === "action";
429
+ `:""}${w}
430
430
  const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
431
431
  target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind);
432
432
  // The composed mutation runs under the SAME wrapper the top-level RPC
@@ -477,7 +477,7 @@ ${L?` const isAction = contextKind === "action";
477
477
 
478
478
  if (queryView === undefined) {
479
479
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
480
- ${r.map(y=>` delete descriptors.${y};
480
+ ${r.map(i=>` delete descriptors.${i};
481
481
  `).join("")} // Writable and configurable, like the plain fields they replace.
482
482
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
483
483
 
@@ -496,7 +496,7 @@ ${r.map(y=>` delete descriptors.${y};
496
496
  installRun(ctx, contextKind);
497
497
 
498
498
  return ctx;
499
- }`},fr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
499
+ }`},gr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
500
500
  // referencing call fails loudly with a clear error instead of overflowing the
501
501
  // stack. Tracked across the awaited handler chain (one DO invocation is
502
502
  // single-threaded), so the counter reflects true nesting depth.
@@ -562,7 +562,7 @@ const dispatchRun = async (
562
562
  } finally {
563
563
  runDepth -= 1;
564
564
  }
565
- };`,wr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
565
+ };`,br=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
566
566
  const registered = LUNORA_FUNCTIONS[functionPath];
567
567
 
568
568
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -739,7 +739,7 @@ const dispatchRun = async (
739
739
  // \`ctx.scheduler\` call that reached the buffer in the first place.
740
740
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
741
741
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
742
- }`,yr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
742
+ }`,fr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
743
743
  const registered = LUNORA_FUNCTIONS[functionPath];
744
744
 
745
745
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -778,7 +778,7 @@ const dispatchRun = async (
778
778
  // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
779
779
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
780
780
  };
781
- }`,vr=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=Z(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},kr=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))Z(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},Sr=a=>{const r={};for(const e of a.tables){const n=[...e.indexes.map(t=>({fields:[...t.fields],name:t.name,type:"index",...t.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(t=>({fields:[t.field,...t.filterFields??[]],name:t.name,type:"search"})),...(e.geoIndexes??[]).map(t=>({fields:[t.field],name:t.name,type:"geo"})),...e.rankIndexes.map(t=>({fields:t.sortBy.map(o=>o.field),name:t.name,type:"rank"})),...e.vectorIndexes.map(t=>({fields:t.field===void 0?[]:[t.field],name:t.name,type:"vector"}))];n.length>0&&(r[e.name]=n)}return r},Rr=a=>{const r=[];for(const e of a.tables)!e.ttl||e.shardMode==="global"||r.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return r},xr=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const r=[];for(const e of a.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const n=JSON.parse(e.literalValue);if(typeof n!="string")return;r.push(n)}catch{return}}return r},Ar=(a,r,e)=>{const n=Z(r),t={name:a,optional:hr(r),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){t.ref=n.tableName;const d=e.get(a);d!==void 0&&(t.onDelete=d)}n.kind==="storage"&&(t.isStorage=!0,n.bucket!==void 0&&(t.bucket=n.bucket));const o=xr(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},Dr=a=>{const r={};for(const e of a.tables){const n=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],t=new Map(e.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,d]of Object.entries(e.shape))n.push(Ar(o,d,t));r[e.name]=n}return r},Or=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
781
+ }`,wr=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=J(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},yr=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))J(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},vr=a=>{const r={};for(const e of a.tables){const n=[...e.indexes.map(t=>({fields:[...t.fields],name:t.name,type:"index",...t.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(t=>({fields:[t.field,...t.filterFields??[]],name:t.name,type:"search"})),...(e.geoIndexes??[]).map(t=>({fields:[t.field],name:t.name,type:"geo"})),...e.rankIndexes.map(t=>({fields:t.sortBy.map(o=>o.field),name:t.name,type:"rank"})),...e.vectorIndexes.map(t=>({fields:t.field===void 0?[]:[t.field],name:t.name,type:"vector"}))];n.length>0&&(r[e.name]=n)}return r},kr=a=>{const r=[];for(const e of a.tables)!e.ttl||e.shardMode==="global"||r.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return r},Sr=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const r=[];for(const e of a.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const n=JSON.parse(e.literalValue);if(typeof n!="string")return;r.push(n)}catch{return}}return r},Rr=(a,r,e)=>{const n=J(r),t={name:a,optional:cr(r),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){t.ref=n.tableName;const d=e.get(a);d!==void 0&&(t.onDelete=d)}n.kind==="storage"&&(t.isStorage=!0,n.bucket!==void 0&&(t.bucket=n.bucket));const o=Sr(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},xr=a=>{const r={};for(const e of a.tables){const n=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],t=new Map(e.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,d]of Object.entries(e.shape))n.push(Rr(o,d,t));r[e.name]=n}return r},Ar=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
782
782
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
783
783
  const shape = LUNORA_SHAPES[name];
784
784
 
@@ -849,7 +849,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
849
849
  protected override isCustomMutator(functionPath: string): boolean {
850
850
  return LUNORA_MUTATOR_PATHS.has(functionPath);
851
851
  }
852
- `:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},Tr=(a,r)=>a?`
852
+ `:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},Dr=(a,r)=>a?`
853
853
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
854
854
  const env = this.env as Record<string, unknown>;
855
855
  // A shape read performs no writes, so the widened request only needs
@@ -908,7 +908,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
908
908
 
909
909
  return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
910
910
  }
911
- `:"",Er=a=>({externalSourceOverride:a?`
911
+ `:"",Or=a=>({externalSourceOverride:a?`
912
912
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
913
913
  const env = (this.env ?? {}) as Record<string, unknown>;
914
914
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1061,7 +1061,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
1061
1061
  `:"",sourceClientCacheConst:a?`
1062
1062
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1063
1063
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1064
- `:""}),Cr=(a,r)=>{const e=r.length>0,t=a?N("vectorsStub: VectorSearchLike",'throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',["deleteByIds","getByIds","query","upsert","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
1064
+ `:""}),Tr=(a,r)=>{const e=r.length>0,t=a?q("vectorsStub: VectorSearchLike",'throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',["deleteByIds","getByIds","query","upsert","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
1065
1065
  `:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",b=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${r.map(f=>JSON.stringify(f)).join(", ")}]`]:[]].join(", ")} }`,c=a?`
1066
1066
  const vectorSync = this.vectorSync(env);
1067
1067
  // Vectorize lives outside this shard's SQLite, so a query whose result
@@ -1105,14 +1105,14 @@ ${o} const vectors = createContextVectors(lunora${b});
1105
1105
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1106
1106
  });
1107
1107
  }
1108
- `:"",vectorsBuild:c,vectorsStub:t}},Br=({advisories:a=[],advisorProcedures:r=[],agents:e=[],containers:n=[],env:t,flagKeys:o=[],hasAccessFacade:d=!1,hasAi:g=!1,hasAnalytics:b=!1,hasBrowser:c=!1,hasFlags:h=!1,hasHyperdrive:f=!1,hasImages:O=!1,hasKv:F=!1,hasNotify:U=!1,hasPayments:B=!1,hasPipelines:T=!1,hasR2sql:E=!1,hasVectors:W=!0,hasX402:C=!1,maskMetadata:j,mutators:H=[],queues:v=[],rlsMetadata:L,schema:i,schemaSnapshot:w,shapes:y=[],storageRules:le,studioFeatures:he,useUmbrella:ue=!1,workflows:V=[]})=>{const u=pr(ue),ee=H.length>0,k=y.length>0,pe=w===void 0?"":Nt(w),me=w===void 0?"":`
1108
+ `:"",vectorsBuild:c,vectorsStub:t}},Fr=({advisories:a=[],advisorProcedures:r=[],agents:e=[],containers:n=[],env:t,flagKeys:o=[],hasAccessFacade:d=!1,hasAi:g=!1,hasAnalytics:b=!1,hasBrowser:c=!1,hasFlags:h=!1,hasHyperdrive:f=!1,hasImages:D=!1,hasKv:N=!1,hasNotify:F=!1,hasPayments:U=!1,hasPipelines:O=!1,hasR2sql:T=!1,hasVectors:B=!0,hasX402:E=!1,maskMetadata:W,mutators:C=[],queues:w=[],rlsMetadata:Y,schema:i,schemaSnapshot:y,shapes:ce=[],storageRules:le,studioFeatures:he,useUmbrella:ue=!1,workflows:j=[]})=>{const u=hr(ue),Z=C.length>0,v=ce.length>0,pe=y===void 0?"":Pt(y),me=y===void 0?"":`
1109
1109
  /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1110
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Ft(w))}, json: ${JSON.stringify(pe)} };
1111
- `,ge=w===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:be,configField:fe,contextField:we,stub:ye}=Wt(g),K=cr(d),S=jt(F),R=Ht(h,u.flags),G=Vt(o,h,u.flags),Q=lr(U),z=Kt(t),x=Gt(b),I=Qt(O),_=zt(f),$=Xt(c),M=Jt(E),P=Yt(T),{build:ve,contextField:ke,importLines:Se,specs:Re}=Zt(v),{build:xe,contextField:Ae,importLines:De,specs:Oe}=er(n,i.jurisdiction),{build:Te,contextField:Ee,importLines:Ce,specs:Le}=tr(V),{build:Ie,contextField:_e,importLines:$e,specs:Me}=rr(e),{build:Pe,configField:qe,contextField:Ne,imports:Fe,stub:Ue}=ar(B),{build:Be,configField:We,imports:je,stub:He}=nr(C),Ve=a,Ke=r,te=L??{policies:[],roles:[]},Ge=j??{columns:[]},Qe=le??{rules:[]},ze=he??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Xe,override:Je}=sr(V),{constant:Ye,override:Ze}=or(v),p=W&&i.vectorIndexes.length>0,re=new Set(i.tables.filter(s=>typeof s.shardMode=="object"&&s.shardMode.kind==="shardBy").map(s=>s.name)),ae=p&&i.vectorIndexes.some(s=>re.has(s.table)),A=i.tables.some(s=>s.shardMode==="global"),X=i.tables.some(s=>Ut(s)),ne=i.tables.some(s=>Bt(s)),q=i.tables.some(s=>s.externalSource!==void 0),se=i.tables.some(s=>s.memory===!0),J=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ne&&X)throw new qt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Y=i.tables.length>0,et=vr(i),tt=Sr(i),rt=Dr(i),at=kr(i),oe=Rr(i),ie=ir(p,V.length>0,v.length>0,h,J);k&&ie.push("WhereInput");const de=dr(A),{customMutatorOverride:nt,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=Or({hasMutators:ee,hasShapes:k,rlsData:te}),D=[`import type { ${ie.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, ${J?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${se?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${q?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...q?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],k?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];Y&&D.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),p&&D.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),g&&D.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),D.push(...K.importLines,...S.importLines,...R.importLines,...Q.importLines,...z.importLines,...x.importLines,...I.importLines,..._.importLines,...$.importLines,...M.importLines,...P.importLines,...De,...Ce,...Se,...$e,...Fe,...je,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...k?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ct=p?`
1112
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",lt=ne?`
1113
- d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",ht=X?`
1114
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ut=q?`
1115
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",pt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',mt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',gt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',bt=A?N("globalDbStub: DatabaseWriterLike",pt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:ft,vectorsBuild:wt,vectorsStub:yt}=Cr(p,ae?i.vectorIndexes.filter(s=>re.has(s.table)).map(s=>s.name):[]),vt=`{
1110
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(qt(y))}, json: ${JSON.stringify(pe)} };
1111
+ `,ge=y===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:be,configField:fe}=Ut(g),H=ir(d),k=Bt(N),S=Wt(h,u.flags),V=jt(o,h,u.flags),K=dr(F),G=Ht(t),R=Vt(b),L=Kt(D),I=Gt(f),_=Qt(c),$=zt(T),M=Xt(O),{build:we,contextField:ye,importLines:ve,specs:ke}=Jt(w),{build:Se,contextField:Re,importLines:xe,specs:Ae}=Yt(n,i.jurisdiction),{build:De,contextField:Oe,importLines:Te,specs:Ee}=Zt(j),{build:Ce,contextField:Le,importLines:Ie,specs:_e}=er(e),{build:$e,configField:Me,contextField:Pe,imports:qe,stub:Ne}=tr(U),{build:Fe,configField:Ue,imports:Be,stub:We}=rr(E),je=a,He=r,ee=Y??{policies:[],roles:[]},Ve=W??{columns:[]},Ke=le??{rules:[]},Ge=he??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Qe,override:ze}=ar(j),{constant:Xe,override:Je}=nr(w),p=B&&i.vectorIndexes.length>0,te=new Set(i.tables.filter(s=>typeof s.shardMode=="object"&&s.shardMode.kind==="shardBy").map(s=>s.name)),re=p&&i.vectorIndexes.some(s=>te.has(s.table)),x=i.tables.some(s=>s.shardMode==="global"),Q=i.tables.some(s=>Nt(s)),ae=i.tables.some(s=>Ft(s)),P=i.tables.some(s=>s.externalSource!==void 0),ne=i.tables.some(s=>s.memory===!0),z=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ae&&Q)throw new Mt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const X=i.tables.length>0,Ye=wr(i),Ze=vr(i),et=xr(i),tt=yr(i),se=kr(i),oe=sr(p,j.length>0,w.length>0,h,z);v&&oe.push("WhereInput");const ie=or(x),{customMutatorOverride:rt,shapeGuardImport:at,shapeReadPolicyAssertion:nt,shapeReadPolicyImport:st,shapeResolveOverride:ot}=Ar({hasMutators:Z,hasShapes:v,rlsData:ee}),A=[`import type { ${oe.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, ${z?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ne?"clearMemoryTables, ":""}${at}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${re?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ie.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],v?`import { asBucketStorage, ${st}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];X&&A.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),p&&A.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),g&&A.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),A.push(...H.importLines,...k.importLines,...S.importLines,...K.importLines,...G.importLines,...R.importLines,...L.importLines,...I.importLines,..._.importLines,...$.importLines,...M.importLines,...xe,...Te,...ve,...Ie,...qe,...Be,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...Z?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const it=p?`
1112
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",dt=ae?`
1113
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",ct=Q?`
1114
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",lt=P?`
1115
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",ht='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',ut='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',pt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',mt=x?q("globalDbStub: DatabaseWriterLike",ht,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:gt,vectorsBuild:bt,vectorsStub:ft}=Tr(p,re?i.vectorIndexes.filter(s=>te.has(s.table)).map(s=>s.name):[]),wt=`{
1116
1116
  ...this.ctxDbTuning(),
1117
1117
  auth: { identity: identity ?? null, userId: userId ?? null },
1118
1118
  broadcast: (delta) => {
@@ -1162,24 +1162,24 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1162
1162
  scheduler,
1163
1163
  schema: schema as unknown as SchemaLike,
1164
1164
  sql: this.sql as SqlExec,
1165
- storage,${A?`
1165
+ storage,${x?`
1166
1166
  globalDb,`:""}
1167
- }`,kt=p?`
1168
- vectors,`:"",St=Y?`
1169
- orm: bindOrm(facade),`:"",ce=X?"config.hyperdriveGlobal":"config.d1",Rt=A?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1170
- const globalDb: DatabaseWriterLike = ${ce}?.(env, globalRequest) ?? globalDbStub;
1171
- `:"",xt=Tr(k&&A,ce),{externalSourceOverride:At,sourceBootstrap:Dt,sourceClientCacheConst:Ot}=Er(q),Tt=`
1167
+ }`,yt=p?`
1168
+ vectors,`:"",vt=X?`
1169
+ orm: bindOrm(facade),`:"",de=Q?"config.hyperdriveGlobal":"config.d1",kt=x?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1170
+ const globalDb: DatabaseWriterLike = ${de}?.(env, globalRequest) ?? globalDbStub;
1171
+ `:"",St=Dr(v&&x,de),{externalSourceOverride:Rt,sourceBootstrap:xt,sourceClientCacheConst:At}=Or(P),Dt=`
1172
1172
  protected override async runShardInit(): Promise<void> {
1173
1173
  this.ensureMigrated();
1174
- ${se?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1174
+ ${ne?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1175
1175
  `:""}
1176
1176
  await this.dispatchShardInit();
1177
1177
  }
1178
- `,Et=oe.length>0?`
1178
+ `,Ot=se.length>0?`
1179
1179
  if (LUNORA_TTL_SWEEPS.length > 0) {
1180
1180
  void this.scheduleTtlSweep();
1181
1181
  }
1182
- `:"",Ct=`
1182
+ `:"",Tt=`
1183
1183
  public constructor(state: ShardDOState, env: unknown) {
1184
1184
  super(state, env, {
1185
1185
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1192,7 +1192,7 @@ ${se?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1192
1192
  ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1193
1193
  ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1194
1194
  });
1195
- ${Dt}${Et} }
1195
+ ${xt}${Ot} }
1196
1196
 
1197
1197
  protected override isCacheableQuery(functionPath: string): boolean {
1198
1198
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1216,14 +1216,14 @@ ${Dt}${Et} }
1216
1216
  protected override isPaidFunction(functionPath: string): boolean {
1217
1217
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1218
1218
  }
1219
- `,Lt=Y?`
1219
+ `,Et=X?`
1220
1220
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1221
1221
  ${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
1222
1222
  `)}
1223
- `:"",It=`${K.build}${S.build}${R.build}${x.build}${z.build}
1223
+ `:"",Ct=`${H.build}${k.build}${S.build}${R.build}${G.build}
1224
1224
  const secrets = createSecrets(env);
1225
- `,_t=`${K.contextField}${S.contextField}${R.contextField}${Q.contextField}${x.contextField}${z.contextField}
1226
- secrets,`,$t=Q.build,Mt=[...O?["images"]:[],...f?["sql"]:[],...c?["browser"]:[],...E?["r2sql"]:[],...T?["pipelines"]:[],...C?["x402"]:[]],Pt=`${I.build}${_.build}${$.build}${M.build}${P.build}${Be}`;return`${ur}${D.join(`
1225
+ `,Lt=`${H.contextField}${k.contextField}${S.contextField}${K.contextField}${R.contextField}${G.contextField}
1226
+ secrets,`,It=K.build,_t=[...g?["ai"]:[],...D?["images"]:[],...f?["sql"]:[],...c?["browser"]:[],...T?["r2sql"]:[],...O?["pipelines"]:[],...E?["x402"]:[]],$t=`${be}${L.build}${I.build}${_.build}${$.build}${M.build}${Fe}`;return`${lr}${A.join(`
1227
1227
  `)}
1228
1228
 
1229
1229
  type FunctionKind = "action" | "mutation" | "query";
@@ -1233,13 +1233,13 @@ interface FunctionReference {
1233
1233
  }
1234
1234
 
1235
1235
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1236
- const LUNORA_TABLE_REFS = ${l(et,"Record<string, Record<string, string>>")};
1236
+ const LUNORA_TABLE_REFS = ${l(Ye,"Record<string, Record<string, string>>")};
1237
1237
 
1238
1238
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1239
- const LUNORA_TABLE_INDEXES = ${l(tt,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1239
+ const LUNORA_TABLE_INDEXES = ${l(Ze,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1240
1240
 
1241
1241
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1242
- const LUNORA_TABLE_COLUMNS = ${l(rt,`Record<
1242
+ const LUNORA_TABLE_COLUMNS = ${l(et,`Record<
1243
1243
  string,
1244
1244
  Array<{
1245
1245
  bucket?: string;
@@ -1256,29 +1256,29 @@ const LUNORA_TABLE_COLUMNS = ${l(rt,`Record<
1256
1256
  >`)};
1257
1257
 
1258
1258
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1259
- const LUNORA_STORAGE_COLUMNS = ${l(at,"Record<string, string[]>")};
1259
+ const LUNORA_STORAGE_COLUMNS = ${l(tt,"Record<string, string[]>")};
1260
1260
 
1261
1261
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1262
- const LUNORA_TTL_SWEEPS = ${l(oe,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1262
+ const LUNORA_TTL_SWEEPS = ${l(se,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1263
1263
 
1264
1264
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1265
- const LUNORA_ADVISORIES = ${l(Ve,"AdvisoryFinding[]")};
1265
+ const LUNORA_ADVISORIES = ${l(je,"AdvisoryFinding[]")};
1266
1266
 
1267
1267
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1268
- const LUNORA_ADVISOR_PROCEDURES = ${l(Ke,"AdvisorProcedure[]")};
1268
+ const LUNORA_ADVISOR_PROCEDURES = ${l(He,"AdvisorProcedure[]")};
1269
1269
 
1270
1270
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1271
- const LUNORA_RLS_METADATA = ${l(te,"RlsPoliciesResult")};
1272
- ${ot}
1271
+ const LUNORA_RLS_METADATA = ${l(ee,"RlsPoliciesResult")};
1272
+ ${nt}
1273
1273
  /** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
1274
- const LUNORA_MASK_METADATA = ${l(Ge,"MaskPoliciesResult")};
1274
+ const LUNORA_MASK_METADATA = ${l(Ve,"MaskPoliciesResult")};
1275
1275
 
1276
1276
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1277
- const LUNORA_STORAGE_RULES = ${l(Qe,"StorageRulesResult")};
1277
+ const LUNORA_STORAGE_RULES = ${l(Ke,"StorageRulesResult")};
1278
1278
 
1279
1279
  /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1280
- const LUNORA_STUDIO_FEATURES = ${l(ze,"StudioFeaturesResult")};
1281
- ${me}${G.constant}${Xe}${Ye}${Oe}${Le}${Re}${Me}
1280
+ const LUNORA_STUDIO_FEATURES = ${l(Ge,"StudioFeaturesResult")};
1281
+ ${me}${V.constant}${Qe}${Xe}${Ae}${Ee}${ke}${_e}
1282
1282
  export interface ShardDOConfig {
1283
1283
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1284
1284
  cdc?: boolean;
@@ -1293,27 +1293,27 @@ export interface ShardDOConfig {
1293
1293
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1294
1294
  scheduler?: (env: Record<string, unknown>) => unknown;
1295
1295
  /** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
1296
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ct}${fe}${S.configField}${R.configField}${x.configField}${I.configField}${_.configField}${$.configField}${M.configField}${P.configField}${qe}${We}${lt}${ht}${ut}
1296
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${it}${fe}${k.configField}${S.configField}${R.configField}${L.configField}${I.configField}${_.configField}${$.configField}${M.configField}${Me}${Ue}${dt}${ct}${lt}
1297
1297
  }
1298
- ${N("schedulerStub",mt,["cancel","runAfter","runAt"])}${N("storageStub",gt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${bt}${Ot}${yt}${ye}${S.stub}${R.stub}${x.stub}${I.stub}${_.stub}${$.stub}${M.stub}${P.stub}${Ue}${He}
1299
- ${fr}
1298
+ ${q("schedulerStub",ut,["cancel","runAfter","runAt"])}${q("storageStub",pt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${mt}${At}${ft}${k.stub}${S.stub}${R.stub}${L.stub}${I.stub}${_.stub}${$.stub}${M.stub}${Ne}${We}
1299
+ ${gr}
1300
1300
 
1301
1301
  /**
1302
1302
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1303
1303
  * from the worker entry so wrangler binds it by name.
1304
1304
  */
1305
1305
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1306
- class extends ShardDOBase {${Ct}
1306
+ class extends ShardDOBase {${Tt}
1307
1307
  private migrated = false;
1308
1308
 
1309
- ${wr}
1310
- ${de.override}
1311
- ${yr}
1312
- ${nt}${dt}${xt}${At}
1309
+ ${br}
1310
+ ${ie.override}
1311
+ ${fr}
1312
+ ${rt}${ot}${St}${Rt}
1313
1313
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1314
1314
  return LUNORA_LIFECYCLE_HOOKS[event];
1315
1315
  }
1316
- ${Tt}
1316
+ ${Dt}
1317
1317
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1318
1318
  // socket-terminated half of the same reactivity — and differs only in who
1319
1319
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1401,7 +1401,7 @@ ${Tt}
1401
1401
  protected override studioFeatures(): StudioFeaturesResult {
1402
1402
  return LUNORA_STUDIO_FEATURES;
1403
1403
  }
1404
- ${G.evaluateOverride}${G.subscriptionOverride}${Je}${Ze}
1404
+ ${V.evaluateOverride}${V.subscriptionOverride}${ze}${Je}
1405
1405
  protected override advisories(): AdvisoryFinding[] {
1406
1406
  return LUNORA_ADVISORIES;
1407
1407
  }
@@ -1410,7 +1410,7 @@ ${G.evaluateOverride}${G.subscriptionOverride}${Je}${Ze}
1410
1410
  return LUNORA_ADVISOR_PROCEDURES;
1411
1411
  }
1412
1412
 
1413
- ${gr}
1413
+ ${pr}
1414
1414
 
1415
1415
  protected override ensureMigrated(): void {
1416
1416
  if (this.migrated) {
@@ -1420,7 +1420,7 @@ ${gr}
1420
1420
  runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ge} });
1421
1421
  this.migrated = true;
1422
1422
  }
1423
- ${J?`
1423
+ ${z?`
1424
1424
  protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1425
1425
  // Migrations create the fts5 companions; without them every backfill
1426
1426
  // statement would raise "no such table" on a shard that has never
@@ -1429,7 +1429,7 @@ ${J?`
1429
1429
 
1430
1430
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1431
1431
  }
1432
- `:""}${ft}
1433
- ${br({actionOnlyFields:Mt,agentsBuild:Ie,agentsContextField:_e,aiBuild:be,aiContextField:we,containersBuild:xe,containersContextField:Ae,databaseOptions:vt,everyContextBuild:It,everyContextField:_t,facadeBlock:Lt,globalDatabaseLine:Rt,notifyBuild:$t,ormContextField:St,paymentsBuild:Pe,paymentsContextField:Ne,queuesBuild:ve,queuesContextField:ke,vectorsBuild:wt,vectorsContextField:kt,workflowsBuild:Te,workflowsContextField:Ee,actionOnlyBuild:Pt})}
1432
+ `:""}${gt}
1433
+ ${mr({actionOnlyFields:_t,agentsBuild:Ce,agentsContextField:Le,containersBuild:Se,containersContextField:Re,databaseOptions:wt,everyContextBuild:Ct,everyContextField:Lt,facadeBlock:Et,globalDatabaseLine:kt,notifyBuild:It,ormContextField:vt,paymentsBuild:$e,paymentsContextField:Pe,queuesBuild:we,queuesContextField:ye,vectorsBuild:bt,vectorsContextField:yt,workflowsBuild:De,workflowsContextField:Oe,actionOnlyBuild:$t})}
1434
1434
  };
1435
- `};export{kr as b,Br as e};
1435
+ `};export{yr as b,Fr as e};
@@ -6,38 +6,24 @@ import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUzi
6
6
 
7
7
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
8
8
  }
9
- `}:{importFragment:"",override:""},k=e=>{if(!e)return{build:"",configField:"",contextField:"",stub:""};const t='throw new Error("ctx.ai: no AI binding found. Add an \\`ai\\` binding (env.AI) to wrangler.jsonc, or pass \\`ai\\` to createShardDO().");';return{build:`
9
+ `}:{importFragment:"",override:""},k=e=>e?{build:`
10
10
  const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
11
11
  // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
12
12
  // function path + trace id into createAi, which folds them into the
13
- // gateway's native \`metadata\` only when a gateway is configured (absent
14
- // otherwise). Mirror the tracer's anchor guard — a deferred subscription
15
- // re-run must not borrow a concurrent dispatch's trace, so read
16
- // \`getCurrentTrace()\` only on the synchronous (non-threaded-identity) path.
13
+ // gateway's \`metadata\`. Mirror the tracer's anchor guard — a deferred
14
+ // subscription re-run must not borrow a concurrent dispatch's trace, so
15
+ // read \`getCurrentTrace()\` only on the synchronous (non-threaded-identity) path.
17
16
  const aiTrace = options.identity ? undefined : this.getCurrentTrace();
18
- const ai: LunoraAi = aiBinding
19
- ? createAi({ binding: aiBinding as AiBindingLike, env: env as Record<string, unknown>, metadata: { functionPath: options.functionPath, traceId: aiTrace?.traceId } })
20
- : aiStub;
17
+ // \`telemetry\` gives every model call an \`ai.generate\` / \`ai.stream\` span
18
+ // and \`gen_ai.usage.*\` token + cost counters attributed to this function.
19
+ const ai: LunoraAi = createAi({
20
+ binding: aiBinding as AiBindingLike | undefined,
21
+ env: env as Record<string, unknown>,
22
+ metadata: { functionPath: options.functionPath, traceId: aiTrace?.traceId },
23
+ telemetry: { metrics, trace },
24
+ });
21
25
  `,configField:`
22
- ai?: (env: Record<string, unknown>) => AiBindingLike;`,contextField:`
23
- ai,`,stub:`
24
- const aiStub: LunoraAi = {
25
- embeddingModel: () => {
26
- ${t}
27
- },
28
- model: () => {
29
- ${t}
30
- },
31
- run: async () => {
32
- ${t}
33
- },
34
- // workersai is a callable-with-properties; a bare throwing arrow isn't
35
- // structurally assignable, so cast it. Never invoked (the stub throws first).
36
- workersai: (() => {
37
- ${t}
38
- }) as unknown as LunoraAi["workersai"],
39
- };
40
- `}},l=(e,t,n,{cast:r="",sync:o=[]}={})=>{const s=n.map(u=>` ${u}: ${o.includes(u)?"":"async "}() => {
26
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`}:{build:"",configField:""},l=(e,t,n,{cast:r="",sync:o=[]}={})=>{const s=n.map(u=>` ${u}: ${o.includes(u)?"":"async "}() => {
41
27
  ${t}
42
28
  },`).join(`
43
29
  `);return`
@@ -137,12 +123,12 @@ const LUNORA_FLAG_KEYS = ${p(e,'ReadonlyArray<{ key: string; type: "boolean" | "
137
123
 
138
124
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
139
125
  }
140
- `;return{constant:o,evaluateOverride:s,subscriptionOverride:u}},A=e=>e?{build:`
126
+ `;return{constant:o,evaluateOverride:s,subscriptionOverride:u}},F=e=>e?{build:`
141
127
  const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
142
128
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
143
129
  `,configField:`
144
130
  analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
145
- analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:l("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:c,F=e=>e?{build:`
131
+ analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:l("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:c,A=e=>e?{build:`
146
132
  const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
147
133
  const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
148
134
  `,configField:`
@@ -232,7 +218,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
232
218
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
233
219
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
234
220
 
235
- ${t}`},B=e=>{if(e.length===0)return"";const n=e.filter(i=>i.voice).length>0,r=e.map(i=>{a(i.exportName,`agent export "${i.exportName}"`),a(i.className,`agent class "${i.className}"`);const g=`/** WorkflowEntrypoint for the \`${i.exportName}\` agent (binding \`${i.bindingName}\`). */
221
+ ${t}`},W=e=>{if(e.length===0)return"";const n=e.filter(i=>i.voice).length>0,r=e.map(i=>{a(i.exportName,`agent export "${i.exportName}"`),a(i.className,`agent class "${i.className}"`);const g=`/** WorkflowEntrypoint for the \`${i.exportName}\` agent (binding \`${i.bindingName}\`). */
236
222
  export class ${i.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
237
223
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
238
224
  super(ctx, env, compileAgentWorkflow(${i.exportName}, "${i.exportName}"), "${i.exportName}");
@@ -260,7 +246,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
260
246
 
261
247
  import { ${o} } from "../agents.js";
262
248
 
263
- ${r}`},W=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)a(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
249
+ ${r}`},B=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)a(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
264
250
  `);return`${d}/**
265
251
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
266
252
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
@@ -309,7 +295,7 @@ const ${e} = ${p(r,t)};
309
295
  protected override ${n}(): ${t} {
310
296
  return ${e};
311
297
  }
312
- `}),M=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return f("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},U=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return f("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Q=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
298
+ `}),U=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return f("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},M=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return f("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Q=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
313
299
  const payments: LunoraPayment = config.payment
314
300
  ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
315
301
  : paymentStub;
@@ -320,4 +306,4 @@ const ${e} = ${p(r,t)};
320
306
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
321
307
  : x402Stub;
322
308
  `,configField:`
323
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:l("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},V=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{I as A,W as B,w as a,R as b,$ as c,S as d,k as e,A as f,F as g,C as h,_ as i,E as j,O as k,T as l,q as m,D as n,j as o,Q as p,K as q,l as r,M as s,U as t,V as u,x as v,L as w,N as x,B as y,P as z};
309
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:l("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},V=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{I as A,B,w as a,R as b,$ as c,S as d,k as e,F as f,A as g,C as h,_ as i,E as j,O as k,T as l,q as m,D as n,j as o,Q as p,K as q,l as r,U as s,M as t,V as u,x as v,L as w,N as x,W as y,P as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.239",
3
+ "version": "1.0.0-alpha.240",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.171",
50
- "@lunora/agent": "1.0.0-alpha.153",
49
+ "@lunora/advisor": "1.0.0-alpha.172",
50
+ "@lunora/agent": "1.0.0-alpha.154",
51
51
  "@lunora/container": "1.0.0-alpha.63",
52
52
  "@lunora/errors": "1.0.0-alpha.47",
53
- "@lunora/platform": "1.0.0-alpha.43",
54
- "@lunora/queue": "1.0.0-alpha.78",
55
- "@lunora/scheduler": "1.0.0-alpha.97",
53
+ "@lunora/platform": "1.0.0-alpha.44",
54
+ "@lunora/queue": "1.0.0-alpha.79",
55
+ "@lunora/scheduler": "1.0.0-alpha.98",
56
56
  "@lunora/values": "1.0.0-alpha.57",
57
57
  "@lunora/workflow": "1.0.0-alpha.68",
58
58
  "jiti": "^2.7.0",