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

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-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
+ 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-D4Em7RoZ.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-CJ3djlcz.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-DmDBaK79.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-BtEGoPTf.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-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} => ({
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-DmDBaK79.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-D4Em7RoZ.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-BtEGoPTf.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-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
+ 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-BtEGoPTf.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,4 +1,4 @@
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?`
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,c=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);
@@ -339,7 +339,7 @@ const buildGlobalCdcApplier =
339
339
 
340
340
  return request.changes.length;
341
341
  };
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} */
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> = {};"]:[],...c(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
343
  public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
344
344
  this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
345
345
 
@@ -398,7 +398,7 @@ const buildGlobalCdcApplier =
398
398
  this.shardSelector = selector;
399
399
 
400
400
  return this;
401
- }`,...l(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
401
+ }`,...c(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
402
402
  public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
403
403
  this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
404
404
 
@@ -411,7 +411,7 @@ const buildGlobalCdcApplier =
411
411
  }`]:[],...H(e)],F=e=>{const r=a=>e.hasScheduler?`
412
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
- d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
414
+ d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null | undefined }) => {
415
415
  const env = rawEnv as Env;
416
416
  const database = this.globalDeclaration?.d1(env);
417
417
 
@@ -422,16 +422,30 @@ const buildGlobalCdcApplier =
422
422
  const origin = this.globalDeclaration?.origin?.(env);
423
423
  const crossShard = origin
424
424
  ? createCrossShardRelationCapabilities({
425
- ...(request?.identity === undefined ? {} : { identity: request.identity }),
425
+ get identity() {
426
+ return request?.identity;
427
+ },
426
428
  origin,
427
- ...(request?.userId == null ? {} : { userId: request.userId }),
429
+ get userId() {
430
+ return request?.userId ?? undefined;
431
+ },
428
432
  })
429
433
  : undefined;
430
434
 
431
435
  return createD1CtxDb({
432
436
  ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("D1CtxDbOptions")}
433
437
  ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
434
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
438
+ // Getters, like the cross-shard identity above: reading the
439
+ // request's caller marks the live query as caller-dependent, so
440
+ // it may happen only when a \`.serverDefault\` column is stamped.
441
+ auth: {
442
+ get identity() {
443
+ return request?.identity ?? null;
444
+ },
445
+ get userId() {
446
+ return request?.userId ?? null;
447
+ },
448
+ },
435
449
  // Forwarded from the shard's own \`cdc\` config, so ONE
436
450
  // switch governs both changelogs. Built without it, the
437
451
  // global \`__cdc_log\` is never written and the shape
@@ -448,7 +462,7 @@ const buildGlobalCdcApplier =
448
462
  }
449
463
  : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
450
464
  ? {
451
- hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
465
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | null | undefined }) => {
452
466
  const env = rawEnv as Env;
453
467
  const declaration = this.hyperdriveGlobalDeclaration;
454
468
  const exec = declaration?.exec(env) as SqlExec | undefined;
@@ -460,16 +474,30 @@ const buildGlobalCdcApplier =
460
474
  const origin = declaration.origin?.(env);
461
475
  const crossShard = origin
462
476
  ? createCrossShardRelationCapabilities({
463
- ...(request?.identity === undefined ? {} : { identity: request.identity }),
477
+ get identity() {
478
+ return request?.identity;
479
+ },
464
480
  origin,
465
- ...(request?.userId == null ? {} : { userId: request.userId }),
481
+ get userId() {
482
+ return request?.userId ?? undefined;
483
+ },
466
484
  })
467
485
  : undefined;
468
486
 
469
487
  return createHyperdriveGlobalCtxDb({
470
488
  ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("SqlCtxDbOptions")}
471
489
  ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
472
- auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
490
+ // Getters, like the cross-shard identity above: reading the
491
+ // request's caller marks the live query as caller-dependent, so
492
+ // it may happen only when a \`.serverDefault\` column is stamped.
493
+ auth: {
494
+ get identity() {
495
+ return request?.identity ?? null;
496
+ },
497
+ get userId() {
498
+ return request?.userId ?? null;
499
+ },
500
+ },
473
501
  // See the D1 twin: one \`cdc\` switch, both changelogs.
474
502
  cdc: request?.cdc ?? false,
475
503
  engine: declaration.engine as HyperdriveEngine,
@@ -488,10 +516,10 @@ const buildGlobalCdcApplier =
488
516
  ? {
489
517
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
490
518
  }
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?`
519
+ : {}),`]:[],...c(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
520
  ${t.join(`
493
521
  `)}
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?`
522
+ `:""},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",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...n?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],l=[...t||a?["createCrossShardRelationCapabilities"]:[],...c(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 { ${l} } from "${i}";`]},te=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:s,hasQueue:i,hasScheduler:d,hasStorage:l,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";']:[],...l?['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
523
  // The schema's jurisdiction pins the auth object like every other DO.
