@lunora/codegen 1.0.0-alpha.377 → 1.0.0-alpha.379

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 a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DKYJ2K4t.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-CN8HACEL.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-a0IT8OSb.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-DHDfKLoa.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-i8Zcf64H.mjs";import{default as J}from"./packem_shared/discoverInserts-IAa3lRR4.mjs";import{d as X}from"./packem_shared/index-BjDVAPNW.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-Ipxibja6.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-B-t7jQSm.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-DZOGiEPs.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-Lq6G--TZ.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-B0DYk-gW.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-DmkjooXZ.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-C1F-Wkky.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ve,emitOpenApi as ze,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-Ct2wK_Tj.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-DA0ZNkhl.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir}from"./packem_shared/loadProjectConfig-B7RmxIeD.mjs";import{PROJECT_CONFIG_FILENAMES as fr,findCodegenConfigFile as mr,findProjectConfigFile as dr,projectConfigCandidatePaths as pr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Dl5nCL-t.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as gr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Ir,SDK_TARGETS as _r,generateSdk as Fr}from"./sdk/index.mjs";import{redact as Mr,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as br}from"./packem_shared/emitDrizzleSchema-BmCxM6tO.mjs";import{e as Ur}from"./packem_shared/server-BY1v1bTx.mjs";import{e as Hr}from"./packem_shared/shard-D1HjM_tr.mjs";import{G as Br}from"./packem_shared/shared-BErjtci3.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{t as Yr,u as Xr,v as Zr}from"./packem_shared/shard-runtime-DAnfkcDz.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-D6uqyYd_.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-C3RiGYk7.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-BMMht_iZ.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-NGByI1FZ.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,gr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DKYJ2K4t.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-CN8HACEL.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-a0IT8OSb.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-DHDfKLoa.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-i8Zcf64H.mjs";import{default as J}from"./packem_shared/discoverInserts-IAa3lRR4.mjs";import{d as X}from"./packem_shared/index-BjDVAPNW.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-Ipxibja6.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-B-t7jQSm.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-DZOGiEPs.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-Lq6G--TZ.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-B0DYk-gW.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-DmkjooXZ.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-Df0hnrKm.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ve,emitOpenApi as ze,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-Ct2wK_Tj.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-DA0ZNkhl.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir}from"./packem_shared/loadProjectConfig-B7RmxIeD.mjs";import{PROJECT_CONFIG_FILENAMES as fr,findCodegenConfigFile as mr,findProjectConfigFile as dr,projectConfigCandidatePaths as pr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-G_NTvXGI.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as gr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Ir,SDK_TARGETS as _r,generateSdk as Fr}from"./sdk/index.mjs";import{redact as Mr,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as br}from"./packem_shared/emitDrizzleSchema-BmCxM6tO.mjs";import{e as Ur}from"./packem_shared/server-BY1v1bTx.mjs";import{e as Hr}from"./packem_shared/shard-CMbVoHUX.mjs";import{G as Br}from"./packem_shared/shared-BErjtci3.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{t as Yr,u as Xr,v as Zr}from"./packem_shared/shard-runtime-HdePIC-P.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-D6uqyYd_.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-C3RiGYk7.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-BMMht_iZ.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-NGByI1FZ.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,gr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as z,readFileSync as Xe,mkdirSync as qt,writeFileSync as Sr,rmSync as Ne,readdirSync as Rn}from"node:fs";import{dirname as jt,join as E,relative as Fn}from"node:path";import{performance as xt}from"node:perf_hooks";import{runAdvisor as Ar}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as yr}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as br}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ht,ts as Nr,VariableDeclarationKind as Gt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as de,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as Pr,propertyInitializer as F,listSecurityScanFiles as Je,objectLiteralFromCallbackBody as Ln,limitNameOf as Dn,optionsObjectLiteral as Mn,handlerOf as wr,collectNodeRows as ie,chainRootOf as Ze,outermostValueWrapper as T,isWriteTarget as et,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Yt,returningFunctionOf as Ot,walkChain as Ir,RUN_METHODS as _n,functionReferenceSegments as Tr,isTestPath as Cr,isFunctionLike as oe,functionKeyOf as zn,withSourceListMemo as Or}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as M,g as Qt,c as S,a as tt,w as Xt,k as kr,l as Rr,h as Fr,m as Lr,j as kt,i as Dr}from"./attribution-DUbGYT4N.mjs";import{a as zs,r as St,i as Y,b as Mr,m as Kn,c as st,e as Jt,E as $n,C as Bn,d as _r,f as zr,g as Kr}from"./context-root-BPfMNAJM.mjs";import{a as I,i as Vn,c as te,d as Un,e as $r,f as Br,g as Wn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as Vr}from"./property-name-7cBlgK_O.mjs";import{b as Ur,a as nt}from"./module-specifiers-BctA0m_p.mjs";import{r as it,s as Wr}from"./parse-validator-CP5CL6Q7.mjs";import qr from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as K,r as qn}from"./database-calls-hLzaOquW.mjs";import jr from"./discoverHyperdriveCalls-i8Zcf64H.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Zt,a as We,s as jn,d as Hr}from"./index-BjDVAPNW.mjs";import{MUTATORS_FILENAME as Gr,isDefineMutatorCallee as Yr,mutatorServerImplOf as Qr,discoverMutators as Xr}from"./MUTATORS_FILENAME-Ipxibja6.mjs";import Jr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Zr,discoverNotifyCalls as eo}from"./NOTIFY_FILENAME-B-t7jQSm.mjs";import to from"./discoverR2sqlCalls-Lq6G--TZ.mjs";import so from"./discoverRlsProcedures-B0DYk-gW.mjs";import{s as es,n as no}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as io,redact as ro,isHeuristicSecretKind as oo,isSecretishName as ao}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Hn,readMergeDurableObjects as co}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as lo,r as uo}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as fo,discoverWorkflows as go}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as po}from"./json-data-Chfs2Cz5.mjs";import{a as mo,I as ho,g as vo,G as Gn,d as Eo,i as xo}from"./shared-BErjtci3.mjs";import{createCodegenProject as So}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as zE,refreshCodegenProject as KE,tsconfigFingerprint as $E}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as Ao,usedCapabilities as yo}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{isD1GlobalTable as Yn,isHyperdriveGlobalTable as Qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bo}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as No}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import Po from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as wo,fileWiresRequestSecretTool as Io,createTargetScope as To,discoverFeatureUsage as Co}from"./capabilitiesUsedBy-CN8HACEL.mjs";import Xn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Oo,findProjectConfigFile as ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Ro}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as Fo}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Lo}from"./readServiceBindings-BA49C6aN.mjs";import Do from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as Rt,gatePlatformFeatures as Mo,readTargetDiagnostics as _o,vectorizeDimensionDiagnostics as zo,liveStreamsDeliveryAuthorizationDiagnostic as Ko,socketRoutesDeliveryAuthorizationDiagnostic as $o,studioPlatformFor as Bo,platformFeatureAvailable as Vo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Uo}from"./schema-BgM8A3XV.mjs";import{b as Jn,e as Wo}from"./shard-D1HjM_tr.mjs";import{e as qo,a as jo}from"./server-BY1v1bTx.mjs";import{emitDataModel as Ho}from"./emitDataModel-BMMht_iZ.mjs";import{i as Go,a as Yo,e as Qo,b as Xo,d as Jo,c as Zo}from"./unwrap-handler-return-eQRIZSOX.mjs";import ea from"./discoverFunctions-a0IT8OSb.mjs";import ta from"./discoverHttpRoutes-DHDfKLoa.mjs";import sa from"./discoverInserts-IAa3lRR4.mjs";import{e as Zn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import na from"./discoverMigrations-Bv8kNIgy.mjs";import ia from"./discoverQueries-DZOGiEPs.mjs";import ra from"./discoverRlsMetadata-Dq6iSXnC.mjs";import oa from"./discoverSchema-DmkjooXZ.mjs";import{discoverShapes as aa}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as ca}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as la,emitApp as da}from"./emitApp-C1F-Wkky.mjs";import{readJsonSync as ua}from"@visulima/fs";import{buildSchemaSnapshot as fa}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as ga,emitOpenApiModule as pa}from"./buildOpenApiDocument-Ct2wK_Tj.mjs";import{buildOpenRpcDocument as ma,emitOpenRpcModule as ha}from"./OPENRPC_VERSION-DA0ZNkhl.mjs";import{w as va,u as Ea,v as xa,t as Sa,x as Aa}from"./shard-runtime-DAnfkcDz.mjs";import{emitCollections as ya,emitSeed as ba,emitApi as Na,emitInternalApi as Pa}from"./emitApi-D6uqyYd_.mjs";import{emitCrons as wa,emitScheduler as Ia,emitShardRegistry as Ta,emitDurableObjects as Ca,emitVectors as Oa,emitWranglerCronTriggers as ka}from"./emitCrons-C3RiGYk7.mjs";import Ra from"./emitDrizzleSchema-BmCxM6tO.mjs";import{LAZY_FUNCTION_DIRECTORY as ei,emitFunctions as Fa,emitLazyFunctionModules as La}from"./emitFunctions-NGByI1FZ.mjs";const Da=(e,t=!1)=>{if(e.length===0)return"";const s=Eo(t),n=e.map(c=>{if(mo(c.exportName,"live stream export name"),!ho.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{vo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as z,readFileSync as Xe,mkdirSync as qt,writeFileSync as Sr,rmSync as Ne,readdirSync as Rn}from"node:fs";import{dirname as jt,join as E,relative as Fn}from"node:path";import{performance as xt}from"node:perf_hooks";import{runAdvisor as Ar}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as yr}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as br}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Ht,ts as Nr,VariableDeclarationKind as Gt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as de,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as Pr,propertyInitializer as F,listSecurityScanFiles as Je,objectLiteralFromCallbackBody as Ln,limitNameOf as Dn,optionsObjectLiteral as Mn,handlerOf as wr,collectNodeRows as ie,chainRootOf as Ze,outermostValueWrapper as T,isWriteTarget as et,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Yt,returningFunctionOf as Ot,walkChain as Ir,RUN_METHODS as _n,functionReferenceSegments as Tr,isTestPath as Cr,isFunctionLike as oe,functionKeyOf as zn,withSourceListMemo as Or}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as M,g as Qt,c as S,a as tt,w as Xt,k as kr,l as Rr,h as Fr,m as Lr,j as kt,i as Dr}from"./attribution-DUbGYT4N.mjs";import{a as zs,r as St,i as Y,b as Mr,m as Kn,c as st,e as Jt,E as $n,C as Bn,d as _r,f as zr,g as Kr}from"./context-root-BPfMNAJM.mjs";import{a as I,i as Vn,c as te,d as Un,e as $r,f as Br,g as Wn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as Vr}from"./property-name-7cBlgK_O.mjs";import{b as Ur,a as nt}from"./module-specifiers-BctA0m_p.mjs";import{r as it,s as Wr}from"./parse-validator-CP5CL6Q7.mjs";import qr from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as K,r as qn}from"./database-calls-hLzaOquW.mjs";import jr from"./discoverHyperdriveCalls-i8Zcf64H.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Zt,a as We,s as jn,d as Hr}from"./index-BjDVAPNW.mjs";import{MUTATORS_FILENAME as Gr,isDefineMutatorCallee as Yr,mutatorServerImplOf as Qr,discoverMutators as Xr}from"./MUTATORS_FILENAME-Ipxibja6.mjs";import Jr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Zr,discoverNotifyCalls as eo}from"./NOTIFY_FILENAME-B-t7jQSm.mjs";import to from"./discoverR2sqlCalls-Lq6G--TZ.mjs";import so from"./discoverRlsProcedures-B0DYk-gW.mjs";import{s as es,n as no}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as io,redact as ro,isHeuristicSecretKind as oo,isSecretishName as ao}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Hn,readMergeDurableObjects as co}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as lo,r as uo}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as fo,discoverWorkflows as go}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as po}from"./json-data-Chfs2Cz5.mjs";import{a as mo,I as ho,g as vo,G as Gn,d as Eo,i as xo}from"./shared-BErjtci3.mjs";import{createCodegenProject as So}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as zE,refreshCodegenProject as KE,tsconfigFingerprint as $E}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as Ao,usedCapabilities as yo}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{isD1GlobalTable as Yn,isHyperdriveGlobalTable as Qn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as bo}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as No}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import Po from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as wo,fileWiresRequestSecretTool as Io,createTargetScope as To,discoverFeatureUsage as Co}from"./capabilitiesUsedBy-CN8HACEL.mjs";import Xn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Oo,findProjectConfigFile as ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Ro}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as Fo}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Lo}from"./readServiceBindings-BA49C6aN.mjs";import Do from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as Rt,gatePlatformFeatures as Mo,readTargetDiagnostics as _o,vectorizeDimensionDiagnostics as zo,liveStreamsDeliveryAuthorizationDiagnostic as Ko,socketRoutesDeliveryAuthorizationDiagnostic as $o,studioPlatformFor as Bo,platformFeatureAvailable as Vo}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Uo}from"./schema-BgM8A3XV.mjs";import{b as Jn,e as Wo}from"./shard-CMbVoHUX.mjs";import{e as qo,a as jo}from"./server-BY1v1bTx.mjs";import{emitDataModel as Ho}from"./emitDataModel-BMMht_iZ.mjs";import{i as Go,a as Yo,e as Qo,b as Xo,d as Jo,c as Zo}from"./unwrap-handler-return-eQRIZSOX.mjs";import ea from"./discoverFunctions-a0IT8OSb.mjs";import ta from"./discoverHttpRoutes-DHDfKLoa.mjs";import sa from"./discoverInserts-IAa3lRR4.mjs";import{e as Zn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import na from"./discoverMigrations-Bv8kNIgy.mjs";import ia from"./discoverQueries-DZOGiEPs.mjs";import ra from"./discoverRlsMetadata-Dq6iSXnC.mjs";import oa from"./discoverSchema-DmkjooXZ.mjs";import{discoverShapes as aa}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as ca}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as la,emitApp as da}from"./emitApp-Df0hnrKm.mjs";import{readJsonSync as ua}from"@visulima/fs";import{buildSchemaSnapshot as fa}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as ga,emitOpenApiModule as pa}from"./buildOpenApiDocument-Ct2wK_Tj.mjs";import{buildOpenRpcDocument as ma,emitOpenRpcModule as ha}from"./OPENRPC_VERSION-DA0ZNkhl.mjs";import{w as va,u as Ea,v as xa,t as Sa,x as Aa}from"./shard-runtime-HdePIC-P.mjs";import{emitCollections as ya,emitSeed as ba,emitApi as Na,emitInternalApi as Pa}from"./emitApi-D6uqyYd_.mjs";import{emitCrons as wa,emitScheduler as Ia,emitShardRegistry as Ta,emitDurableObjects as Ca,emitVectors as Oa,emitWranglerCronTriggers as ka}from"./emitCrons-C3RiGYk7.mjs";import Ra from"./emitDrizzleSchema-BmCxM6tO.mjs";import{LAZY_FUNCTION_DIRECTORY as ei,emitFunctions as Fa,emitLazyFunctionModules as La}from"./emitFunctions-NGByI1FZ.mjs";const Da=(e,t=!1)=>{if(e.length===0)return"";const s=Eo(t),n=e.map(c=>{if(mo(c.exportName,"live stream export name"),!ho.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{vo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
2
  __lunoraLive: ${m},
3
3
  topic: \`${u.name}:${v}\`,
4
4
  }),`});return` ${c.exportName}: {
@@ -1 +1 @@
1
- import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-DAnfkcDz.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowEventFragments,w as emitWorkflowFragments,W as emitWorkflows,v as emitWorkflowsMetadataFragments,A as queueAliasFindings};
1
+ import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-HdePIC-P.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowEventFragments,w as emitWorkflowFragments,W as emitWorkflows,v as emitWorkflowsMetadataFragments,A as queueAliasFindings};
@@ -1,11 +1,11 @@
1
- import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as T}from"./schema-BgM8A3XV.mjs";import{a as N,I,G as y}from"./shared-BErjtci3.mjs";const L={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...q.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[L]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(t=>T(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,j=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as L}from"./schema-BgM8A3XV.mjs";import{a as j,I as $,G as w}from"./shared-BErjtci3.mjs";const G={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},k=e=>[...N.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[G]:[]],S=e=>k(e).length>0,E=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>L(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,P=e=>e.hasScheduler?`
2
2
  /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
3
3
  private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
4
4
  const namespace = this.schedulerDeclaration?.namespace(env);
5
5
 
6
6
  return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
7
7
  }
8
- `:"",G=e=>e?`
8
+ `:"",M=e=>e?`
9
9
  /**
10
10
  * One bucket's \`Storage\`, signing under the name it is registered as.
11
11
  *
@@ -114,7 +114,7 @@ import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";impor
114
114
  storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
115
115
  };
116
116
  }
117
- `:"",P=e=>e?`
117
+ `:"",B=e=>e?`
118
118
  /**
119
119
  * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
120
120
  *
@@ -339,12 +339,12 @@ const buildGlobalCdcApplier =
339
339
 
340
340
  return request.changes.length;
341
341
  };
342
- `:"",$=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],M=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...l(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],B=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
343
- public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
344
- this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
342
+ `:"",W=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],_=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...S(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...l(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],H=e=>k(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
343
+ public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
344
+ this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
345
345
 
346
346
  return this;
347
- }`),_=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
347
+ }`),U=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
348
348
  public admin(selector: Selector<Env, string>): this {
349
349
  this.adminToken = selector;
350
350
 
@@ -408,8 +408,8 @@ const buildGlobalCdcApplier =
408
408
  this.storageDeclaration = declaration;
409
409
 
410
410
  return this;
411
- }`]:[],...B(e)],H=e=>{const t=a=>e.hasScheduler?`
412
- ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
411
+ }`]:[],...H(e)],F=e=>{const r=a=>e.hasScheduler?`
412
+ ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
413
413
  ? {
414
414
  d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
415
415
  const env = rawEnv as Env;
@@ -429,7 +429,7 @@ const buildGlobalCdcApplier =
429
429
  : undefined;
430
430
 
431
431
  return createD1CtxDb({
432
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
432
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("D1CtxDbOptions")}
433
433
  ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
434
434
  auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
435
435
  // Forwarded from the shard's own \`cdc\` config, so ONE
@@ -467,7 +467,7 @@ const buildGlobalCdcApplier =
467
467
  : undefined;
468
468
 
469
469
  return createHyperdriveGlobalCtxDb({
470
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
470
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("SqlCtxDbOptions")}
471
471
  ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
472
472
  auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
473
473
  // See the D1 twin: one \`cdc\` switch, both changelogs.
@@ -488,13 +488,13 @@ const buildGlobalCdcApplier =
488
488
  ? {
489
489
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
490
490
  }
491
- : {}),`]:[],...l(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
492
- ${r.join(`
491
+ : {}),`]:[],...l(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...S(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
492
+ ${t.join(`
493
493
  `)}
494
- `:""},W=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],U=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],F=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],z=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],J=e=>e?['import notifyConfig from "../notify.js";']:[],K=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],V=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Y=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],c=[...r||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((s,u)=>s.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},X=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:o,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:s}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...U(t,r),...z(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...F(o),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...s?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...K(e),...Y(e),"",...W(e.identity),...V(e),...a||n?['import schema from "../schema.js";']:[],...J(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},Z=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
494
+ `:""},Q=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],z=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],J=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],K=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],V=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],Y=e=>e?['import notifyConfig from "../notify.js";']:[],X=e=>E(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Z=e=>E(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],ee=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:s}=e,i=s?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},te=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:s,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...z(r,t),...V(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...J(s),...K(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...X(e),...ee(e),"",...Q(e.identity),...Z(e),...a||n?['import schema from "../schema.js";']:[],...Y(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},re=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
495
495
  // The schema's jurisdiction pins the auth object like every other DO.
496
- jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",ee=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,te=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
497
- ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${ee(t.shardMode)}],`).join(`
496
+ jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",ae=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,ne=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
497
+ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${ae(r.shardMode)}],`).join(`
498
498
  `)}
499
499
  ]);
500
500
 
@@ -503,10 +503,10 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${ee(t.shardMode)}],`
503
503
 
504
504
  if (shardRegistry) {
505
505
  options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
506
- }`]:[]],S=e=>(e.liveStreamDeclarations??[]).map(t=>{if(N(t.exportName,"live stream export name"),!I.test(t.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(t.filePath)}`);return` { id: ${JSON.stringify(t.id)}, load: () => import("../${t.filePath}.js").then((m) => m.${t.exportName}) },`}),re=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ae=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ne=e=>p(e)?`liveStreamRouter([
507
- ${S(e).join(`
506
+ }`]:[]],D=e=>(e.liveStreamDeclarations??[]).map(r=>{if(j(r.exportName,"live stream export name"),!$.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),se=e=>p(e)?[" httpRouter: liveStreamRouter([",...D(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],oe=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],ie=e=>p(e)?`liveStreamRouter([
507
+ ${D(e).join(`
508
508
  `)}
509
- ], host)`:"host",se=e=>[...te(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
509
+ ], host)`:"host",ce=e=>[...ne(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
510
510
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
511
511
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
512
512
  const source = workflowEnv as Record<string, unknown>;
@@ -627,10 +627,10 @@ ${S(e).join(`
627
627
  // The OAuth discovery documents (an \`mcp()\` resource's metadata, the
628
628
  // issuer's) are derived here from the declared options, so the worker
629
629
  // forwards only those exact paths and no other probe reaches the object.
630
- // Memoised on the declaration: a framework-hosted worker rebuilds these
631
- // options per request, and \`options(env)\` rebuilds every plugin.
630
+ // Memoised on the declaration: each worker built for a new \`env\` runs
631
+ // these options again, and \`options(env)\` rebuilds every plugin.
632
632
  discoveryPaths,
633
- internalSecret,${Z(e)}
633
+ internalSecret,${re(e)}
634
634
  namespace,
635
635
  ...(objectName === undefined ? {} : { objectName }),
636
636
  });
@@ -770,15 +770,15 @@ ${S(e).join(`
770
770
  }`:` if (this.accessSelector) {
771
771
  options.resolveIdentity = createAccessResolver(this.accessSelector(env));
772
772
  }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
773
- ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
773
+ ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
774
774
  `)}
775
- };`]:[]],oe=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...e.hasQueue?[` queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],...re(e),...ae(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],ie=e=>e?`
775
+ };`]:[]],le=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...e.hasQueue?[` queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],...se(e),...oe(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],de=e=>e?`
776
776
  /** The identity memo per \`env\` object, owned by one assembled worker. */
777
777
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
778
- `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ce=e=>{if(!E(e))return"";const r=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,n,o])=>[a,n,o]);return`
778
+ `:"",R=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,he=e=>{if(!R(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,n,s])=>[a,n,s]);return`
779
779
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
780
780
  interface DeferredModules {
781
- ${r.map(([a,n])=>` ${a}: ${n};`).join(`
781
+ ${t.map(([a,n])=>` ${a}: ${n};`).join(`
782
782
  `)}
783
783
  }
784
784
 
@@ -788,16 +788,20 @@ let deferredModules: Promise<DeferredModules> | undefined;
788
788
  const loadDeferredModules = (): Promise<DeferredModules> =>
789
789
  (deferredModules ??= (async (): Promise<DeferredModules> => {
790
790
  return {
791
- ${r.map(([a,,n])=>` ${a}: ${n},`).join(`
791
+ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
792
792
  `)}
793
793
  };
794
794
  })());
795
- `},le=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
796
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},be=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
797
- `:"",de=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),me=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,n=$(r),o=se(r),i=a?` let auth: LunoraAuth | null = null;
795
+ `},ue=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
796
+ await ensureAuth(env);`:"",n=e?`
797
+ await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"target",eventWorkerLine:`
798
+ const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"worker",eventWorkerLine:`
799
+ worker ??= ${t};`}},pe=e=>R(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
800
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},ye=e=>e?`${w}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
801
+ `:"",be=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),fe=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=W(t),s=ce(t),i=a?` let auth: LunoraAuth | null = null;
798
802
  let authInit: Promise<void> | null = null;
799
- // One memo per env for THIS assembled worker: a framework-hosted worker rebuilds its options per
800
- // request and must reuse it, but a second \`assemble()\` has its own auth closure and must not share.
803
+ // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
804
+ // \`assemble()\` has its own auth closure and must not share.
801
805
  const identityMemos: IdentityMemoStore = new WeakMap();
802
806
  `:"",d=a?`
803
807
  const initAuth = async (env: Env): Promise<void> => {
@@ -852,17 +856,29 @@ ${r.map(([a,,n])=>` ${a}: ${n},`).join(`
852
856
  authInit = null;