496
524
  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
525
  ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${ae(r.shardMode)}],`).join(`
@@ -499,14 +527,14 @@ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${ae(r.shardMode)}],`
499
527
  ]);
500
528
 
501
529
  options.listSchemaTables = () => [...tableSharding.keys()];
502
- options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...l(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
530
+ options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...c(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
503
531
 
504
532
  if (shardRegistry) {
505
533
  options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
506
534
  }`]:[]],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
535
  ${D(e).join(`
508
536
  `)}
509
- ], host)`:"host",ce=e=>[...ne(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
537
+ ], host)`:"host",le=e=>[...ne(e),...e.hasScheduler?[` if (this.schedulerDeclaration) {
510
538
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
511
539
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
512
540
  const source = workflowEnv as Record<string, unknown>;
@@ -772,7 +800,7 @@ ${D(e).join(`
772
800
  }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
773
801
  ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
774
802
  `)}
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?`
803
+ };`]:[]],ce=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
804
  /** The identity memo per \`env\` object, owned by one assembled worker. */
777
805
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
778
806
  `:"",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`
@@ -798,7 +826,7 @@ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
798
826
  const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"worker",eventWorkerLine:`
799
827
  worker ??= ${t};`}},pe=e=>R(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
800
828
  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;
829
+ `:"",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=le(t),i=a?` let auth: LunoraAuth | null = null;
802
830
  let authInit: Promise<void> | null = null;
803
831
  // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
804
832
  // \`assemble()\` has its own auth closure and must not share.
@@ -869,7 +897,7 @@ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
869
897
  return false;
870
898
  },
871
899
  );
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 =>
900
+ `:"",{asyncIfDeferred:l,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
901
  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
902
  ${y.map(f=>` { agent: lunoraAgentDefinitions.${f.exportName}, className: ${JSON.stringify(f.className)} },`).join(`
875
903
  `)}
@@ -945,7 +973,7 @@ ${O}
945
973
 
946
974
  return ${b}.scheduled(controller, rawEnv, context);
947
975
  },
948
- serverQuery: ${c}(request, rawEnv, reference, args, options) => {${h}${x}
976
+ serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${x}
949
977
  worker ??= buildWorker(rawEnv as Env${o});
950
978
 
951
979
  return worker.serverQuery(request, rawEnv, reference, args, options);
@@ -967,7 +995,7 @@ ${t.hasFramework?`
967
995
  // of its own the host's is the only one there is — forward to it rather than
968
996
  // dropping the entry.
969
997
  if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
970
- composed.email = ${c}(message, rawEnv, context) => {${h}${m}
998
+ composed.email = ${l}(message, rawEnv, context) => {${h}${m}
971
999
 
972
1000
  return ${b}.email?.(message, rawEnv, context) ?? Promise.resolve();
973
1001
  };
@@ -979,7 +1007,7 @@ ${P(t)}${M(t.hasStorage)}
979
1007
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
980
1008
  private buildWorkerOptions(env: Env, ${C}): WorkerOptions {
981
1009
  const options: WorkerOptions = {
982
- ${le(t).join(`
1010
+ ${ce(t).join(`
983
1011
  `)}
984
1012
  };
985
1013
 
@@ -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-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
+ import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DmDBaK79.mjs";import"./shard-runtime-BtEGoPTf.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-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=` /**
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-BtEGoPTf.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"],Ir=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}},Er=` /**
2
2
  * The bare writer every admin/maintenance entry point writes through.
3
3
  *
4
4
  * Admin and maintenance writes go through the SAME reactive-cache hooks as a
@@ -30,7 +30,7 @@ import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,b=(r="")=>` const writer = this.adminWriter(${r});`,Cr=`${Ir}
33
+ }`,b=(r="")=>` const writer = this.adminWriter(${r});`,Cr=`${Er}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -234,7 +234,7 @@ ${b()}
234
234
  await applyCdcChanges(writer, args.changes);
235
235
 
236
236
  return { applied: args.changes.length };
237
- }`,Lr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,containersBuild:n,containersContextField:a,databaseOptions:i,everyContextBuild:u,everyContextField:h,facadeBlock:m,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:f=!1,notifyBuild:c,ormContextField:y,paymentsBuild:U,paymentsContextField:A,queuesBuild:B,queuesContextField:j,topicsBuild:R,topicsContextField:W,vectorsBuild:d,vectorsContextField:w,workflowsBuild:I,workflowsContextField:K})=>{const C=t.length>0,L=y===""?"{ db }":"{ db, orm: bindOrm(facade) }",H=y===""?"":`
237
+ }`,Lr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,containersBuild:n,containersContextField:a,databaseOptions:i,everyContextBuild:u,everyContextField:h,facadeBlock:m,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:f=!1,notifyBuild:c,ormContextField:y,paymentsBuild:U,paymentsContextField:A,queuesBuild:B,queuesContextField:j,topicsBuild:R,topicsContextField:W,vectorsBuild:d,vectorsContextField:w,workflowsBuild:E,workflowsContextField:K})=>{const C=t.length>0,L=y===""?"{ db }":"{ db, orm: bindOrm(facade) }",H=y===""?"":`
238
238
  orm: databaseContext.orm,`,V=y===""?"":`
239
239
  orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,P=C?`
240
240
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
@@ -269,8 +269,38 @@ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(v=>` ctx.${v} = ${v};`
269
269
  ...(userId === undefined ? {} : { userId }),
270
270
  };
271
271
  })();
272
- const { identity, ip, userId } = caller;
273
- ${d}${u}${n}${I}${B}${R}${e}
272
+ // The ONLY way to the caller: there are deliberately no \`identity\` /
273
+ // \`userId\` / \`ip\` locals. Each reader marks this function path as
274
+ // reading its caller, which is what keeps a live query that reads it from
275
+ // sharing one run across subscribers (see \`noteIdentityRead\`). A consumer
276
+ // that copies a value at build time marks every ctx of the app; one that
277
+ // reads it lazily marks only the handlers that reach it.
278
+ //
279
+ // Only a registered path is marked: only one can ever be shared, and a
280
+ // client-chosen name (a shape, a relation fan-out) must not grow the set.
281
+ const identityPath = Object.hasOwn(LUNORA_FUNCTIONS, options.functionPath ?? "") ? options.functionPath : undefined;
282
+ const noteCallerRead = (): void => {
283
+ if (identityPath !== undefined) {
284
+ this.noteIdentityRead(identityPath);
285
+ }
286
+ };
287
+ const readIdentity = (): Record<string, unknown> | undefined => {
288
+ noteCallerRead();
289
+
290
+ return caller.identity;
291
+ };
292
+ const readUserId = (): string | undefined => {
293
+ noteCallerRead();
294
+
295
+ return caller.userId;
296
+ };
297
+ const readIp = (): string | undefined => {
298
+ noteCallerRead();
299
+ options.scope?.markIpRead();
300
+
301
+ return caller.ip;
302
+ };
303
+ ${d}${u}${n}${E}${B}${R}${e}
274
304
  // Which dispatch this ctx belongs to. Drives the two deferral facades
275
305
  // below and the \`ctx.run*\` caller guard; a ctx built for an
276
306
  // admin/lifecycle path has no registered function, and so no kind. An
@@ -412,16 +442,32 @@ ${c}
412
442
  // A reactor run is driven by the writer's inline refresh, not replayed by the writer, so it must not
413
443
  // inherit the writer's key: every run would restart the same id and random sequence.
414
444
  const stableKey = options.replayKey !== false && options.identity === undefined && this.idempotencyNamespace() !== undefined ? this.getCurrentMutationId() : undefined;
415
- // Both factories ignore the scope without a replay key, and most dispatches have none.
416
- const stableScope = stableKey === undefined ? "" : JSON.stringify([this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? "", userId ?? ""]);
445
+ // The scope reads the caller, so a factory is only built (and the read only made) on its first draw: a
446
+ // query that carries a replay key but never draws must not count as reading its caller. Both factories
447
+ // ignore the scope without a replay key, and most dispatches have none.
448
+ // The request-scoped parts are captured now: instance state may belong to another request by the first draw.
449
+ const scopeHead = stableKey === undefined ? [] : [this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? ""];
450
+ let scopeText: string | undefined;
451
+ const stableScope = (): string => (scopeText ??= JSON.stringify([...scopeHead, readUserId() ?? ""]));
452
+ const scoped = <T>(create: (scope: string) => () => T): (() => T) => {
453
+ if (stableKey === undefined) {
454
+ return create("");
455
+ }
456
+
457
+ let made: (() => T) | undefined;
458
+
459
+ return () => (made ??= create(stableScope()))();
460
+ };
417
461
  // One sequence for every mutation this run composes: their ids share one counter (the copied \`newId\`), so their draws must too.
418
462
  // Created on the first composed mutation that gets a ctx of its own; most dispatches compose none.
419
463
  let composedRandom: (() => number) | undefined;
420
464
 
421
465
  const ctx: Record<string, unknown> = {
422
466
  auth: {
423
- getIdentity: async () => identity ?? null,
424
- userId: userId ?? null,
467
+ getIdentity: async () => readIdentity() ?? null,
468
+ get userId() {
469
+ return readUserId() ?? null;
470
+ },
425
471
  },
426
472
  db,
427
473
  // \`ctx.newId()\`: a replay of the same top-level mutation gets the same ids. A nested or
@@ -429,9 +475,11 @@ ${c}
429
475
  // A replay key only means something inside the caller's dedup namespace; without one the call is not
430
476
  // deduplicated, so its ids stay random.
431
477
  // \`ctx.random()\` shares the replay key and scope, so a replay reproduces both sequences.
432
- newId: createStableIdFactory(stableKey, stableScope),
433
- // Only a mutation is a replay the key reproduces; a query or action carrying the header draws Math.random.
434
- random: createStableRandomFactory(contextKind === "mutation" ? stableKey : undefined, stableScope),
478
+ // A query is never replayed, so its ids skip \`scoped\` (whose first draw reads the caller) and stay random.
479
+ newId: contextKind === "query" ? createStableIdFactory(undefined, "") : scoped((scope) => createStableIdFactory(stableKey, scope)),
480
+ // Only a mutation is a replay the key reproduces; a query or action carrying the header draws Math.random,
481
+ // and never goes through \`scoped\`, whose first draw reads the caller.
482
+ random: contextKind === "mutation" ? scoped((scope) => createStableRandomFactory(stableKey, scope)) : createStableRandomFactory(undefined, ""),
435
483
  shardKey: this.currentShardKey(),
436
484
  // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
437
485
  // \`traceparent\` propagation, so time spent in a downstream service
@@ -448,9 +496,7 @@ ${c}
448
496
  // Reading it here marks the dispatch's scope; \`runCachedQuery\`
449
497
  // folds the address into the key for this function from then on.
450
498
  get ip() {
451
- options.scope?.markIpRead();
452
-
453
- return ip;
499
+ return readIp();
454
500
  },
455
501
  log,
456
502
  metrics,
@@ -495,7 +541,7 @@ ${f?` const captureScope = (): (() => void) => {
495
541
  const mutationDatabase = makeDatabaseContext(mutationScheduler);
496
542
  // The composed mutation's ids come from the action's replay key and counter, so its draws do too; a
497
543
  // fresh factory per call would repeat the same draws across sibling mutations.
498
- const mutationRandom = (composedRandom ??= createStableRandomFactory(stableKey, stableScope));
544
+ const mutationRandom = (composedRandom ??= scoped((scope) => createStableRandomFactory(stableKey, scope)));
499
545
 
500
546
  // Copied from an action's ctx, which carries the real \`fetch\`; a mutation
501
547
  // refuses network I/O wherever it runs, so its \`fetch\` is overridden here.
@@ -573,7 +619,7 @@ ${t.map(v=>` delete descriptors.${v};
573
619
  fetch: field(refuseFetch),
574
620
  origin: field(undefined),
575
621
  // A composed query is not a mutation replay, so it must not advance the mutation's random sequence.
576
- random: field(createStableRandomFactory(undefined, stableScope)),
622
+ random: field(scoped((scope) => createStableRandomFactory(undefined, scope))),
577
623
  scheduler: field(schedulerBase),
578
624
  storage: field(makeStorage()),
579
625
  }) as Record<string, unknown>;
@@ -877,7 +923,7 @@ __COMMITTED_CATCH__ } finally {
877
923
  // \`ctx.scheduler\` call that reached the buffer in the first place.
878
924
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
879
925
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
880
- }`,$r=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
926
+ }`,$r=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ identityTracked?: boolean; ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
881
927
  const registered = LUNORA_FUNCTIONS[functionPath];
882
928
 
883
929
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -897,7 +943,10 @@ __PREPARE_FUNCTION__ this.ensureServable();
897
943
  // a deferred re-run interleaves with unrelated dispatches.
898
944
  const ranges = footprint.ranges();
899
945
 
900
- return { ...(ranges === undefined ? {} : { ranges }), result, tables: footprint.tables };
946
+ // \`identityTracked\`: this ctx reports every read of its caller through
947
+ // \`noteIdentityRead\`, so the base may share the run across subscribers
948
+ // of a path observed never reading it.
949
+ return { identityTracked: true, ...(ranges === undefined ? {} : { ranges }), result, tables: footprint.tables };
901
950
  }
902
951
 
903
952
  protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
@@ -1025,7 +1074,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as
1025
1074
  protected override isCustomMutator(functionPath: string): boolean {
1026
1075
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1027
1076
  }
1028
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},Jr=(r,t)=>r?`
1077
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},zr=(r,t)=>r?`
1029
1078
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1030
1079
  const env = this.env as Record<string, unknown>;
1031
1080
  // A shape read performs no writes, so the widened request only needs
@@ -1091,7 +1140,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as
1091
1140
 
1092
1141
  return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
1093
1142
  }
1094
- `:"",zr=r=>({externalSourceOverride:r?`
1143
+ `:"",Jr=r=>({externalSourceOverride:r?`
1095
1144
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1096
1145
  const env = (this.env ?? {}) as Record<string, unknown>;
1097
1146
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1288,14 +1337,14 @@ ${a} const vectors = createContextVectors(lunora${h});
1288
1337
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1289
1338
  });
1290
1339
  }
1291
- `:"",vectorsBuild:m,vectorsStub:n}},pn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:a,flagKeys:i=[],hasFlags:u=!1,hasNotify:h=!1,hasRooms:m=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:f=!1,lazyFunctions:c=!1,hasVectors:y=!0,liveStreamDeclarations:U=[],liveStreams:A=!1,maskMetadata:B,mutators:j=[],queues:R=[],rlsMetadata:W,schema:d,schemaSnapshot:w,shapes:I=[],storageRules:K,studioFeatures:C,services:L=[],topics:H=[],useUmbrella:V=!1,workflowEvents:P=[],workflows:O=[]})=>{const l=Dr(V),v=j.length>0,D=I.length>0,T=I.some(s=>Sr(s.args).length>0),G=S||T,ge=w===void 0?"":Xt(w),be=w===void 0?"":`
1340
+ `:"",vectorsBuild:m,vectorsStub:n}},pn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:a,flagKeys:i=[],hasFlags:u=!1,hasNotify:h=!1,hasRooms:m=!1,hasSecretValues:x=!1,hasSensitiveArgs:S=!1,hasSockets:f=!1,lazyFunctions:c=!1,hasVectors:y=!0,liveStreamDeclarations:U=[],liveStreams:A=!1,maskMetadata:B,mutators:j=[],queues:R=[],rlsMetadata:W,schema:d,schemaSnapshot:w,shapes:E=[],storageRules:K,studioFeatures:C,services:L=[],topics:H=[],useUmbrella:V=!1,workflowEvents:P=[],workflows:O=[]})=>{const l=Dr(V),v=j.length>0,D=E.length>0,T=E.some(s=>Sr(s.args).length>0),G=S||T,ge=w===void 0?"":Xt(w),be=w===void 0?"":`
1292
1341
  /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1293
1342
  const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Zt(w))}, json: ${JSON.stringify(ge)} };
1294
- `,ye=w===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=nr(o),N=ar(u,l.flags),Q=sr(i,u,l.flags),J=vr(h),z=or(a),{build:we,contextField:ve,importLines:ke,specs:Se}=ir(Tr(R)),{build:Re,contextField:xe,importLines:Ae,specs:Oe}=dr(H,R),Y=cr(L,l.server),{build:De,contextField:Te,importLines:_e,specs:Ee}=lr(n,d.jurisdiction),{build:Ie,contextField:Ce,importLines:Le,specs:Pe}=ur(O),{build:Ne,contextField:$e,importLines:Me,specs:qe}=hr(e,x&&e.length>0),{build:Fe,configField:Ue,contextField:Be,imports:je,stub:We}=pr(o.has("payments")),Ke=r,{advisoryRules:He,advisoryRows:Ve}=Er(Ke),Ge=t,ae=W??{policies:[],roles:[]},Qe=B??{columns:[]},Je=K??{rules:[]},ze=C??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ye,override:Xe}=mr(O,P),{constant:Ze,override:et}=fr(O,P),{constant:tt,override:rt}=gr(R),g=y&&d.vectorIndexes.length>0,X=new Set(d.tables.filter(s=>_r(s)).map(s=>s.name)),se=g&&d.vectorIndexes.some(s=>X.has(s.table)),_=d.tables.some(s=>s.shardMode==="global"),Z=br(X),ee=d.tables.some(s=>er(s)),oe=d.tables.some(s=>tr(s)),$=d.tables.some(s=>s.externalSource!==void 0),ie=d.tables.some(s=>s.memory===!0),te=d.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(oe&&ee)throw new pe("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const re=d.tables.length>0,nt=Fr(d),at=Br(d),st=Gr(d),ot=Ur(d),de=jr(d),ne=yr(g,O.length>0,R.length>0,u,te);D&&ne.push("WhereInput"),T&&ne.push("SensitiveScope");const ce=wr(_),{customMutatorOverride:it,shapeGuardImport:dt,shapeReadPolicyAssertion:ct,shapeReadPolicyImport:lt,shapeResolveOverride:ut}=Qr({hasMutators:v,hasSensitiveShapes:T,hasShapes:D,rlsData:ae}),E=A?U:[];for(const s of E)if(Rr(s.exportName,"live stream export name"),!xr.test(s.filePath))throw new pe("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ht=c?[]:E.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),pt=` protected override liveStreams() {
1295
- return { ${E.map(s=>`${Ar(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1343
+ `,ye=w===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=nr(o),N=ar(u,l.flags),Q=sr(i,u,l.flags),z=vr(h),J=or(a),{build:we,contextField:ve,importLines:ke,specs:Se}=ir(Tr(R)),{build:Re,contextField:xe,importLines:Ae,specs:Oe}=dr(H,R),Y=cr(L,l.server),{build:De,contextField:Te,importLines:_e,specs:Ie}=lr(n,d.jurisdiction),{build:Ee,contextField:Ce,importLines:Le,specs:Pe}=ur(O),{build:Ne,contextField:$e,importLines:Me,specs:qe}=hr(e,x&&e.length>0),{build:Fe,configField:Ue,contextField:Be,imports:je,stub:We}=pr(o.has("payments")),Ke=r,{advisoryRules:He,advisoryRows:Ve}=Ir(Ke),Ge=t,ae=W??{policies:[],roles:[]},Qe=B??{columns:[]},ze=K??{rules:[]},Je=C??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ye,override:Xe}=mr(O,P),{constant:Ze,override:et}=fr(O,P),{constant:tt,override:rt}=gr(R),g=y&&d.vectorIndexes.length>0,X=new Set(d.tables.filter(s=>_r(s)).map(s=>s.name)),se=g&&d.vectorIndexes.some(s=>X.has(s.table)),_=d.tables.some(s=>s.shardMode==="global"),Z=br(X),ee=d.tables.some(s=>er(s)),oe=d.tables.some(s=>tr(s)),$=d.tables.some(s=>s.externalSource!==void 0),ie=d.tables.some(s=>s.memory===!0),te=d.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(oe&&ee)throw new pe("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const re=d.tables.length>0,nt=Fr(d),at=Br(d),st=Gr(d),ot=Ur(d),de=jr(d),ne=yr(g,O.length>0,R.length>0,u,te);D&&ne.push("WhereInput"),T&&ne.push("SensitiveScope");const ce=wr(_),{customMutatorOverride:it,shapeGuardImport:dt,shapeReadPolicyAssertion:ct,shapeReadPolicyImport:lt,shapeResolveOverride:ut}=Qr({hasMutators:v,hasSensitiveShapes:T,hasShapes:D,rlsData:ae}),I=A?U:[];for(const s of I)if(Rr(s.exportName,"live stream export name"),!xr.test(s.filePath))throw new pe("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ht=c?[]:I.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),pt=` protected override liveStreams() {
1344
+ return { ${I.map(s=>`${Ar(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1296
1345
  }
1297
1346
  `,mt=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1298
- ${E.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1347
+ ${I.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1299
1348
  `)}
1300
1349
  ]);
1301
1350
 
@@ -1316,13 +1365,20 @@ ${E.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1316
1365
  protected override liveStreams() {
1317
1366
  return Object.fromEntries(this.loadedLiveStreams);
1318
1367
  }
1319
- `;let le="";E.length>0&&(le=c?mt:pt);const M=[`import type { ${ne.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${te?"backfillSearchIndexes, ":""}${g?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ie?"clearMemoryTables, ":""}${dt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${$?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ce.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...$?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],D?`import { asBucketStorage, ${lt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];re&&M.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),g&&M.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),M.push(...k.importLines,...N.importLines,...J.importLines,...z.importLines,..._e,...Le,...ke,...Ae,...Y.importLines,...Me,...je,...G?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ht,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...v?["LUNORA_MUTATOR_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...f?["LUNORA_SOCKETS"]:[],...D?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ft=g?`
1368
+ `;let le="";I.length>0&&(le=c?mt:pt);const M=[`import type { ${ne.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${te?"backfillSearchIndexes, ":""}${g?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ie?"clearMemoryTables, ":""}${dt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${$?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ce.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...$?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],D?`import { asBucketStorage, ${lt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];re&&M.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),g&&M.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),M.push(...k.importLines,...N.importLines,...z.importLines,...J.importLines,..._e,...Le,...ke,...Ae,...Y.importLines,...Me,...je,...G?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ht,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...v?["LUNORA_MUTATOR_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...f?["LUNORA_SOCKETS"]:[],...D?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ft=g?`
1320
1369
  vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",gt=oe?`
1321
- d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",bt=ee?`
1322
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",yt=$?`
1370
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",bt=ee?`
1371
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",yt=$?`
1323
1372
  sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",wt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",vt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",kt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",St=_?q("globalDbStub: DatabaseWriterLike",wt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:Rt,vectorsBuild:xt,vectorsStub:At}=Yr(g,se?d.vectorIndexes.filter(s=>X.has(s.table)).map(s=>s.name):[]),Ot=`{
1324
1373
  ...this.ctxDbTuning(),
1325
- auth: { identity: identity ?? null, userId: userId ?? null },
1374
+ auth: {
1375
+ get identity() {
1376
+ return readIdentity() ?? null;
1377
+ },
1378
+ get userId() {
1379
+ return readUserId() ?? null;
1380
+ },
1381
+ },
1326
1382
  broadcast: (delta) => {
1327
1383
  this.recordChangedTable(delta.table, delta.indexKeys);
1328
1384
  },
@@ -1380,19 +1436,23 @@ ${E.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1380
1436
  const globalRequest = {
1381
1437
  ...this.globalCdcOptions(config.cdc ?? false),
1382
1438
  ...(bookmark === undefined ? {} : { bookmark }),
1383
- ...(identity === undefined ? {} : { identity }),
1439
+ get identity(): Record<string, unknown> | undefined {
1440
+ return readIdentity();
1441
+ },
1384
1442
  onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
1385
- ...(userId === undefined ? {} : { userId }),
1443
+ get userId(): string | undefined {
1444
+ return readUserId();
1445
+ },
1386
1446
  };
1387
1447
  const globalDb: DatabaseWriterLike = ${ue}?.(env, globalRequest) ?? globalDbStub;
1388
- `:"",Et=Jr(D&&_,ue),It=m?` protected override roomHandlerPath(topic: string): string | undefined {
1448
+ `:"",It=zr(D&&_,ue),Et=m?` protected override roomHandlerPath(topic: string): string | undefined {
1389
1449
  // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1390
1450
  return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1391
1451
  }
1392
1452
  `:"",Ct=f?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1393
1453
  return LUNORA_SOCKETS[path];
1394
1454
  }
1395
- `:"",{externalSourceOverride:Lt,sourceBootstrap:Pt,sourceClientCacheConst:Nt}=zr($),$t=`
1455
+ `:"",{externalSourceOverride:Lt,sourceBootstrap:Pt,sourceClientCacheConst:Nt}=Jr($),$t=`
1396
1456
  private shardInitDeferred = false;
1397
1457
  private deferredShardInit?: Promise<void>;
1398
1458
 
@@ -1520,16 +1580,16 @@ ${Pt}${Mt} }
1520
1580
  const facade = db as unknown as Record<string, FacadeEntry>;
1521
1581
  ${d.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`).join(`
1522
1582
  `)}
1523
- `:"",Vt=`${k.everyBuild}${N.build}${z.build}
1583
+ `:"",Vt=`${k.everyBuild}${N.build}${J.build}
1524
1584
  const secrets = createSecrets(env);
1525
- `,Gt=`${k.everyFields}${N.contextField}${J.contextField}${z.contextField}
1526
- secrets,`,Qt=J.build,Jt=A?`
1585
+ `,Gt=`${k.everyFields}${N.contextField}${z.contextField}${J.contextField}
1586
+ secrets,`,Qt=z.build,zt=A?`
1527
1587
  const live = {
1528
1588
  publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
1529
1589
  await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1530
1590
  },
1531
1591
  };
1532
- `:"",zt=[...k.actionFields,...L.length>0?["services"]:[],...A?["live"]:[]],Yt=`${k.actionBuild}${Y.build}${Jt}`;return`${Or}${M.join(`
1592
+ `:"",Jt=[...k.actionFields,...L.length>0?["services"]:[],...A?["live"]:[]],Yt=`${k.actionBuild}${Y.build}${zt}`;return`${Or}${M.join(`
1533
1593
  `)}
1534
1594
 
1535
1595
  type FunctionKind = "action" | "mutation" | "query";
@@ -1588,14 +1648,14 @@ ${ct}
1588
1648
  const LUNORA_MASK_METADATA = ${p(Qe,"MaskPoliciesResult")};
1589
1649
 
1590
1650
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1591
- const LUNORA_STORAGE_RULES = ${p(Je,"StorageRulesResult")};
1651
+ const LUNORA_STORAGE_RULES = ${p(ze,"StorageRulesResult")};
1592
1652
 
1593
1653
  /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1594
- const LUNORA_STUDIO_FEATURES = ${p(ze,"StudioFeaturesResult")};
1654
+ const LUNORA_STUDIO_FEATURES = ${p(Je,"StudioFeaturesResult")};
1595
1655
 
1596
1656
  /** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
1597
1657
  const BLOCKED_MIGRATION_RETRY_MS = 5000;
1598
- ${be}${Z.constant}${Q.constant}${Ye}${Ze}${tt}${Ee}${Pe}${Se}${Oe}${Y.specs}${qe}
1658
+ ${be}${Z.constant}${Q.constant}${Ye}${Ze}${tt}${Ie}${Pe}${Se}${Oe}${Y.specs}${qe}
1599
1659
  export interface ShardDOConfig {
1600
1660
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1601
1661
  cdc?: boolean;
@@ -1639,11 +1699,11 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
1639
1699
  private migrationRetryAt = 0;${Ft}${Ut}${Kt}
1640
1700
  ${ce.override}
1641
1701
  ${Wt}
1642
- ${it}${ut}${Et}${Lt}
1702
+ ${it}${ut}${It}${Lt}
1643
1703
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1644
1704
  return LUNORA_LIFECYCLE_HOOKS[event];
1645
1705
  }
1646
- ${It}${Ct}${le}${Z.override}${$t}
1706
+ ${Et}${Ct}${le}${Z.override}${$t}
1647
1707
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1648
1708
  // socket-terminated half of the same reactivity — and differs only in who
1649
1709
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1804,6 +1864,6 @@ ${te?`
1804
1864
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1805
1865
  }
1806
1866
  `:""}${Rt}
1807
- ${Lr({hasSensitiveArgs:G,lazyFunctions:c,actionOnlyFields:zt,agentsBuild:Ne,agentsContextField:$e,containersBuild:De,containersContextField:Te,databaseOptions:Ot,everyContextBuild:Vt,everyContextField:Gt,facadeBlock:Ht,globalDatabaseLine:_t,notifyBuild:Qt,ormContextField:Tt,paymentsBuild:Fe,paymentsContextField:Be,queuesBuild:we,queuesContextField:ve,topicsBuild:Re,topicsContextField:xe,vectorsBuild:xt,vectorsContextField:Dt,workflowsBuild:Ie,workflowsContextField:Ce,actionOnlyBuild:Yt})}
1867
+ ${Lr({hasSensitiveArgs:G,lazyFunctions:c,actionOnlyFields:Jt,agentsBuild:Ne,agentsContextField:$e,containersBuild:De,containersContextField:Te,databaseOptions:Ot,everyContextBuild:Vt,everyContextField:Gt,facadeBlock:Ht,globalDatabaseLine:_t,notifyBuild:Qt,ormContextField:Tt,paymentsBuild:Fe,paymentsContextField:Be,queuesBuild:we,queuesContextField:ve,topicsBuild:Re,topicsContextField:xe,vectorsBuild:xt,vectorsContextField:Dt,workflowsBuild:Ee,workflowsContextField:Ce,actionOnlyBuild:Yt})}
1808
1868
  };
1809
1869
  `};export{Ur as b,pn as e};
@@ -25,7 +25,7 @@ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(r=>JSON.string
25
25
  `},M=(e,r)=>e?{build:`
26
26
  const flags: import("${r}").LunoraFlags = createFlags(flagsConfig, env, {
27
27
  provider: () => config.flags?.(env),
28
- targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
28
+ targetingKey: () => flagsConfig.identify?.({ identity: readIdentity() ?? null, userId: readUserId() ?? null }),
29
29
  });
30
30
  `,configField:`
31
31
  flags?: (env: Record<string, unknown>) => import("${r}").Provider;`,contextField:`
@@ -117,8 +117,8 @@ const LUNORA_FLAG_KEYS = ${b(e,'ReadonlyArray<{ key: string; type: "boolean" | "
117
117
  });
118
118
  `,configField:`
119
119
  ai?: (env: Record<string, unknown>) => AiBindingLike;`,importLines:['import type { AiBindingLike, LunoraAi } from "@lunora/ai/create";','import { createAi } from "@lunora/ai/create";'],stub:""}),L=()=>({build:`
120
- const access = accessFacade(identity, userId);
121
- `,configField:"",importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}),A=()=>({build:`
120
+ const access = lazyAccessFacade(readIdentity, readUserId);
121
+ `,configField:"",importLines:['import { lazyAccessFacade } from "@lunora/cloudflare-access/context";'],stub:""}),A=()=>({build:`
122
122
  const r2sqlEnv = env as Record<string, unknown>;
123
123
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
124
124
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -335,7 +335,7 @@ ${r.map(t=>` [${JSON.stringify(t.type)}, () => import("../${t.filePath}.js").
335
335
 
336
336
  if (payments === undefined) {
337
337
  payments = config.payment
338
- ? paymentsFromContext({ auth: { userId: userId ?? null }, db: this.db as unknown as LunoraPaymentDbLike }, config.payment(env))
338
+ ? paymentsFromContext({ auth: { userId: readUserId() ?? null }, db: this.db as unknown as LunoraPaymentDbLike }, config.payment(env))
339
339
  : paymentStub;
340
340
  paymentsByContext.set(this, payments);
341
341
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.379",
3
+ "version": "1.0.0-alpha.380",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",