853
857
  throw error;
854
858
  }));
855
- `:"",{asyncIfDeferred:c,deferredArgument:s,deferredParameter:u,loadDeferredLine:h}=le(r),D=a?`
856
- await ensureAuth(env);`:"",b=`${a?"() => auth, identityMemos":"() => null"}${s}`,R=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,m=`env: Env${u}`,A=r.hasFramework?` const buildWorker = (${m}): LunoraWorker =>
857
- host ? withFrameworkWorker(${ne(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${b})) : createWorker(this.buildWorkerOptions(env, ${b}));`:` const buildWorker = (${m}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${b}));`,x=r.hasFramework?"host?: FrameworkHostHandler":"",g=r.emailAgents??[],C=g.length>0?` composed.email = dispatchAgentEmail([
858
- ${g.map(v=>` { agent: lunoraAgentDefinitions.${v.exportName}, className: ${JSON.stringify(v.className)} },`).join(`
859
+
860
+ // For host-owned events (cron, queue, mail), which must not go down with auth. The failure is
861
+ // logged each time: auth retries on the next event, and an isolate that only ever sees these
862
+ // would otherwise repeat it with nothing saying why the admin and auth surfaces are missing.
863
+ const authReady = (env: Env): Promise<boolean> =>
864
+ ensureAuth(env).then(
865
+ () => true,
866
+ (error: unknown) => {
867
+ console.error("[lunora] auth failed to initialise; this event runs without auth:", error);
868
+
869
+ return false;
870
+ },
871
+ );
872
+ `:"",{asyncIfDeferred:c,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=pe(t),{ensureAuthCall:A,ensureRawAuthCall:x,eventWorker:b,eventWorkerLine:m}=ue(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,C=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,O=t.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
873
+ host ? withFrameworkWorker(${ie(t)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,T=t.hasFramework?"host?: FrameworkHostHandler":"",y=t.emailAgents??[],q=y.length>0?` composed.email = dispatchAgentEmail([
874
+ ${y.map(f=>` { agent: lunoraAgentDefinitions.${f.exportName}, className: ${JSON.stringify(f.className)} },`).join(`
859
875
  `)}
860
876
  ]);
861
877
 
862
- `:"",O=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
878
+ `:"",I=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
863
879
  public build(): ComposedApp {
864
880
  return this.assemble();
865
- }${r.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${X(r).join(`
881
+ }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${w}${te(t).join(`
866
882
  `)}
867
883
 
868
884
  /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
@@ -870,11 +886,11 @@ type Selector<Env, T> = (env: Env) => T | undefined;
870
886
 
871
887
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
872
888
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
873
- ${ie(a)}${ce(r)}${r.jurisdiction?`
889
+ ${de(a)}${he(t)}${t.jurisdiction?`
874
890
  // Module scope, so every isolate loading this script (the worker and each Durable
875
891
  // Object class it exports) knows the schema's jurisdiction before a request runs.
876
892
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
877
- declareAppJurisdiction(${JSON.stringify(r.jurisdiction)});
893
+ declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
878
894
  `:""}
879
895
  ${n.join(`
880
896
 
@@ -895,78 +911,75 @@ interface ComposedApp extends LunoraWorker {
895
911
  * first request so per-isolate singletons are built once.
896
912
  */
897
913
  class AppBuilder<Env extends object> {
898
- ${M(r).join(`
914
+ ${_(t).join(`
899
915
  `)}
900
916
 
901
917
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
902
918
 
903
- ${_(r).join(`
919
+ ${U(t).join(`
904
920
 
905
921
  `)}
906
922
 
907
- ${O}
923
+ ${I}
908
924
 
909
925
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
910
- private assemble(${x}): ComposedApp {
911
- const ShardDO = createShardDO({${H(r)}});
926
+ private assemble(${T}): ComposedApp {
927
+ const ShardDO = createShardDO({${F(t)}});
912
928
 
913
929
  // Per-isolate singletons: the worker (and auth instance) are expensive to
914
930
  // build, so the first request constructs them and every later request on
915
931
  // the same isolate reuses them.
916
932
  let worker: LunoraWorker | null = null;
917
933
  ${i}${d}
918
- ${A}
934
+ ${O}
919
935
 
920
936
  const composed: ComposedApp = {
921
937
  ShardDO,
922
938
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
923
- const env = rawEnv as Env;${h}${D}
924
- worker ??= buildWorker(env${s});
939
+ const env = rawEnv as Env;${h}${A}
940
+ worker ??= buildWorker(env${o});
925
941
 
926
942
  return worker.fetch(request, rawEnv, context);
927
943
  },
928
- scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}
929
- worker ??= buildWorker(rawEnv as Env${s});
944
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}${m}
930
945
 
931
- return worker.scheduled(controller, rawEnv, context);
946
+ return ${b}.scheduled(controller, rawEnv, context);
932
947
  },
933
- serverQuery: ${c}(request, rawEnv, reference, args, options) => {${h}
934
- worker ??= buildWorker(rawEnv as Env${s});
948
+ serverQuery: ${c}(request, rawEnv, reference, args, options) => {${h}${x}
949
+ worker ??= buildWorker(rawEnv as Env${o});
935
950
 
936
951
  return worker.serverQuery(request, rawEnv, reference, args, options);
937
- },${r.hasQueue||r.hasFramework?`
938
- queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}
939
- worker ??= buildWorker(rawEnv as Env${s});
952
+ },${t.hasQueue||t.hasFramework?`
953
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}${m}
940
954
 
941
- return worker.queue?.(batch, rawEnv, context);
955
+ return ${b}.queue?.(batch, rawEnv, context);
942
956
  },`:""}
943
957
  };
944
958
 
945
- ${C} if (this.emailHandler) {
959
+ ${q} if (this.emailHandler) {
946
960
  const handler = this.emailHandler;
947
961
 
948
962
  composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
949
963
  }
950
- ${r.hasFramework?`
964
+ ${t.hasFramework?`
951
965
  // A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
952
966
  // does). Nothing in Lunora serves one, so when the app registered no handler
953
967
  // of its own the host's is the only one there is — forward to it rather than
954
968
  // dropping the entry.
955
969
  if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
956
- composed.email = ${c}(message, rawEnv, context) => {${h}
957
- worker ??= buildWorker(rawEnv as Env${s});
970
+ composed.email = ${c}(message, rawEnv, context) => {${h}${m}
958
971
 
959
- return worker.email?.(message, rawEnv, context) ?? Promise.resolve();
972
+ return ${b}.email?.(message, rawEnv, context) ?? Promise.resolve();
960
973
  };
961
974
  }
962
975
  `:""}
963
976
  return composed;
964
977
  }
965
- ${j(r)}${G(r.hasStorage)}
978
+ ${P(t)}${M(t.hasStorage)}
966
979
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
967
- private buildWorkerOptions(env: Env, ${R}): WorkerOptions {
980
+ private buildWorkerOptions(env: Env, ${C}): WorkerOptions {
968
981
  const options: WorkerOptions = {
969
- ${oe(r).join(`
982
+ ${le(t).join(`
970
983
  `)}
971
984
  };
972
985
 
@@ -976,9 +989,9 @@ ${oe(r).join(`
976
989
  options.adminToken = adminToken;
977
990
  }
978
991
 
979
- ${o.join(`
992
+ ${s.join(`
980
993
 
981
- `)}${o.length>0?`
994
+ `)}${s.length>0?`
982
995
 
983
996
  `:""} for (const fn of this.extendFns) {
984
997
  Object.assign(options, fn(env, { ...options }));
@@ -987,7 +1000,7 @@ ${o.join(`
987
1000
  return options;
988
1001
  }
989
1002
  }
990
- ${P(r.hasGlobal)}
1003
+ ${B(t.hasGlobal)}
991
1004
  /**
992
1005
  * Shape of the project's root \`lunora.config.*\`.
993
1006
  *
@@ -1026,5 +1039,5 @@ interface LunoraConfig<Env extends object = object> {
1026
1039
  const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
1027
1040
 
1028
1041
  export { AppBuilder, defineApp };
1029
- export type { ${de(r)} };
1030
- `};export{me as emitApp,be as emitAuthModule};
1042
+ export type { ${be(t)} };
1043
+ `};export{fe as emitApp,ye as emitAuthModule};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-D1HjM_tr.mjs";import"./shard-runtime-DAnfkcDz.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CMbVoHUX.mjs";import"./shard-runtime-HdePIC-P.mjs";import"./shared-BErjtci3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -1,4 +1,4 @@
1
- import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Xt,hashSchemaSnapshot as Zt}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{isHyperdriveGlobalTable as er,isD1GlobalTable as tr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as rr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as nr,a as ar,b as sr,c as or,d as ir,f as dr,g as cr,h as lr,i as ur,j as hr,k as pr,l as mr,m as fr,n as gr,o as br,p as yr,q as wr,s as vr}from"./shard-runtime-DAnfkcDz.mjs";import{u as F,h as kr,s as Sr,a as Rr,I as xr,c as Ar,G as Or,d as Dr}from"./shared-BErjtci3.mjs";import{p as Tr}from"./platform-8oj7iXQy.mjs";import{i as _r}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Er=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!me.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Ir=` /**
1
+ import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Xt,hashSchemaSnapshot as Zt}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{isHyperdriveGlobalTable as er,isD1GlobalTable as tr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as rr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as nr,a as ar,b as sr,c as or,d as ir,f as dr,g as cr,h as lr,i as ur,j as hr,k as pr,l as mr,m as fr,n as gr,o as br,p as yr,q as wr,s as vr}from"./shard-runtime-HdePIC-P.mjs";import{u as F,h as kr,s as Sr,a as Rr,I as xr,c as Ar,G as Or,d as Dr}from"./shared-BErjtci3.mjs";import{p as Tr}from"./platform-8oj7iXQy.mjs";import{i as _r}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Er=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!me.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Ir=` /**
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
@@ -6,7 +6,7 @@ import{LunoraError as N}from"@lunora/errors";import{r as b}from"./json-data-Chfs
6
6
 
7
7
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
8
8
  }
9
- `}:{importFragment:"",override:""},f=(e,o,t,{cast:n="",sync:a=[]}={})=>{const u=`throw new Error(${JSON.stringify(o)});`,c=t.map(s=>` ${s}: ${a===!0||a.includes(s)?"":"async "}() => {
9
+ `}:{importFragment:"",override:""},f=(e,r,t,{cast:n="",sync:a=[]}={})=>{const u=`throw new Error(${JSON.stringify(r)});`,c=t.map(s=>` ${s}: ${a===!0||a.includes(s)?"":"async "}() => {
10
10
  ${u}
11
11
  },`).join(`
12
12
  `);return`
@@ -15,57 +15,58 @@ ${c}
15
15
  }${n};
16
16
  `},h={build:"",configField:"",contextField:"",importLines:[],stub:""},Q=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
17
17
  /** The \`.shardBy()\` tables this shard registers with the shard registry when it writes them. */
18
- const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(o=>JSON.stringify(o)).join(", ")}]);
18
+ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(r=>JSON.stringify(r)).join(", ")}]);
19
19
  `,override:`
20
20
  protected override shardRegistry(): undefined | { namespace: unknown; shardedTables: ReadonlySet<string> } {
21
21
  const namespace = config.shardRegistry?.((this.env ?? {}) as Record<string, unknown>);
22
22
 
23
23
  return namespace === undefined ? undefined : { namespace, shardedTables: SHARDED_TABLES };
24
24
  }
25
- `},M=(e,o)=>e?{build:`
26
- const flags: import("${o}").LunoraFlags = createFlags(flagsConfig, env, {
25
+ `},M=(e,r)=>e?{build:`
26
+ const flags: import("${r}").LunoraFlags = createFlags(flagsConfig, env, {
27
27
  provider: () => config.flags?.(env),
28
28
  targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
29
29
  });
30
30
  `,configField:`
31
- flags?: (env: Record<string, unknown>) => import("${o}").Provider;`,contextField:`
32
- flags,`,importLines:[`import { createFlags } from "${o}";`,'import flagsConfig from "../flags.js";'],stub:""}:h,K=e=>e?{build:`
31
+ flags?: (env: Record<string, unknown>) => import("${r}").Provider;`,contextField:`
32
+ flags,`,importLines:[`import { createFlags } from "${r}";`,'import flagsConfig from "../flags.js";'],stub:""}:h,K=e=>e?{build:`
33
33
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
34
34
  `,configField:"",contextField:`
35
35
  notify,
36
36
  push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:h,H=e=>e?{build:`
37
37
  const envConfig = lunoraEnvContract.${e.exportName}(env);
38
38
  `,configField:"",contextField:`
39
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:h,G=(e,o,t)=>{if(!o)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=s=>`
39
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:h,G=(e,r,t)=>{if(!r)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=o=>`
40
40
  const env = (this.env ?? {}) as Record<string, unknown>;
41
41
  const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
42
42
  provider: () => config.flags?.(env),
43
- targetingKey: ${s},
43
+ targetingKey: ${o},
44
44
  });`,a=`
45
45
  /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
46
46
  const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }>')};
47
- `,u=`
47
+ `,c=`
48
48
  protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${n("undefined")}
49
49
  const evalContext = context as import("${t}").EvaluationContext | undefined;
50
- const evaluations: FlagsResult["flags"] = [];
51
-
52
- for (const entry of LUNORA_FLAG_KEYS) {
53
- // eslint-disable-next-line no-await-in-loop -- flags evaluate sequentially; each shares the single memoized provider client
54
- const details =
55
- entry.type === "boolean"
56
- ? await flags.details.boolean(entry.key, false, evalContext)
57
- : entry.type === "number"
58
- ? await flags.details.number(entry.key, 0, evalContext)
59
- : entry.type === "string"
60
- ? await flags.details.string(entry.key, "", evalContext)
61
- : await flags.details.object(entry.key, {}, evalContext);
50
+ // Concurrent, not sequential: against a remote provider every read is a round
51
+ // trip, and the request-scoped bind in createFlags is shared by all of them.
52
+ const evaluations: FlagsResult["flags"] = await Promise.all(
53
+ LUNORA_FLAG_KEYS.map(async (entry) => {
54
+ const details =
55
+ entry.type === "boolean"
56
+ ? await flags.details.boolean(entry.key, false, evalContext)
57
+ : entry.type === "number"
58
+ ? await flags.details.number(entry.key, 0, evalContext)
59
+ : entry.type === "string"
60
+ ? await flags.details.string(entry.key, "", evalContext)
61
+ : await flags.details.object(entry.key, {}, evalContext);
62
62
 
63
- evaluations.push({ errorCode: details.errorCode, key: entry.key, reason: details.reason, type: entry.type, value: details.value, variant: details.variant });
64
- }
63
+ return { errorCode: details.errorCode, key: entry.key, reason: details.reason, type: entry.type, value: details.value, variant: details.variant };
64
+ }),
65
+ );
65
66
 
66
67
  return { configured: true, flags: evaluations };
67
68
  }
68
- `,c=`
69
+ `,s=`
69
70
  protected override runFlagSubscriptionRead(_functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<unknown> {${n("() => flagsConfig.identify?.({ identity: identity?.identity ?? null, userId: identity?.userId ?? null })")}
70
71
  const key = typeof args.key === "string" ? args.key : "";
71
72
 
@@ -98,7 +99,7 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
98
99
 
99
100
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
100
101
  }
101
- `;return{constant:a,evaluateOverride:u,subscriptionOverride:c}},S=()=>({build:`
102
+ `;return{constant:a,evaluateOverride:c,subscriptionOverride:s}},S=()=>({build:`
102
103
  const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
103
104
  // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
104
105
  // function path + trace id into createAi, which folds them into the
@@ -133,23 +134,23 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
133
134
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
134
135
  : x402Stub;
135
136
  `,configField:`
136
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:f("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),C={access:L,ai:S,r2sql:A,x402:_},F=e=>e.shardBinding==="bespoke",E=e=>typeof e.shardBinding=="object",m=" ",O=(e,o,t)=>{const n=`${e}Binding`,{factory:a}=t;let u=`(${n} as ${o})`;if(a!==void 0){const c=`${n} as ${t.bindingType??o}`;u=a.option===void 0?`${a.name}(${c})`:`${a.name}({ ${a.option}: ${c} })`}return`${n} ? ${u} : ${e}Stub`},P=(e,o,t)=>{const n=O(e,o,t),a=`${m}const ${e}Binding = config.${e}?.(env) ?? (env as Record<string, unknown>).${t.envName};
137
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,importLines:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],stub:f("x402Stub: X402Pay","ctx.x402: no pay rail configured. Pass `x402` to createShardDO().",["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}),C={access:L,ai:S,r2sql:A,x402:_},F=e=>e.shardBinding==="bespoke",E=e=>typeof e.shardBinding=="object",m=" ",O=(e,r,t)=>{const n=`${e}Binding`,{factory:a}=t;let u=`(${n} as ${r})`;if(a!==void 0){const c=`${n} as ${t.bindingType??r}`;u=a.option===void 0?`${a.name}(${c})`:`${a.name}({ ${a.option}: ${c} })`}return`${n} ? ${u} : ${e}Stub`},P=(e,r,t)=>{const n=O(e,r,t),a=`${m}const ${e}Binding = config.${e}?.(env) ?? (env as Record<string, unknown>).${t.envName};
137
138
  `,u=t.unvouchableReads??[];return u.length===0?`
138
- ${a}${m}const ${e}: ${o} = ${n};
139
+ ${a}${m}const ${e}: ${r} = ${n};
139
140
  `:`
140
141
  ${a}${m}// ${t.envName} is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
141
142
  ${m}// when a value changes — a subscription that read one can never be proven
142
143
  ${m}// current on reconnect and must re-snapshot. Reads only; writes stay unstamped.
143
- ${m}const ${e}: ${o} = markUnvouchableReads(${n}, options.onRead, [
144
+ ${m}const ${e}: ${r} = markUnvouchableReads(${n}, options.onRead, [
144
145
  ${u.map(c=>`${m} ${JSON.stringify(c)},`).join(`
145
146
  `)}
146
147
  ${m}]);
147
- `},q=(e,o,t)=>{const{binding:n,clientType:a}=t,u=f(`${e}Stub: ${a}`,t.missingMessage,t.stubMethods,{sync:t.syncStubMethods});if(n===void 0){const r=t.instrument===void 0?`config.${e}(env)`:`this.${t.instrument}(config.${e}(env), logFunctionPath, traceAnchor, observability)`;return{build:`
148
- ${m}const ${e}: ${a} = config.${e} ? ${r} : ${e}Stub;
148
+ `},q=(e,r,t)=>{const{binding:n,clientType:a}=t,u=f(`${e}Stub: ${a}`,t.missingMessage,t.stubMethods,{sync:t.syncStubMethods});if(n===void 0){const o=t.instrument===void 0?`config.${e}(env)`:`this.${t.instrument}(config.${e}(env), logFunctionPath, traceAnchor, observability)`;return{build:`
149
+ ${m}const ${e}: ${a} = config.${e} ? ${o} : ${e}Stub;
149
150
  `,configField:`
150
- ${e}?: (env: Record<string, unknown>) => ${a};`,importLines:[`import type { ${a} } from "${o}";`],stub:u}}const c=n.bindingType??a,s=[...new Set([c,a])].toSorted((r,i)=>r.localeCompare(i));return{build:P(e,a,n),configField:`
151
- ${e}?: (env: Record<string, unknown>) => ${c};`,importLines:[`import type { ${s.join(", ")} } from "${o}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${o}";`]],stub:u}},V=e=>{const o=[],t=[];let n="",a="",u="",c="",s="";for(const r of k.filter(({key:i})=>e.has(i))){let i;if(F(r))i=C[r.key]();else if(E(r))i=q(r.contextProperty,r.moduleSpecifier,r.shardBinding);else continue;const d=r.contextProperty;t.push(...i.importLines),a+=i.configField,s+=i.stub,r.tier==="every"?(u+=i.build,c+=`
152
- ${d},`):(n+=i.build,o.push(d))}return{actionBuild:n,actionFields:o,configFields:a,everyBuild:u,everyFields:c,importLines:t,stubs:s}},J=(e,o)=>{if(e.length===0)return"";const t=o?`, ${JSON.stringify(o)}`:"",n=e.map(i=>{l(i.exportName,`container export "${i.exportName}"`),l(i.className,`container class "${i.className}"`);const d=i.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${i.exportName}\` definition (binding \`${i.bindingName}\`). */
151
+ ${e}?: (env: Record<string, unknown>) => ${a};`,importLines:[`import type { ${a} } from "${r}";`],stub:u}}const c=n.bindingType??a,s=[...new Set([c,a])].toSorted((o,i)=>o.localeCompare(i));return{build:P(e,a,n),configField:`
152
+ ${e}?: (env: Record<string, unknown>) => ${c};`,importLines:[`import type { ${s.join(", ")} } from "${r}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${r}";`]],stub:u}},V=e=>{const r=[],t=[];let n="",a="",u="",c="",s="";for(const o of k.filter(({key:i})=>e.has(i))){let i;if(F(o))i=C[o.key]();else if(E(o))i=q(o.contextProperty,o.moduleSpecifier,o.shardBinding);else continue;const d=o.contextProperty;t.push(...i.importLines),a+=i.configField,s+=i.stub,o.tier==="every"?(u+=i.build,c+=`
153
+ ${d},`):(n+=i.build,r.push(d))}return{actionBuild:n,actionFields:r,configFields:a,everyBuild:u,everyFields:c,importLines:t,stubs:s}},J=(e,r)=>{if(e.length===0)return"";const t=r?`, ${JSON.stringify(r)}`:"",n=e.map(i=>{l(i.exportName,`container export "${i.exportName}"`),l(i.className,`container class "${i.className}"`);const d=i.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${i.exportName}\` definition (binding \`${i.bindingName}\`). */
153
154
  export class ${i.className} extends ${d} {
154
155
  public constructor(ctx: ConstructorParameters<typeof ${d}>[0], env: Record<string, unknown>) {
155
156
  super(ctx, env, ${i.exportName}, "${i.exportName}"${t});
@@ -181,16 +182,16 @@ ${u?`
181
182
  */
182
183
  export { DirectoryBackupGateway, S3Gateway } from "@lunora/container/sandbox";
183
184
  `:""}
184
- ${n}`},Y=(e,o)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`container export "${n.exportName}"`),l(n.bindingName,`container binding "${n.bindingName}"`);const t=e.map(n=>{const a=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${a} },`}).join(`
185
+ ${n}`},Y=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`container export "${n.exportName}"`),l(n.bindingName,`container binding "${n.bindingName}"`);const t=e.map(n=>{const a=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${a} },`}).join(`
185
186
  `);return{build:`
186
- const containers = createContainerContext(env, LUNORA_CONTAINERS, ${o?JSON.stringify(o):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
187
+ const containers = createContainerContext(env, LUNORA_CONTAINERS, ${r?JSON.stringify(r):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
187
188
  `,contextField:`
188
189
  containers,`,importLines:['import type { ContainerBindingSpec } from "@lunora/container";','import { createContainerContext } from "@lunora/container";'],specs:`
189
190
  /** Wiring specs for \`ctx.containers\` (codegen-derived from \`lunora/containers.ts\`). */
190
191
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
191
192
  ${t}
192
193
  ];
193
- `}},X=e=>{if(e.length===0)return"";const o=e.map(n=>(l(n.exportName,`workflow export "${n.exportName}"`),l(n.className,`workflow class "${n.className}"`),`/** WorkflowEntrypoint for the \`${n.exportName}\` definition, reached as \`ctx.exports.${n.className}\`. */
194
+ `}},X=e=>{if(e.length===0)return"";const r=e.map(n=>(l(n.exportName,`workflow export "${n.exportName}"`),l(n.className,`workflow class "${n.className}"`),`/** WorkflowEntrypoint for the \`${n.exportName}\` definition, reached as \`ctx.exports.${n.className}\`. */
194
195
  export class ${n.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${n.exportName}>, WorkflowOutputOf<typeof ${n.exportName}>> {
195
196
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
196
197
  super(ctx, env, ${n.exportName}, "${n.exportName}");
@@ -218,20 +219,20 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
218
219
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
219
220
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
220
221
 
221
- ${o}`},z=e=>{if(e.length===0)return"";const t=e.filter(s=>s.voice).length>0,n=e.map(s=>{l(s.exportName,`agent export "${s.exportName}"`),l(s.className,`agent class "${s.className}"`);const r=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent, reached as \`ctx.exports.${s.className}\`. */
222
+ ${r}`},z=e=>{if(e.length===0)return"";const t=e.filter(s=>s.voice).length>0,n=e.map(s=>{l(s.exportName,`agent export "${s.exportName}"`),l(s.className,`agent class "${s.className}"`);const o=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent, reached as \`ctx.exports.${s.className}\`. */
222
223
  export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
223
224
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
224
225
  super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
225
226
  }
226
227
  }
227
- `;if(!s.voice)return r;const i=s.voiceClassName??"",d=s.voiceBindingName??"";l(i,`agent voice class "${i}"`);const p=`
228
+ `;if(!s.voice)return o;const i=s.voiceClassName??"",d=s.voiceBindingName??"";l(i,`agent voice class "${i}"`);const p=`
228
229
  /** Voice-session Durable Object for the \`${s.exportName}\` agent (binding \`${d}\`). */
229
230
  export class ${i} extends VoiceSessionDO {
230
231
  public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
231
232
  super(ctx, env, ${s.exportName}, "${s.exportName}");
232
233
  }
233
234
  }
234
- `;return`${r}${p}`}).join(`
235
+ `;return`${o}${p}`}).join(`
235
236
  `),a=e.map(s=>s.exportName).join(", ");return`${g}/**
236
237
  * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
237
238
  * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
@@ -246,8 +247,8 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
246
247
 
247
248
  import { ${a} } from "../agents.js";
248
249
 
249
- ${n}`},y=e=>e.env===void 0?"the top level":`env.${e.env}`,v=(e,o)=>{const t=e.filter(r=>r.mode==="push"),n=new Map(t.map(r=>[r.bindingName,r])),a=new Map(e.map(r=>[r.name,r])),u=new Map(t.map(r=>[r.name,r])),c=new Map,s=[];for(const r of o){const i=n.get(r.binding);if(i===void 0||r.queue===i.name)continue;const d=a.get(r.queue);if(d!==void 0){s.push(`${y(r)} maps \`${r.binding}\` to "${r.queue}", the declared name of queue \`${d.exportName}\` — batches for "${r.queue}" go to \`${d.exportName}\`, never \`${i.exportName}\`.`);continue}const p=u.get(r.queue);if(p===void 0)u.set(r.queue,i),c.set(r.queue,r);else if(p!==i){const x=c.get(r.queue);s.push(`"${r.queue}" is aliased to \`${p.exportName}\` by ${x===void 0?"an earlier producer":y(x)} and to \`${i.exportName}\` by ${y(r)} — batches for it go to \`${p.exportName}\`.`)}}return{conflicts:s,routes:u}},Z=(e,o)=>v(e,o).conflicts.map(t=>({cacheKey:`queue_alias_conflict:${t}`,categories:["SCHEMA"],description:"Codegen routes a delivered batch by its queue name. A wrangler.jsonc producer that maps a queue's binding to another name adds that name as a route, so it must not be another queue's declared name or an alias another scope gives a different queue.",detail:t,facing:"INTERNAL",level:"WARN",metadata:{},name:"queue_alias_conflict",remediation:"Give each queue a distinct name in every `env.<name>` block of wrangler.jsonc, then rerun codegen.",title:"Queue name routes to a different handler than wrangler.jsonc implies"})),ee=(e,o=[])=>{const t=e.filter(c=>c.mode==="push");if(t.length===0)return"";for(const c of t)l(c.exportName,`queue export "${c.exportName}"`);const n=[...Map.groupBy(t,c=>c.filePath)].map(([c,s])=>`import { ${s.map(r=>r.exportName).join(", ")} } from "../${c}.js";`).join(`
250
- `),{routes:a}=v(e,o),u=[...a].map(([c,s])=>` ${JSON.stringify(c)}: { binding: ${JSON.stringify(s.bindingName)}, definition: ${s.exportName}, exportName: ${JSON.stringify(s.exportName)} },`).join(`
250
+ ${n}`},y=e=>e.env===void 0?"the top level":`env.${e.env}`,v=(e,r)=>{const t=e.filter(o=>o.mode==="push"),n=new Map(t.map(o=>[o.bindingName,o])),a=new Map(e.map(o=>[o.name,o])),u=new Map(t.map(o=>[o.name,o])),c=new Map,s=[];for(const o of r){const i=n.get(o.binding);if(i===void 0||o.queue===i.name)continue;const d=a.get(o.queue);if(d!==void 0){s.push(`${y(o)} maps \`${o.binding}\` to "${o.queue}", the declared name of queue \`${d.exportName}\` — batches for "${o.queue}" go to \`${d.exportName}\`, never \`${i.exportName}\`.`);continue}const p=u.get(o.queue);if(p===void 0)u.set(o.queue,i),c.set(o.queue,o);else if(p!==i){const x=c.get(o.queue);s.push(`"${o.queue}" is aliased to \`${p.exportName}\` by ${x===void 0?"an earlier producer":y(x)} and to \`${i.exportName}\` by ${y(o)} — batches for it go to \`${p.exportName}\`.`)}}return{conflicts:s,routes:u}},Z=(e,r)=>v(e,r).conflicts.map(t=>({cacheKey:`queue_alias_conflict:${t}`,categories:["SCHEMA"],description:"Codegen routes a delivered batch by its queue name. A wrangler.jsonc producer that maps a queue's binding to another name adds that name as a route, so it must not be another queue's declared name or an alias another scope gives a different queue.",detail:t,facing:"INTERNAL",level:"WARN",metadata:{},name:"queue_alias_conflict",remediation:"Give each queue a distinct name in every `env.<name>` block of wrangler.jsonc, then rerun codegen.",title:"Queue name routes to a different handler than wrangler.jsonc implies"})),ee=(e,r=[])=>{const t=e.filter(c=>c.mode==="push");if(t.length===0)return"";for(const c of t)l(c.exportName,`queue export "${c.exportName}"`);const n=[...Map.groupBy(t,c=>c.filePath)].map(([c,s])=>`import { ${s.map(o=>o.exportName).join(", ")} } from "../${c}.js";`).join(`
251
+ `),{routes:a}=v(e,r),u=[...a].map(([c,s])=>` ${JSON.stringify(c)}: { binding: ${JSON.stringify(s.bindingName)}, definition: ${s.exportName}, exportName: ${JSON.stringify(s.exportName)} },`).join(`
251
252
  `);return`${g}/**
252
253
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
253
254
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
@@ -262,25 +263,25 @@ ${n}
262
263
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
263
264
  ${u}
264
265
  };
265
- `},te=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`workflow export "${t.exportName}"`),l(t.className,`workflow class "${t.className}"`);const o=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}" },`).join(`
266
+ `},te=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`workflow export "${t.exportName}"`),l(t.className,`workflow class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}" },`).join(`
266
267
  `);return{build:`
267
268
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS, this.state.exports);
268
269
  `,contextField:`
269
270
  workflows,`,importLines:['import type { WorkflowBindingSpec } from "@lunora/workflow";','import { createWorkflowContext } from "@lunora/workflow";'],specs:`
270
271
  /** Wiring specs for \`ctx.workflows\` (codegen-derived from \`lunora/workflows.ts\`). */
271
272
  const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
272
- ${o}
273
+ ${r}
273
274
  ];
274
- `}},ne=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`queue export "${t.exportName}"`),l(t.bindingName,`queue binding "${t.bindingName}"`);const o=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}", name: ${JSON.stringify(t.name)} },`).join(`
275
+ `}},ne=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)l(t.exportName,`queue export "${t.exportName}"`),l(t.bindingName,`queue binding "${t.bindingName}"`);const r=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}", name: ${JSON.stringify(t.name)} },`).join(`
275
276
  `);return{build:`
276
277
  const queues = createQueueContext(env, LUNORA_QUEUES);
277
278
  `,contextField:`
278
279
  queues,`,importLines:['import type { QueueBindingSpec } from "@lunora/queue";','import { createQueueContext } from "@lunora/queue";'],specs:`
279
280
  /** Wiring specs for \`ctx.queues\` (codegen-derived from \`lunora/queues.ts\`). */
280
281
  const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
281
- ${o}
282
+ ${r}
282
283
  ];
283
- `}},oe=(e,o)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const a=w(o,n.exportName).map(u=>`{ binding: "${u.bindingName}", exportName: "${u.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${a}] },`}).join(`
284
+ `}},re=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{l(n.exportName,`topic export "${n.exportName}"`);const a=w(r,n.exportName).map(u=>`{ binding: "${u.bindingName}", exportName: "${u.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${a}] },`}).join(`
284
285
  `);return{build:`
285
286
  const topics = createTopicContext(env, LUNORA_TOPICS);
286
287
  `,contextField:`
@@ -289,18 +290,18 @@ ${o}
289
290
  const LUNORA_TOPICS: ReadonlyArray<TopicBindingSpec> = [
290
291
  ${t}
291
292
  ];
292
- `}},re=(e,o)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const t=e.map(n=>(l(n.name,`service "${n.name}"`),l(n.binding,`service binding "${n.binding}"`),` { binding: "${n.binding}", name: "${n.name}"${n.rpcEntrypoint===void 0?"":", rpc: true"} },`)).join(`
293
+ `}},oe=(e,r)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const t=e.map(n=>(l(n.name,`service "${n.name}"`),l(n.binding,`service binding "${n.binding}"`),` { binding: "${n.binding}", name: "${n.name}"${n.rpcEntrypoint===void 0?"":", rpc: true"} },`)).join(`
293
294
  `);return{build:`
294
295
  const services = createServices(env, LUNORA_SERVICES);
295
- `,importLines:[`import type { ServiceBindingSpec } from "${o}";`,`import { createServices } from "${o}";`],specs:`
296
+ `,importLines:[`import type { ServiceBindingSpec } from "${r}";`,`import { createServices } from "${r}";`],specs:`
296
297
  /** Wiring specs for \`ctx.services\` (codegen-derived from \`lunora.config\` \`services\`). */
297
298
  const LUNORA_SERVICES: ReadonlyArray<ServiceBindingSpec> = [
298
299
  ${t}
299
300
  ];
300
- `}},se=(e,o)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`agent export "${n.exportName}"`),l(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
301
+ `}},se=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)l(n.exportName,`agent export "${n.exportName}"`),l(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
301
302
  `);return{build:`
302
303
  const agents = createAgentContext(env, LUNORA_AGENTS, { exports: this.state.exports });
303
- `,contextField:o?`
304
+ `,contextField:r?`
304
305
  agents,
305
306
  agentSecrets: this.secretValues,`:`
306
307
  agents,`,importLines:['import { createAgentContext } from "@lunora/agent";','import type { AgentBindingSpec } from "@lunora/agent";'],specs:`
@@ -308,24 +309,24 @@ ${t}
308
309
  const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
309
310
  ${t}
310
311
  ];
311
- `}},$=(e,o,t,n,a)=>({constant:`
312
+ `}},$=(e,r,t,n,a)=>({constant:`
312
313
  ${a}
313
- const ${e} = ${b(n,o)};
314
+ const ${e} = ${b(n,r)};
314
315
  `,override:`
315
- protected override ${t}(): ${o} {
316
+ protected override ${t}(): ${r} {
316
317
  return ${e};
317
318
  }
318
- `}),ae=(e,o)=>{if(e.length===0)return{constant:"",override:""};const t={...o.length===0?{}:{eventTypes:o.map(n=>n.type)},workflows:e.map(n=>({className:n.className,exportName:n.exportName,name:n.name}))};return $("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. */")},ie=(e,o)=>{if(e.length===0||o.length===0)return{constant:"",override:""};for(const t of o)if(l(t.exportName,"workflow event export name"),!R.test(t.filePath))throw new N("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe workflow event file path: ${JSON.stringify(t.filePath)}`);return{constant:`
319
+ `}),ae=(e,r)=>{if(e.length===0)return{constant:"",override:""};const t={...r.length===0?{}:{eventTypes:r.map(n=>n.type)},workflows:e.map(n=>({className:n.className,exportName:n.exportName,name:n.name}))};return $("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. */")},ie=(e,r)=>{if(e.length===0||r.length===0)return{constant:"",override:""};for(const t of r)if(l(t.exportName,"workflow event export name"),!R.test(t.filePath))throw new N("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe workflow event file path: ${JSON.stringify(t.filePath)}`);return{constant:`
319
320
  /** Declared workflow events (\`defineWorkflowEvent\` exports), loaded by type when an admin \`sendWorkflowEvent\` parses its payload. */
320
321
  const LUNORA_WORKFLOW_EVENTS: ReadonlyMap<string, () => Promise<{ payload: { parse: (value: unknown) => unknown } }>> = new Map([
321
- ${o.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").then((module) => module.${t.exportName})],`).join(`
322
+ ${r.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").then((module) => module.${t.exportName})],`).join(`
322
323
  `)}
323
324
  ]);
324
325
  `,override:`
325
326
  protected override async workflowEvent(type: string): Promise<{ payload: { parse: (value: unknown) => unknown } } | undefined> {
326
327
  return LUNORA_WORKFLOW_EVENTS.get(type)?.();
327
328
  }
328
- `}},ce=e=>{if(e.length===0)return{constant:"",override:""};const o={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return $("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",o,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},W=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],ue=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
329
+ `}},ce=e=>{if(e.length===0)return{constant:"",override:""};const r={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return $("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",r,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},W=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],ue=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
329
330
  const paymentsByContext = new WeakMap<object, LunoraPayment>();
330
331
  `,configField:`
331
332
  payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
@@ -340,4 +341,4 @@ ${o.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").
340
341
  }
341
342
 
342
343
  return payments;
343
- },`,stub:f("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",W,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},le=(e,o,t,n,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","SensitiveScope",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...o?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{M as a,G as b,H as c,ne as d,V as e,oe as f,re as g,Y as h,te as i,se as j,ue as k,ae as l,ie as m,ce as n,Q as o,le as p,U as q,f as r,K as s,z as t,J as u,X as v,Z as w,ee as x};
344
+ },`,stub:f("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",W,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},le=(e,r,t,n,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","SensitiveScope",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{M as a,G as b,H as c,ne as d,V as e,re as f,oe as g,Y as h,te as i,se as j,ue as k,ae as l,ie as m,ce as n,Q as o,le as p,U as q,f as r,K as s,z as t,J as u,X as v,Z as w,ee as x};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.377",
3
+ "version": "1.0.0-alpha.379",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,15 +50,15 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/advisor": "1.0.0-alpha.275",
54
- "@lunora/agent": "1.0.0-alpha.266",
55
- "@lunora/container": "1.0.0-alpha.100",
53
+ "@lunora/advisor": "1.0.0-alpha.277",
54
+ "@lunora/agent": "1.0.0-alpha.268",
55
+ "@lunora/container": "1.0.0-alpha.102",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
57
  "@lunora/platform": "1.0.0-alpha.76",
58
- "@lunora/queue": "1.0.0-alpha.134",
59
- "@lunora/scheduler": "1.0.0-alpha.159",
60
- "@lunora/values": "1.0.0-alpha.86",
61
- "@lunora/workflow": "1.0.0-alpha.101",
58
+ "@lunora/queue": "1.0.0-alpha.136",
59
+ "@lunora/scheduler": "1.0.0-alpha.161",
60
+ "@lunora/values": "1.0.0-alpha.88",
61
+ "@lunora/workflow": "1.0.0-alpha.103",
62
62
  "@visulima/fs": "7.0.0",
63
63
  "jiti": "^2.7.0",
64
64
  "quicktype-core": "^26.0.0",