@lunora/codegen 1.0.0-alpha.393 → 1.0.0-alpha.395

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -4456,6 +4456,12 @@ declare const emitAgents: (agents: ReadonlyArray<AgentIR>, options?: {
4456
4456
  declare const GENERATED_HEADER = "// GENERATED by @lunora/codegen — do not edit.\n// Run `lunora codegen` to regenerate.\n\n";
4457
4457
  /** Which capability methods the generated `defineApp` builder exposes — one flag per package-backed feature the app actually uses. */
4458
4458
  interface EmitAppOptions {
4459
+ /**
4460
+ * Every agent's generated workflow class name → wire `options.agentWorkflows`, so a
4461
+ * scheduled agent job takes its run shard from the scheduler record instead of its
4462
+ * args. Empty/absent ⇒ no wiring, byte-identical output for agent-free projects.
4463
+ */
4464
+ agentWorkflows?: ReadonlyArray<string>;
4459
4465
  /**
4460
4466
  * The package-backed capabilities the app uses (post platform gate). Every
4461
4467
  * used row of the `CAPABILITIES` table with an `appMethod` gets its fluent
package/dist/index.d.ts CHANGED
@@ -4456,6 +4456,12 @@ declare const emitAgents: (agents: ReadonlyArray<AgentIR>, options?: {
4456
4456
  declare const GENERATED_HEADER = "// GENERATED by @lunora/codegen — do not edit.\n// Run `lunora codegen` to regenerate.\n\n";
4457
4457
  /** Which capability methods the generated `defineApp` builder exposes — one flag per package-backed feature the app actually uses. */
4458
4458
  interface EmitAppOptions {
4459
+ /**
4460
+ * Every agent's generated workflow class name → wire `options.agentWorkflows`, so a
4461
+ * scheduled agent job takes its run shard from the scheduler record instead of its
4462
+ * args. Empty/absent ⇒ no wiring, byte-identical output for agent-free projects.
4463
+ */
4464
+ agentWorkflows?: ReadonlyArray<string>;
4459
4465
  /**
4460
4466
  * The package-backed capabilities the app uses (post platform gate). Every
4461
4467
  * used row of the `CAPABILITIES` table with an `appMethod` gets its fluent
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-DTLoSaNn.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-BuNEmlCO.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-BxpEvZgW.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-DrszPMtU.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-D-ZsZKvv.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as _}from"./packem_shared/CONTAINERS_FILENAME-CvPP3wR-.mjs";import{default as P}from"./packem_shared/discoverCrons-BT_qyOt8.mjs";import{capabilitiesUsedBy as y,createTargetScope as b,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-B8KULfAq.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-Ce1G6kZd.mjs";import{d as z}from"./packem_shared/index-DzO8JT7M.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-DOkHmHzy.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-BGhSZp00.mjs";import{default as J}from"./packem_shared/discoverInserts-d_zAWqc4.mjs";import{d as X}from"./packem_shared/index-VKPwR6Cj.mjs";import{default as $}from"./packem_shared/discoverMigrations-Dq-7Od3H.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-JBFlT9aD.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-CWLdAwUM.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-DLGxunzB.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-Bvh__ZjJ.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-2K8DSvbt.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-CexxhDRt.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-CDbsnndn.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-CugyqoLu.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CSt29RbS.mjs";import{default as he}from"./packem_shared/discoverSchema-DTgg8rAu.mjs";import{readServiceBindings as Ie,resolveServiceBindings as Le}from"./packem_shared/readServiceBindings-rDIqDBSW.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-DCqsIdQQ.mjs";import{default as ye}from"./packem_shared/discoverStorageRulesMetadata-DTXC-pY3.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{emitApp as je}from"./packem_shared/emitApp-Bz0oVnTy.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-KKQFkA_W.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CLZ5Em9J.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-C0xI7Xqd.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir,readProjectLazyFunctions as sr}from"./packem_shared/loadProjectConfig-Dbux4jI3.mjs";import{PROJECT_CONFIG_FILENAMES as mr,findCodegenConfigFile as dr,findProjectConfigFile as pr,projectConfigCandidatePaths as nr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as lr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bx2x4Eva.mjs";import{SchemaSnapshotParseError as Er,buildSchemaSnapshot as ur,evaluateSchemaDrift as Ar,indexReferencesOf as vr,parseSchemaSnapshot as gr}from"./packem_shared/SchemaSnapshotParseError-DnAuFdpl.mjs";import{default as Nr}from"./packem_shared/fingerprintSchemaSources-Pmxw808S.mjs";import{schemaFromIr as Rr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as hr,validatorIrToJsonSchema as Fr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Lr,SDK_TARGETS as _r,generateSdk as Mr}from"./sdk/index.mjs";import{redact as Dr,secretKindOf as yr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Ur}from"./packem_shared/emitDrizzleSchema-Dszoyymv.mjs";import{e as Hr}from"./packem_shared/server-Box8pDwi.mjs";import{e as Br}from"./packem_shared/shard-CVJYK961.mjs";import{G as Wr}from"./packem_shared/shared-DhqnD5R3.mjs";import{MESSAGE_SOLUTIONS as Kr,findSolutionByMessage as Vr}from"@lunora/errors";import{createCodegenProject as qr,findTsconfig as wr,refreshCodegenProject as Jr,tsconfigFingerprint as Yr}from"./packem_shared/createCodegenProject-khHqIXPY.mjs";import{t as Zr,u as $r,v as eo}from"./packem_shared/shard-runtime-BfamDqXW.mjs";import{emitApi as oo,emitCollections as to,emitInternalApi as ao}from"./packem_shared/emitApi-Cdc8MeNK.mjs";import{emitCrons as so,emitScheduler as fo,emitVectors as mo,emitWranglerCronTriggers as po}from"./packem_shared/emitCrons-BQjDleCe.mjs";import{emitDataModel as co}from"./packem_shared/emitDataModel-MjAOi3KM.mjs";import{emitFunctions as xo}from"./packem_shared/emitFunctions-BIMKBLQ8.mjs";import{isTypedSchema as Eo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Wr as GENERATED_HEADER,hr as LUNORA_ERROR_CODES,Kr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,mr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,lr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Lr as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Er as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,Je as buildOpenRpcDocument,ur as buildSchemaSnapshot,y as capabilitiesUsedBy,qr as createCodegenProject,b as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,F as discoverAuthApiCalls,_ as discoverContainers,P as discoverCrons,k as discoverFlags,z as discoverFunctions,V 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,ye as discoverStorageRulesMetadata,Ge as discoverWorkflows,Zr as emitAgents,oo as emitApi,je as emitApp,to as emitCollections,$r as emitContainers,so as emitCrons,co as emitDataModel,Ur as emitDrizzleSchema,xo as emitFunctions,ao as emitInternalApi,Ve as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,fo as emitScheduler,Hr as emitServer,Br as emitShard,mo as emitVectors,eo as emitWorkflows,po as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Ar as evaluateSchemaDrift,dr as findCodegenConfigFile,Vr as findLunoraSolution,pr as findProjectConfigFile,wr as findTsconfig,Nr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Mr as generateSdk,vr as indexReferencesOf,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,Eo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,gr as parseSchemaSnapshot,er as platformMatrixIds,nr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,sr as readProjectLazyFunctions,rr as readProjectTarget,Ie as readServiceBindings,Dr as redact,Jr as refreshCodegenProject,or as resolveCodegenTarget,Le as resolveServiceBindings,xr as runCodegen,Rr as schemaFromIr,yr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,Yr as tsconfigFingerprint,Fr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.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-BuNEmlCO.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-BxpEvZgW.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-DrszPMtU.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-D-ZsZKvv.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as _}from"./packem_shared/CONTAINERS_FILENAME-CvPP3wR-.mjs";import{default as P}from"./packem_shared/discoverCrons-BT_qyOt8.mjs";import{capabilitiesUsedBy as y,createTargetScope as b,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-B8KULfAq.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-Ce1G6kZd.mjs";import{d as z}from"./packem_shared/index-DzO8JT7M.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-DOkHmHzy.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-BGhSZp00.mjs";import{default as J}from"./packem_shared/discoverInserts-d_zAWqc4.mjs";import{d as X}from"./packem_shared/index-VKPwR6Cj.mjs";import{default as $}from"./packem_shared/discoverMigrations-Dq-7Od3H.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-JBFlT9aD.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-CWLdAwUM.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-DLGxunzB.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-Bvh__ZjJ.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-2K8DSvbt.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-CexxhDRt.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-CDbsnndn.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-CugyqoLu.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CSt29RbS.mjs";import{default as he}from"./packem_shared/discoverSchema-DTgg8rAu.mjs";import{readServiceBindings as Ie,resolveServiceBindings as Le}from"./packem_shared/readServiceBindings-rDIqDBSW.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-DCqsIdQQ.mjs";import{default as ye}from"./packem_shared/discoverStorageRulesMetadata-DTXC-pY3.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{emitApp as je}from"./packem_shared/emitApp-D-fxbE34.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-KKQFkA_W.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CLZ5Em9J.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-C0xI7Xqd.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir,readProjectLazyFunctions as sr}from"./packem_shared/loadProjectConfig-Dbux4jI3.mjs";import{PROJECT_CONFIG_FILENAMES as mr,findCodegenConfigFile as dr,findProjectConfigFile as pr,projectConfigCandidatePaths as nr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as lr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BRRkfu5-.mjs";import{SchemaSnapshotParseError as Er,buildSchemaSnapshot as ur,evaluateSchemaDrift as Ar,indexReferencesOf as vr,parseSchemaSnapshot as gr}from"./packem_shared/SchemaSnapshotParseError-DnAuFdpl.mjs";import{default as Nr}from"./packem_shared/fingerprintSchemaSources-Pmxw808S.mjs";import{schemaFromIr as Rr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as hr,validatorIrToJsonSchema as Fr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Lr,SDK_TARGETS as _r,generateSdk as Mr}from"./sdk/index.mjs";import{redact as Dr,secretKindOf as yr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Ur}from"./packem_shared/emitDrizzleSchema-Dszoyymv.mjs";import{e as Hr}from"./packem_shared/server-Box8pDwi.mjs";import{e as Br}from"./packem_shared/shard-DXVp_Iht.mjs";import{G as Wr}from"./packem_shared/shared-DhqnD5R3.mjs";import{MESSAGE_SOLUTIONS as Kr,findSolutionByMessage as Vr}from"@lunora/errors";import{createCodegenProject as qr,findTsconfig as wr,refreshCodegenProject as Jr,tsconfigFingerprint as Yr}from"./packem_shared/createCodegenProject-khHqIXPY.mjs";import{t as Zr,u as $r,v as eo}from"./packem_shared/shard-runtime-BHljpfS5.mjs";import{emitApi as oo,emitCollections as to,emitInternalApi as ao}from"./packem_shared/emitApi-Cdc8MeNK.mjs";import{emitCrons as so,emitScheduler as fo,emitVectors as mo,emitWranglerCronTriggers as po}from"./packem_shared/emitCrons-BQjDleCe.mjs";import{emitDataModel as co}from"./packem_shared/emitDataModel-MjAOi3KM.mjs";import{emitFunctions as xo}from"./packem_shared/emitFunctions-BIMKBLQ8.mjs";import{isTypedSchema as Eo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Wr as GENERATED_HEADER,hr as LUNORA_ERROR_CODES,Kr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,mr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,lr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Lr as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Er as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,Je as buildOpenRpcDocument,ur as buildSchemaSnapshot,y as capabilitiesUsedBy,qr as createCodegenProject,b as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,F as discoverAuthApiCalls,_ as discoverContainers,P as discoverCrons,k as discoverFlags,z as discoverFunctions,V 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,ye as discoverStorageRulesMetadata,Ge as discoverWorkflows,Zr as emitAgents,oo as emitApi,je as emitApp,to as emitCollections,$r as emitContainers,so as emitCrons,co as emitDataModel,Ur as emitDrizzleSchema,xo as emitFunctions,ao as emitInternalApi,Ve as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,fo as emitScheduler,Hr as emitServer,Br as emitShard,mo as emitVectors,eo as emitWorkflows,po as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Ar as evaluateSchemaDrift,dr as findCodegenConfigFile,Vr as findLunoraSolution,pr as findProjectConfigFile,wr as findTsconfig,Nr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Mr as generateSdk,vr as indexReferencesOf,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,Eo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,gr as parseSchemaSnapshot,er as platformMatrixIds,nr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,sr as readProjectLazyFunctions,rr as readProjectTarget,Ie as readServiceBindings,Dr as redact,Jr as refreshCodegenProject,or as resolveCodegenTarget,Le as resolveServiceBindings,xr as runCodegen,Rr as schemaFromIr,yr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,Yr as tsconfigFingerprint,Fr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as K,readFileSync as Je,mkdirSync as jt,writeFileSync as Pr,rmSync as we,readdirSync as Dn}from"node:fs";import{dirname as Ht,join as v,relative as Gt}from"node:path";import{performance as St}from"node:perf_hooks";import{runAdvisor as wr}from"@lunora/advisor";import{LunoraError as M}from"@lunora/errors";import{serializeSchemaSnapshot as Ir}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Tr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Yt,ts as Cr,VariableDeclarationKind as Qt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as T,descendantsOfKind as E,bindingKeyName as fe,collectCallRows as k,findObjectProperty as U,collectSecurityCallRows as Or,propertyInitializer as D,listSecurityScanFiles as Ze,objectLiteralFromCallbackBody as Mn,limitNameOf as _n,optionsObjectLiteral as zn,handlerOf as kr,collectNodeRows as re,chainRootOf as et,outermostValueWrapper as O,isWriteTarget as tt,isSameNode as b,unwrapExpression as h,isConstDeclaration as oe,memberAccessOf as Xt,returningFunctionOf as kt,walkChain as Rr,RUN_METHODS as Kn,functionReferenceSegments as Fr,isTestPath as Lr,isFunctionLike as ae,functionKeyOf as $n,withSourceListMemo as Dr}from"./isTestPath-DrszPMtU.mjs";import{j as J,h as G,d as _,b as Jt,c as S,a as st,w as Zt,k as Mr,l as _r,f as zr,m as Kr,g as Rt,i as $r}from"./attribution-7Qs8xFmy.mjs";import{b as $s,r as At,a as Q,e as Br,m as Bn,c as nt,f as es,E as Vn,C as Un,d as Vr,g as Ur,i as Wr}from"./context-root-DHXNIvVA.mjs";import{a as C,i as Wn,c as se,d as qn,e as qr,f as jr,g as jn}from"./classify-procedure-call-D7XTLd8w.mjs";import{a as A,s as Hr}from"./property-name-7cBlgK_O.mjs";import{b as Gr,a as it}from"./module-specifiers-BctA0m_p.mjs";import{r as rt,s as Yr}from"./parse-validator-BisfC8bR.mjs";import Qr from"./discoverAuthApiCalls-D-ZsZKvv.mjs";import{i as $,r as Hn}from"./database-calls-CxJgjC_X.mjs";import{i as Ft,p as Gn,w as Xr,d as Jr}from"./index-DzO8JT7M.mjs";import Zr from"./discoverHyperdriveCalls-BGhSZp00.mjs";import{diagnosticAt as ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ts,a as qe,s as Yn,d as eo}from"./index-VKPwR6Cj.mjs";import{MUTATORS_FILENAME as to,isDefineMutatorCallee as so,mutatorServerImplOf as no,discoverMutators as io}from"./MUTATORS_FILENAME-JBFlT9aD.mjs";import ro from"./discoverNondeterministicCalls-CWLdAwUM.mjs";import{discoverNotifyConfig as oo,discoverNotifyCalls as ao}from"./NOTIFY_FILENAME-DLGxunzB.mjs";import co from"./discoverR2sqlCalls-CexxhDRt.mjs";import lo from"./discoverRlsProcedures-CDbsnndn.mjs";import{s as ss,n as uo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as fo,redact as go,isHeuristicSecretKind as po,isSecretishName as mo}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Qn,readProjectLazyFunctions as ho,readMergeDurableObjects as vo}from"./loadProjectConfig-Dbux4jI3.mjs";import{a as Me,d as Eo,r as xo}from"./modules-CYf6V2w7.mjs";import{WORKFLOWS_FILENAME as So,discoverWorkflows as Ao}from"./WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{r as yo}from"./json-data-Chfs2Cz5.mjs";import{a as bo,I as No,g as Po,G as Xn,d as wo,i as Io}from"./shared-DhqnD5R3.mjs";import{createCodegenProject as To}from"./createCodegenProject-khHqIXPY.mjs";import{findTsconfig as HE,refreshCodegenProject as GE,tsconfigFingerprint as YE}from"./createCodegenProject-khHqIXPY.mjs";import{CAPABILITIES as Co,usedCapabilities as Oo}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Jn,isHyperdriveGlobalTable as Zn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as ko}from"./AGENTS_FILENAME-BxpEvZgW.mjs";import{discoverContainers as Ro}from"./CONTAINERS_FILENAME-CvPP3wR-.mjs";import Fo from"./discoverCrons-BT_qyOt8.mjs";import{contextPropertiesRead as Lo,fileWiresRequestSecretTool as Do,createTargetScope as Mo,discoverFeatureUsage as _o}from"./capabilitiesUsedBy-B8KULfAq.mjs";import ei from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as zo,findProjectConfigFile as Ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as $o}from"./QUEUES_FILENAME-2K8DSvbt.mjs";import{discoverSandboxUsage as Bo}from"./discoverSandboxUsage-CSt29RbS.mjs";import{resolveServiceBindings as Vo}from"./readServiceBindings-rDIqDBSW.mjs";import Uo from"./discoverStorageRulesMetadata-DTXC-pY3.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as Wo,readTargetDiagnostics as qo,vectorizeDimensionDiagnostics as jo,liveStreamsDeliveryAuthorizationDiagnostic as Ho,socketRoutesDeliveryAuthorizationDiagnostic as Go,studioPlatformFor as Yo,platformFeatureAvailable as Qo,gateAdminTokenRevocation as Xo}from"./DEFAULT_TARGET-C0xI7Xqd.mjs";import{i as Jo}from"./schema-BgM8A3XV.mjs";import{b as ti,e as Zo}from"./shard-CVJYK961.mjs";import{e as ea,a as ta}from"./server-Box8pDwi.mjs";import{emitDataModel as sa}from"./emitDataModel-MjAOi3KM.mjs";import{i as na,b as ia,e as ra,d as oa,f as aa,c as ca}from"./unwrap-handler-return-X7HuBhd5.mjs";import la from"./discoverHttpRoutes-DOkHmHzy.mjs";import da from"./discoverInserts-d_zAWqc4.mjs";import{e as si}from"./exported-procedure-chains-D1wkgxKb.mjs";import ua from"./discoverMigrations-Dq-7Od3H.mjs";import Bs from"./discoverQueries-Bvh__ZjJ.mjs";import fa from"./discoverRlsMetadata-CugyqoLu.mjs";import ga from"./discoverSchema-DTgg8rAu.mjs";import{discoverShapes as pa}from"./SHAPES_FILENAME-DCqsIdQQ.mjs";import{i as ma}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as ha,emitApp as va}from"./emitApp-Bz0oVnTy.mjs";import{readJsonSync as Ea}from"@visulima/fs";import{indexReferencesOf as xa,buildSchemaSnapshot as Sa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Aa,emitOpenApiModule as ya}from"./buildOpenApiDocument-KKQFkA_W.mjs";import{buildOpenRpcDocument as ba,emitOpenRpcModule as Na}from"./OPENRPC_VERSION-CLZ5Em9J.mjs";import{w as Pa,u as wa,v as Ia,t as Ta,x as Ca}from"./shard-runtime-BfamDqXW.mjs";import{emitCollections as Oa,emitSeed as ka,emitApi as Ra,emitInternalApi as Fa}from"./emitApi-Cdc8MeNK.mjs";import{emitCrons as La,emitScheduler as Da,emitAdminRevocations as Ma,emitShardRegistry as _a,emitDurableObjects as za,emitVectors as Ka,emitWranglerCronTriggers as $a}from"./emitCrons-BQjDleCe.mjs";import Ba from"./emitDrizzleSchema-Dszoyymv.mjs";import{LAZY_FUNCTION_DIRECTORY as ni,emitFunctions as Va,emitLazyFunctionModules as Ua}from"./emitFunctions-BIMKBLQ8.mjs";const Wa=(e,t=!1)=>{if(e.length===0)return"";const s=wo(t),n=e.map(c=>{if(bo(c.exportName,"live stream export name"),!No.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=>{Po(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 x=u.fields.map(N=>`\${encodeURIComponent(key.${N})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as K,readFileSync as Je,mkdirSync as jt,writeFileSync as Pr,rmSync as we,readdirSync as Dn}from"node:fs";import{dirname as Ht,join as v,relative as Gt}from"node:path";import{performance as St}from"node:perf_hooks";import{runAdvisor as wr}from"@lunora/advisor";import{LunoraError as M}from"@lunora/errors";import{serializeSchemaSnapshot as Ir}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Tr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Yt,ts as Cr,VariableDeclarationKind as Qt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as T,descendantsOfKind as E,bindingKeyName as fe,collectCallRows as k,findObjectProperty as U,collectSecurityCallRows as Or,propertyInitializer as D,listSecurityScanFiles as Ze,objectLiteralFromCallbackBody as Mn,limitNameOf as _n,optionsObjectLiteral as zn,handlerOf as kr,collectNodeRows as re,chainRootOf as et,outermostValueWrapper as O,isWriteTarget as tt,isSameNode as b,unwrapExpression as h,isConstDeclaration as oe,memberAccessOf as Xt,returningFunctionOf as kt,walkChain as Rr,RUN_METHODS as Kn,functionReferenceSegments as Fr,isTestPath as Lr,isFunctionLike as ae,functionKeyOf as $n,withSourceListMemo as Dr}from"./isTestPath-DrszPMtU.mjs";import{j as J,h as G,d as _,b as Jt,c as S,a as st,w as Zt,k as Mr,l as _r,f as zr,m as Kr,g as Rt,i as $r}from"./attribution-7Qs8xFmy.mjs";import{b as $s,r as At,a as Q,e as Br,m as Bn,c as nt,f as es,E as Vn,C as Un,d as Vr,g as Ur,i as Wr}from"./context-root-DHXNIvVA.mjs";import{a as C,i as Wn,c as se,d as qn,e as qr,f as jr,g as jn}from"./classify-procedure-call-D7XTLd8w.mjs";import{a as A,s as Hr}from"./property-name-7cBlgK_O.mjs";import{b as Gr,a as it}from"./module-specifiers-BctA0m_p.mjs";import{r as rt,s as Yr}from"./parse-validator-BisfC8bR.mjs";import Qr from"./discoverAuthApiCalls-D-ZsZKvv.mjs";import{i as $,r as Hn}from"./database-calls-CxJgjC_X.mjs";import{i as Ft,p as Gn,w as Xr,d as Jr}from"./index-DzO8JT7M.mjs";import Zr from"./discoverHyperdriveCalls-BGhSZp00.mjs";import{diagnosticAt as ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ts,a as qe,s as Yn,d as eo}from"./index-VKPwR6Cj.mjs";import{MUTATORS_FILENAME as to,isDefineMutatorCallee as so,mutatorServerImplOf as no,discoverMutators as io}from"./MUTATORS_FILENAME-JBFlT9aD.mjs";import ro from"./discoverNondeterministicCalls-CWLdAwUM.mjs";import{discoverNotifyConfig as oo,discoverNotifyCalls as ao}from"./NOTIFY_FILENAME-DLGxunzB.mjs";import co from"./discoverR2sqlCalls-CexxhDRt.mjs";import lo from"./discoverRlsProcedures-CDbsnndn.mjs";import{s as ss,n as uo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as fo,redact as go,isHeuristicSecretKind as po,isSecretishName as mo}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Qn,readProjectLazyFunctions as ho,readMergeDurableObjects as vo}from"./loadProjectConfig-Dbux4jI3.mjs";import{a as Me,d as Eo,r as xo}from"./modules-CYf6V2w7.mjs";import{WORKFLOWS_FILENAME as So,discoverWorkflows as Ao}from"./WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{r as yo}from"./json-data-Chfs2Cz5.mjs";import{a as bo,I as No,g as Po,G as Xn,d as wo,i as Io}from"./shared-DhqnD5R3.mjs";import{createCodegenProject as To}from"./createCodegenProject-khHqIXPY.mjs";import{findTsconfig as HE,refreshCodegenProject as GE,tsconfigFingerprint as YE}from"./createCodegenProject-khHqIXPY.mjs";import{CAPABILITIES as Co,usedCapabilities as Oo}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Jn,isHyperdriveGlobalTable as Zn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as ko}from"./AGENTS_FILENAME-BxpEvZgW.mjs";import{discoverContainers as Ro}from"./CONTAINERS_FILENAME-CvPP3wR-.mjs";import Fo from"./discoverCrons-BT_qyOt8.mjs";import{contextPropertiesRead as Lo,fileWiresRequestSecretTool as Do,createTargetScope as Mo,discoverFeatureUsage as _o}from"./capabilitiesUsedBy-B8KULfAq.mjs";import ei from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as zo,findProjectConfigFile as Ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as $o}from"./QUEUES_FILENAME-2K8DSvbt.mjs";import{discoverSandboxUsage as Bo}from"./discoverSandboxUsage-CSt29RbS.mjs";import{resolveServiceBindings as Vo}from"./readServiceBindings-rDIqDBSW.mjs";import Uo from"./discoverStorageRulesMetadata-DTXC-pY3.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as Wo,readTargetDiagnostics as qo,vectorizeDimensionDiagnostics as jo,liveStreamsDeliveryAuthorizationDiagnostic as Ho,socketRoutesDeliveryAuthorizationDiagnostic as Go,studioPlatformFor as Yo,platformFeatureAvailable as Qo,gateAdminTokenRevocation as Xo}from"./DEFAULT_TARGET-C0xI7Xqd.mjs";import{i as Jo}from"./schema-BgM8A3XV.mjs";import{b as ti,e as Zo}from"./shard-DXVp_Iht.mjs";import{e as ea,a as ta}from"./server-Box8pDwi.mjs";import{emitDataModel as sa}from"./emitDataModel-MjAOi3KM.mjs";import{i as na,b as ia,e as ra,d as oa,f as aa,c as ca}from"./unwrap-handler-return-X7HuBhd5.mjs";import la from"./discoverHttpRoutes-DOkHmHzy.mjs";import da from"./discoverInserts-d_zAWqc4.mjs";import{e as si}from"./exported-procedure-chains-D1wkgxKb.mjs";import ua from"./discoverMigrations-Dq-7Od3H.mjs";import Bs from"./discoverQueries-Bvh__ZjJ.mjs";import fa from"./discoverRlsMetadata-CugyqoLu.mjs";import ga from"./discoverSchema-DTgg8rAu.mjs";import{discoverShapes as pa}from"./SHAPES_FILENAME-DCqsIdQQ.mjs";import{i as ma}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as ha,emitApp as va}from"./emitApp-D-fxbE34.mjs";import{readJsonSync as Ea}from"@visulima/fs";import{indexReferencesOf as xa,buildSchemaSnapshot as Sa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Aa,emitOpenApiModule as ya}from"./buildOpenApiDocument-KKQFkA_W.mjs";import{buildOpenRpcDocument as ba,emitOpenRpcModule as Na}from"./OPENRPC_VERSION-CLZ5Em9J.mjs";import{w as Pa,u as wa,v as Ia,t as Ta,x as Ca}from"./shard-runtime-BHljpfS5.mjs";import{emitCollections as Oa,emitSeed as ka,emitApi as Ra,emitInternalApi as Fa}from"./emitApi-Cdc8MeNK.mjs";import{emitCrons as La,emitScheduler as Da,emitAdminRevocations as Ma,emitShardRegistry as _a,emitDurableObjects as za,emitVectors as Ka,emitWranglerCronTriggers as $a}from"./emitCrons-BQjDleCe.mjs";import Ba from"./emitDrizzleSchema-Dszoyymv.mjs";import{LAZY_FUNCTION_DIRECTORY as ni,emitFunctions as Va,emitLazyFunctionModules as Ua}from"./emitFunctions-BIMKBLQ8.mjs";const Wa=(e,t=!1)=>{if(e.length===0)return"";const s=wo(t),n=e.map(c=>{if(bo(c.exportName,"live stream export name"),!No.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=>{Po(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 x=u.fields.map(N=>`\${encodeURIComponent(key.${N})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
2
  __lunoraLive: ${m},
3
3
  topic: \`${u.name}:${x}\`,
4
4
  }),`});return` ${c.exportName}: {
@@ -27,5 +27,5 @@ ${i}
27
27
 
28
28
  Install them with your package manager, then re-run codegen.`)},Jp="env.ts",Zp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return it(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},em=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&it(n.getModuleSpecifierValue())}return!1},tm=e=>{if(r.isIdentifier(e))return Zp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&em(t)}return!1},sm=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!tm(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ce(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=st(s,"member");a!==void 0&&t.push({exportName:a})}return t},nm=(e,t)=>{const s=v(t,Jp);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=sm(n);if(i.length!==0){if(i.length>1)throw ce(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},im={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},rm=new Set(["allowedHosts","deniedHosts","interceptHttps"]),om=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},am=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),cm=new Set(["durable"]),lm=new Set(["rollback"]),Bi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},dm="defineApp",Pe="app",Nn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Pe&&s.getInitializer()?.getText()===t)||t===Pe&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Pe),um=e=>{if(e===void 0||!zo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Pe;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Pe;if(r.isVariableDeclaration(t))return Nn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&Nn(e.getSourceFile(),s)},fm="AppBuilder",Vi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},gm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===fm&&s.getDeclarations().some(n=>Vi(n))},pm=e=>e.getText()===dm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Vi(t)),Ui=(e,t,s=new Set)=>{const n=et(t);if(n===void 0||!r.isIdentifier(n))return!1;if(pm(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return um(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Ui(e,a.getInitializer(),s)}}return!1},Wi=(e,t)=>{const s=Xt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Ui(e,s.object)||gm(s.object))},mm=new Map([["defineContainer",{keys:rm,signal:"containerEgressPolicy"}],["defineStep",{keys:lm,signal:"workflowRollback"}],["stream",{keys:cm,signal:"durableStreams"}]]),hm=(e,t)=>{const s=mm.get(Bi(t));if(s!==void 0)return t.getArguments().some(n=>am(om(e,n),s.keys))?s.signal:void 0},vm=(e,t)=>im[Bi(t)]??(Wi(e,t)?"deliveryAuthorization":void 0),Em=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Lo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=hm(o,c)??vm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>jn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Je(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Wi(i,o))}return n},xm=(e,t)=>{const s=Mo();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Do(i,s))return!0}return!1},Sm="createWorker",Am="extend",Pn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,wn=e=>{const t=[],s=Pn(D(e,"backupCron"));s!==void 0&&t.push(s);const n=D(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=Pn(i.getNameNode());o!==void 0&&t.push(o)}return t},ym=e=>{const t=C(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Sm)return r.isObjectLiteralExpression(s)?wn(s):[];if(t!==Am||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Mn(s.getBody());return n===void 0?[]:wn(n)},bm=(e,t)=>{const s=[];for(const{filePath:n}of Ze(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...ym(o))}return[...new Set(s)]},qi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:qi(e.inner)},Nm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=qi(n);return i!==void 0&&t.has(i)}))},Pm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new M("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new M("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},wm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=pd(s,t),a=nm(s,t),c=Ao(s,t),{queues:l,topics:u}=$o(s,t),f=Vo(n),g=ko(s,t);Pm(c,g);const m=Ro(s,t),x=Uo(s,t),N=Fo(s,t,c,g),pe=bm(s,t),P=Em(s,t,Ko(n)),B=Bo(s,t),Y=xm(s,t),w=_o(s,t);w.browser=w.browser||B.usesSandboxBrowser;const W=_e(n,e.target),L=Wo(w,W,{agents:g.length>0,commitOrderedTables:i.tables.some(z=>z.commitOrdered===!0),cronTriggers:N.length>0,crossShardFanout:i.tables.some(z=>Jo(z)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(z=>z.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(z=>z.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(z=>z.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Nm(i),secretValues:Y,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:B.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(z=>z.schedules!==void 0)}),R=L.usage,Z=Oo(R),ee=L.signals.vectorStore!==!1,ne=L.signals.services===!1?[]:f,ie=ei(n),le=ie??new Set,I=le.has("lunorash");Xp(i,ie,{hasVectors:ee,scheduler:R.scheduler||N.length>0,storage:R.storage||x.rules.length>0||Object.keys(ti(i)).length>0,usage:R});const F=K(v(t,"flags.ts")),V=K(v(t,"notify.ts"));return{agents:g,capabilities:Z,containers:m,crons:N,dataModelContent:sa(i),declaredDependencies:ie,dependencies:le,entryCronTriggers:pe,env:a,featureUsage:R,hasFlags:F,hasNotify:V,identity:o,platformGate:{...L,diagnostics:[...qo(n,e.target),...L.diagnostics,...jo(W,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[Ho(W)]:[],...P.socketRoutes&&P.deliveryAuthorization?[Go(W)]:[]]},queues:l,serverContent:ea({agents:g,capabilities:Z,containers:m,env:a,hasVectors:ee,hasFlags:F,hasNotify:V,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:x.rules.map(z=>z.bucket),topics:u,useUmbrella:I,workflows:c}),services:ne,storageRulesMetadata:x,topics:u,usesSandbox:B.usesSandboxBrowser||B.usesSandboxContainer||B.usesSandboxFs,useUmbrella:I,workflows:c}},ji=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Im=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},Tm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Cm=/^[\w$]+:[\w$]+$/u,Om=(e,t)=>{const s=$n(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},In=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},km=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return In(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Qt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?In(s):void 0}}},Rm=(e,t,s)=>({schedule:{argKeys:km(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Fm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return Om(s,n);if((s==="runAfter"||s==="runAt")&&Im(t)){const l=$n(i)??(r.isStringLiteral(i)&&Cm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Rm(s,n,o)}}const a=Tm.get(s),c=a===void 0?void 0:ji(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Lm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Hi=e=>Cr.isOptionalChain(e.compilerNode),Dm=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ae(t)?t.getFirstAncestor(ae)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Lm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Hi(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Hg(s)),Mm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ae);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(ae),i))===!0},_m=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),zm=(e,t)=>{if(Hi(e)||t==="schedule"&&Mm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Dm(s,i)){if(!_m(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Tn=(e,t,s)=>{if(s===void 0)return;const n=zm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Km=(e,t)=>[...k(e,t,(s,n)=>Tn(s,n,Fm(s))),...re(e,t,d.PropertyAccessExpression,(s,n)=>{const i=ji(s,"services");return Tn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],$m=new Set(["boolean","number","object","string"]),Bm=e=>{const t=e.getName();if(!$m.has(t))return;const s=e.getExpression();return Q(s,["flags"])||Q(s,["flags","details"])?t:void 0},Vm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Bm(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Um=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Vm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Wm=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||na(o))return;const a=e.getSourceFile().getFilePath();if(ia(i,e,a)){const c=ra(i,e,a,0,new Set);return c===void 0&&oa(o),c}return o},qm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Hr(t.getNameNode());return s===void 0||s==="namespace"}),jm=(e,t)=>{for(const{filePath:s}of Ze(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||qm(a)))return i}}},Hm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Gm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ce(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Hm}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},Ym="room:",Qm="__lunora_socket__:",Xm=/^[A-Za-z]\w*$/u,Cn=e=>Xm.test(e),Jm=e=>`${e}:`.startsWith(Ym)||`${e}:`.startsWith(Qm),Gi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Yi=e=>Gi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),On=e=>A(e),us=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),ue=(e,t)=>{const s=ce(e,`defineLiveStream ${t}`);return new M("LIVE_STREAM_NOT_LITERAL",s.message)},Qi=(e,t,s)=>{const n=us(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ue(n??e,`needs ${s} so codegen can read its topics`);if(Yi(i))throw ue(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Zm=(e,t)=>{const s=On(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Yi(n))throw ue(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Cn(s)||Jm(s))throw new M("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(us(n,"key")===void 0)return{fields:[],name:s};const a=Qi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>On(l)),c=a.find(l=>!Cn(l));if(c!==void 0)throw new M("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},eh=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Gi(n))throw ue(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=us(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ue(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Qi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:T(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Zm(a,l))}},th=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new M("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},sh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},nh=(e,t)=>E(e,d.CallExpression).filter(s=>jn(s,"defineLiveStream")).map(s=>{const n=sh(s),i=r.isVariableDeclaration(n)?st(n,"binding"):void 0;if(i===void 0)throw new M("LIVE_STREAM_NOT_EXPORTED",ce(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return eh(s,i,t)}),ih=(e,t)=>{const s=y(t).flatMap(n=>nh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return th(s),s},rh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,oh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?rh(e):!0,Xi=(e,t=!1)=>{for(const s of e.getProperties()){if(oh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Xi(n,!0))return!0}return!1},ah=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of si(n))for(const o of ts(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Xi(a)))return!0}}return!1},ch=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=qe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=qe(a);c!==void 0&&s.push({column:c,strategy:Yn(a),table:i})}}return s},lh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of si(i))for(const a of ts(o))for(const c of ch(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},dh=["providerSubscriptionId","state"],uh=["providerEventId","processedAt"],kn=(e,t)=>t.every(s=>s in e.shape),fh=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&kn(t,dh)&&kn(s,uh)},gh=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],ph=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},mh=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},hh="@lunora/privacy",Ji="userId",Rn=new Set(["user","users"]),vh=e=>e.replaceAll("\\","/"),Eh="privacy",xh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),at=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Te=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",fs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Sh=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},ct=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Ah=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Sh(s,"tables"),i=at(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:fs(n).map(a=>Te(a)))t.datasets.set(o,i)},gs=8,ve=(e,t=0)=>{if(t>gs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return ve(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:ve(i,t+1)},yh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:ve(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[],o=new Set(i.map(a=>Te(a)));for(const a of gh)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?at(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Te(a)==="user"&&t.userTables.add(c))}},Fn=(e,t,s)=>{t.datasets.set(at(e.getArguments()[0])??s,s)},bh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Te(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Zi=(e,t=0)=>{const s=ve(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>gs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Zi(i.getExpression(),t+1):[bh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Nh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Zi(t)},Ph=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:ve(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[])t.excluded.set(Te(i),r.isPropertyAssignment(i)?at(i.getInitializer())??"":"")},wh=(e,t)=>{switch(ct(e)){case"actionCacheDataset":{Fn(e,t,"actionCache");break}case"authDataset":{yh(e,t);break}case"defineDataset":{Ah(e,t);break}case"documentHistoryDataset":{Fn(e,t,"documentHistory");break}}},ps=e=>e!==void 0&&r.isCallExpression(e)&&ct(e)==="defineDataset",er=e=>e!==void 0&&r.isCallExpression(e)&&xh.has(ct(e)??""),Ih=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(ps(i)||er(i))?n:void 0},tr=(e,t,s=0)=>{const n=ve(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>gs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!tr(i.getExpression(),t,s+1))return!1}else if(!ps(i)&&!er(i)){const o=r.isIdentifier(i)?Ih(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Th=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||tr(t,s)?s:void 0},Ch=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(wh(i,t),ct(i)==="definePrivacy"){const o=Nh(i);Ph(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Th(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>ps(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Oh=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),...K(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>vh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},kh=(e,t,s)=>{if(s?.has(hh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Rn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Rn)},i=[],o=[];for(const f of Oh(e,t)){const g=Ch(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:ph(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},sr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&sr(n,t)),Rh=(e,t)=>e.extensionKey!==Eh&&(Ji in e.shape||Object.values(e.shape).some(s=>sr(s,t))),Fh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Ji}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Lh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Rh(o,t.userTables)).map(o=>o.name),[n]=mh(s,t.classifications);if(n!==void 0)throw new M("PRIVACY_COVERAGE",Fh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new M("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Dh=(e,t)=>{const s=Yo(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Mh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Ln=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),_h="",zh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Kh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Qt.Const?t.getInitializer():void 0},Ue=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ue(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Kh(e);if(n!==void 0)return Ue(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},$h=(e,t)=>{if(Mh.has(e))return{method:e,tables:Ue(t)??[_h]}},Ot=(e,t,s)=>e===void 0?void 0:{...e,fields:zh(t,e.method,s)},Bh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Qt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Vh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Bh(n);if(i!==void 0)return Ln.has(s)?Ot({method:s,tables:[i]},e,1):void 0;if($(n))return Ot($h(s,e.getArguments()[0]),e,2);if(Ln.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Ot({method:s,tables:[n.getName()]},e,1)},Uh=(e,t)=>k(e,t,(s,n)=>{const i=Vh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Wh=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),qh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||U(s,"args")===void 0)return!1}return is(e,t).opaque},jh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=se(a);c!==void 0&&qh(a,c.receiver)&&s.push(Wh(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Hh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...jh(i,T(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Gh=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Xe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),nr=e=>!e.isAny(),ir=e=>{const t=e.getType();if(!nr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Gh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Yh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},rr={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Qh=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),Xh={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},Jh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Zh={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},ev=(e,t,s)=>{if(!t.some(i=>$r(i)))return Xh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Jh.has(s.typeName)&&!n&&!t.some(i=>ma(i))?Zh:rr},or=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Qh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},tv=(e,t,s)=>{const n=[];for(const i of J(e)){const o=r.isIdentifier(i.getNameNode())?Rt(i):[i.getName()],c=o.some(u=>Xe(s,t,u))||!Yh(i)?void 0:ir(i),[l=i.getName()]=o;c!==void 0&&n.push(or(t,l,c,i.getStartLineNumber(),ev(i,o,c)))}return n},sv=(e,t,s)=>{if(Xe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=ir(i.getExpression());o!==void 0&&n.push(or(t,"default",o,i.getStartLineNumber(),rr))}return n},nv=(e,t,s)=>[...tv(e,t,s),...sv(e,t,s)],iv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Rt(n).some(i=>Xe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Rt(n).find(o=>Xe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),rv=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),ov=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=T(t,a);n.push(...nv(c,l,s)),i.push(...iv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!nr(a.getType()))&&n.push(rv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},av=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},cv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},lv=(e,t)=>k(e,t,(s,n)=>av(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:cv(s)}:void 0),ar=e=>e==="@lunora/workflow",dv=e=>new Set(e.getImportDeclarations().filter(t=>ar(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),uv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),fv=(e,t)=>{const s=Wn(e,"defineWorkflowEvent",ar),n=dv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!uv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?st(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new M("WORKFLOW_EVENT_NOT_LITERAL",ce(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:T(t,e.getFilePath()),type:l.getLiteralValue()})}return i},gv=(e,t)=>{const s=y(t).flatMap(i=>fv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new M("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},Ce=(e,t)=>{K(e)&&Je(e,"utf8")===t||Pr(e,t,"utf8")},pv=(e,t)=>{if(t===""){we(e,{force:!0});return}Ce(e,t)},mv=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){we(s,{force:!0,recursive:!0});return}if(K(s))for(const n of Dn(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Gt(e,i)]===void 0&&we(i)}for(const[n,i]of Object.entries(t))jt(Ht(v(e,n)),{recursive:!0}),Ce(v(e,n),i)},hv=(e,t,s)=>{const n=v(e,t);if(Object.keys(s).length===0){we(n,{force:!0,recursive:!0});return}if(K(n))for(const i of Dn(n,{recursive:!0,withFileTypes:!0})){const o=v(i.parentPath,i.name);i.isFile()&&s[Gt(n,o)]===void 0&&we(o)}for(const[i,o]of Object.entries(s)){const a=v(n,i);jt(Ht(a),{recursive:!0}),Ce(a,o)}},vv=e=>{try{const t=Ea(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},We=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Ev=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,xv=(e,t)=>{K(e)||jt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Ce(v(e,n.name),n.content),s.push(n.name);break}case"directory":{hv(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{mv(e,n.files),s.push(...Object.keys(n.files));break}default:pv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},Sv=e=>{const t=vv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Aa({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ba({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
29
  `,openApiModuleContent:ya(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
- `,openRpcModuleContent:Na(i)}},Av=".lunora-schema.json",yv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},bv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new M("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new M("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new M("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},Nv=8,Pv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:x}=e,N=()=>ca(()=>{const w=Jr(l,a,{lazyFunctions:o}),W=io(l,a);return{functions:w,httpRoutes:la(l,a),mutators:W}});let{erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N();Xr(y(a).map(w=>l.getSourceFileOrThrow(w)),w=>Gt(a,w.getFilePath())),bn([...P,...Y].map(w=>w.filePath)),bn(B.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const W=u?P:P.filter(I=>I.channel?.kind!=="room"&&I.lifecycle!=="socket"),L=Ra({agents:t,functions:W,httpRoutes:B,mutators:Y,useUmbrella:m,workflows:x}),R={agents:t,functions:W,lazyFunctions:o,migrations:c,mutators:Y,shapes:f,useUmbrella:m,usesSandbox:g},Z=Va(R),ee=Ua(R),ne=Fa({functions:P,useUmbrella:m}),ie=v(a,"_generated",ni),le=[[s,L],[i,ne],[n,Z],...Object.entries(ee).map(([I,F])=>[v(ie,I),F])];if(w>=Nv||le.every(([I,F])=>Ev(l,I,F)))return{apiContent:L,erased:pe,functions:P,functionModulesContent:ee,functionsContent:Z,httpRoutes:B,internalContent:ne,mutators:Y};for(const[I,F]of le)We(l,I,F);({erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N())}},wv=e=>{const t=yv(),s=t?St.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=ho(n),o=e.lazyFunctions===!0||i,a=v(n,"schema.ts");if(!K(a))throw new M("INTERNAL",`schema.ts not found at ${a}`);const c=e.project??To(n);Yr(Wm);const l=ga(c,a,e.projectRoot);Lh(l.tables,kh(c,n,ei(e.projectRoot)));const{agents:u,capabilities:f,containers:g,crons:m,dataModelContent:x,dependencies:N,entryCronTriggers:pe,env:P,featureUsage:B,hasFlags:Y,hasNotify:w,identity:W,platformGate:L,queues:R,serverContent:Z,services:ee,storageRulesMetadata:ne,topics:ie,usesSandbox:le,useUmbrella:I,workflows:F}=wm({lunoraDirectory:n,project:c,projectRoot:e.projectRoot,schema:l,target:e.target});Gm(l,l.jurisdiction===void 0?void 0:jm(c,n));const V=v(n,"_generated"),z=v(V,"dataModel.ts"),cr=v(V,"server.ts"),lr=v(V,"api.ts"),dr=v(V,"internal.ts"),ur=v(V,"functions.ts");We(c,z,x),We(c,cr,Z);const ms=Object.fromEntries(ee.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(ta(p,V))));for(const[p,xt]of Object.entries(ms))We(c,v(V,p),xt);const Oe=ua(c,n),de=pa(c,n),lt=L.signals.typedWebSockets!==!1,{apiContent:hs,erased:fr,functions:q,functionModulesContent:vs,functionsContent:Es,httpRoutes:dt,internalContent:xs,mutators:ut}=Pv({agents:u,apiPath:lr,generatedFunctionsPath:ur,internalPath:dr,lazyFunctions:o,roomsSupported:lt,lunoraDirectory:n,migrations:Oe,project:c,shapes:de,useUmbrella:I,usesSandbox:le,workflows:F}),Ss=Eo(c,n),ft=xo(Ss,l,[...q,...dt].map(p=>p.filePath)),ke=Ss.length>0,Ee=e.lint===!1&&!ke?void 0:{callEdges:Km(c,n),inserts:da(c,n),queries:Bs(c,n,q),tableWrites:Uh(c,n),workflowCalls:lv(c,n)},gr=xa(Ee?.queries??Bs(c,n,q)),Re=e.lint===!1||Ee===void 0?void 0:wp(c,n,{callSites:Ee,containers:g,crons:m,functions:q,modules:ft,mutators:ut,queues:R,schema:l,shapes:de,workflows:F,wranglerVariables:e.wranglerVariables}),As=Re===void 0?[]:Fp(e.projectRoot,[...wr(Re,{source:"static"}),...ov(c,n,{byName:new Set([...F,...R,...u,...g].map(p=>p.exportName)),byPath:new Set([...q,...ut,...de,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...Hh(c,n),...aa(fr,n),...Pa(R,e.wranglerQueueProducers)]),pr=fa(c,n),ys=lh(c,n);bv(de,ys,ah(c,n));const mr=Y?Um(c,n):[],gt=L.signals.vectorStore!==!1,hr=Qo(_e(e.projectRoot,e.target),"deliveryAuthorization"),xe=Dh(B,{containerCount:g.length,cronCount:m.length,dependencies:N,hasPaymentTables:fh(l.tables),queueCount:R.length,storageColumnCount:Object.keys(ti(l)).length,storageRuleCount:ne.rules.length,vectorIndexCount:l.vectorIndexes.length,target:_e(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:F.length}),bs=t?St.now():0,pt=Sa(l,Oe.map(p=>p.id)),mt=ih(c,n),Ns=Zo({advisories:As.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Re?.procedureProtections??[],agents:u,capabilities:f,containers:g,env:P,flagKeys:mr,hasFlags:Y,hasNotify:w,hasIpReaders:q.some(p=>p.readsIp===!0)||de.some(p=>p.readsIp===!0),hasRooms:lt&&q.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:u.length>0||q.some(p=>Io(p)),hasSecretValues:L.signals.secretValues===!0,hasSockets:lt&&q.some(p=>p.lifecycle==="socket"),lazyFunctions:o,hasVectors:gt,liveStreamDeclarations:mt,liveStreams:L.signals.liveStreams===!0,maskMetadata:ys,mutators:ut,queues:R,rlsMetadata:pr,schema:l,schemaSnapshot:pt,shapes:de,services:ee,storageRules:ne,studioFeatures:xe,topics:ie,useUmbrella:I,workflowEvents:gv(c,n),workflows:F}),Ps=Oa(de,N.has("@lunora/db"),I),ws=wa(g,l.jurisdiction),Is=Ia(F,{lazy:o}),Ts=Ta(u,{lazy:o}),Cs=Ca(R,e.wranglerQueueProducers),Os=Wa(mt,I),ks=La(m),vr=Da(xe.scheduler),Fe=Xo(_e(e.projectRoot,e.target)),Er=Fe.supported?Ma(I):"",xr=_a(l.tables,I,l.jurisdiction),Sr=vo(e.projectRoot)?za(I):"",Rs=Ka(l.vectorIndexes),Le=Ba(l,I),Fs=ka(N.has("@lunora/seed")),De=e.apiSpec??"openapi",ht=De==="openapi"||De==="both",vt=De==="openrpc"||De==="both",Ls=ha(N.has("@lunora/auth")),Ds=va({capabilities:f,emailAgents:u.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:N.has("@lunora/cloudflare-access"),hasAuth:N.has("@lunora/auth"),hasFramework:N.has("@lunora/astro")||N.has("@lunora/svelte")||N.has("@lunora/vue")||K(v(e.projectRoot,"src","worker.ts")),hasGlobal:l.tables.some(p=>Jn(p)),hasHyperdriveGlobal:l.tables.some(p=>Zn(p)),hasKvIntrospector:xe.kv,hasNotify:w,hasQueue:R.some(p=>p.mode==="push"),liveStreams:L.signals.liveStreams===!0,liveStreamsWithheld:L.liveStreamsWithheld,liveStreamDeclarations:mt,hasAdminRevocations:Fe.supported,hasScheduler:xe.scheduler,hasSourcedTables:l.tables.some(p=>p.externalSource!==void 0),hasStorage:xe.storage,hasDeliveryAuthorization:hr,hasVectors:gt,hasWorkflow:F.length>0,identity:W,jurisdiction:l.jurisdiction,jurisdictionPinsAuth:l.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:l.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:I,vectorIndexCount:l.vectorIndexes.length,voiceAgents:u.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:ht,wantsOpenRpc:vt}),{openApiContent:Ms,openApiModuleContent:_s,openRpcContent:zs,openRpcModuleContent:Ks}=Sv({functions:q,httpRoutes:dt,modules:ft,projectRoot:e.projectRoot,wantsArchitecture:ke}),Se=ke&&Ee!==void 0?Gp({...Ee,crons:m,functions:q,httpRoutes:dt,modules:ft,queues:R,schema:l,services:ee,topics:ie,workflows:F}):void 0,Et=v(n,Av),Ar=K(Et),yr=e.dryRun?[]:xv(V,[{content:Ds,kind:"always",name:"app.ts"},{content:x,kind:"always",name:"dataModel.ts"},{content:hs,kind:"always",name:"api.ts"},{content:xs,kind:"always",name:"internal.ts"},{content:Z,kind:"always",name:"server.ts"},{content:Es,kind:"always",name:"functions.ts"},{files:vs,kind:"directory",name:ni},{content:Ns,kind:"always",name:"shard.ts"},{content:ks,kind:"always",name:"crons.ts"},{content:Rs,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:ws,kind:"optional",name:"containers.ts"},{content:Is,kind:"optional",name:"workflows.ts"},{content:Ts,kind:"optional",name:"agents.ts"},{content:Cs,kind:"optional",name:"queues.ts"},{content:Os,kind:"optional",name:"live.ts"},{content:vr,kind:"optional",name:"scheduler.ts"},{content:xr,kind:"optional",name:"shardRegistry.ts"},{content:Er,kind:"optional",name:"adminRevocations.ts"},{content:Sr,kind:"optional",name:"durableObjects.ts"},{content:Fs,kind:"optional",name:"seed.ts"},{content:Ls,kind:"optional",name:"authModule.ts"},{content:Ps,kind:"optional",name:"collections.ts"},{files:ms,kind:"services"},{content:ht?Ms:"",kind:"optional",name:"openapi.json"},{content:ht?_s:"",kind:"optional",name:"openapi.ts"},{content:vt?zs:"",kind:"optional",name:"openrpc.json"},{content:vt?Ks:"",kind:"optional",name:"openrpc.ts"},{content:Se===void 0?"":`${JSON.stringify(Se,void 0,2)}
30
+ `,openRpcModuleContent:Na(i)}},Av=".lunora-schema.json",yv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},bv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new M("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new M("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new M("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},Nv=8,Pv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:x}=e,N=()=>ca(()=>{const w=Jr(l,a,{lazyFunctions:o}),W=io(l,a);return{functions:w,httpRoutes:la(l,a),mutators:W}});let{erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N();Xr(y(a).map(w=>l.getSourceFileOrThrow(w)),w=>Gt(a,w.getFilePath())),bn([...P,...Y].map(w=>w.filePath)),bn(B.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const W=u?P:P.filter(I=>I.channel?.kind!=="room"&&I.lifecycle!=="socket"),L=Ra({agents:t,functions:W,httpRoutes:B,mutators:Y,useUmbrella:m,workflows:x}),R={agents:t,functions:W,lazyFunctions:o,migrations:c,mutators:Y,shapes:f,useUmbrella:m,usesSandbox:g},Z=Va(R),ee=Ua(R),ne=Fa({functions:P,useUmbrella:m}),ie=v(a,"_generated",ni),le=[[s,L],[i,ne],[n,Z],...Object.entries(ee).map(([I,F])=>[v(ie,I),F])];if(w>=Nv||le.every(([I,F])=>Ev(l,I,F)))return{apiContent:L,erased:pe,functions:P,functionModulesContent:ee,functionsContent:Z,httpRoutes:B,internalContent:ne,mutators:Y};for(const[I,F]of le)We(l,I,F);({erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N())}},wv=e=>{const t=yv(),s=t?St.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=ho(n),o=e.lazyFunctions===!0||i,a=v(n,"schema.ts");if(!K(a))throw new M("INTERNAL",`schema.ts not found at ${a}`);const c=e.project??To(n);Yr(Wm);const l=ga(c,a,e.projectRoot);Lh(l.tables,kh(c,n,ei(e.projectRoot)));const{agents:u,capabilities:f,containers:g,crons:m,dataModelContent:x,dependencies:N,entryCronTriggers:pe,env:P,featureUsage:B,hasFlags:Y,hasNotify:w,identity:W,platformGate:L,queues:R,serverContent:Z,services:ee,storageRulesMetadata:ne,topics:ie,usesSandbox:le,useUmbrella:I,workflows:F}=wm({lunoraDirectory:n,project:c,projectRoot:e.projectRoot,schema:l,target:e.target});Gm(l,l.jurisdiction===void 0?void 0:jm(c,n));const V=v(n,"_generated"),z=v(V,"dataModel.ts"),cr=v(V,"server.ts"),lr=v(V,"api.ts"),dr=v(V,"internal.ts"),ur=v(V,"functions.ts");We(c,z,x),We(c,cr,Z);const ms=Object.fromEntries(ee.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(ta(p,V))));for(const[p,xt]of Object.entries(ms))We(c,v(V,p),xt);const Oe=ua(c,n),de=pa(c,n),lt=L.signals.typedWebSockets!==!1,{apiContent:hs,erased:fr,functions:q,functionModulesContent:vs,functionsContent:Es,httpRoutes:dt,internalContent:xs,mutators:ut}=Pv({agents:u,apiPath:lr,generatedFunctionsPath:ur,internalPath:dr,lazyFunctions:o,roomsSupported:lt,lunoraDirectory:n,migrations:Oe,project:c,shapes:de,useUmbrella:I,usesSandbox:le,workflows:F}),Ss=Eo(c,n),ft=xo(Ss,l,[...q,...dt].map(p=>p.filePath)),ke=Ss.length>0,Ee=e.lint===!1&&!ke?void 0:{callEdges:Km(c,n),inserts:da(c,n),queries:Bs(c,n,q),tableWrites:Uh(c,n),workflowCalls:lv(c,n)},gr=xa(Ee?.queries??Bs(c,n,q)),Re=e.lint===!1||Ee===void 0?void 0:wp(c,n,{callSites:Ee,containers:g,crons:m,functions:q,modules:ft,mutators:ut,queues:R,schema:l,shapes:de,workflows:F,wranglerVariables:e.wranglerVariables}),As=Re===void 0?[]:Fp(e.projectRoot,[...wr(Re,{source:"static"}),...ov(c,n,{byName:new Set([...F,...R,...u,...g].map(p=>p.exportName)),byPath:new Set([...q,...ut,...de,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...Hh(c,n),...aa(fr,n),...Pa(R,e.wranglerQueueProducers)]),pr=fa(c,n),ys=lh(c,n);bv(de,ys,ah(c,n));const mr=Y?Um(c,n):[],gt=L.signals.vectorStore!==!1,hr=Qo(_e(e.projectRoot,e.target),"deliveryAuthorization"),xe=Dh(B,{containerCount:g.length,cronCount:m.length,dependencies:N,hasPaymentTables:fh(l.tables),queueCount:R.length,storageColumnCount:Object.keys(ti(l)).length,storageRuleCount:ne.rules.length,vectorIndexCount:l.vectorIndexes.length,target:_e(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:F.length}),bs=t?St.now():0,pt=Sa(l,Oe.map(p=>p.id)),mt=ih(c,n),Ns=Zo({advisories:As.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Re?.procedureProtections??[],agents:u,capabilities:f,containers:g,env:P,flagKeys:mr,hasFlags:Y,hasNotify:w,hasIpReaders:q.some(p=>p.readsIp===!0)||de.some(p=>p.readsIp===!0),hasRooms:lt&&q.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:u.length>0||q.some(p=>Io(p)),hasSecretValues:L.signals.secretValues===!0,hasSockets:lt&&q.some(p=>p.lifecycle==="socket"),lazyFunctions:o,hasVectors:gt,liveStreamDeclarations:mt,liveStreams:L.signals.liveStreams===!0,maskMetadata:ys,mutators:ut,queues:R,rlsMetadata:pr,schema:l,schemaSnapshot:pt,shapes:de,services:ee,storageRules:ne,studioFeatures:xe,topics:ie,useUmbrella:I,workflowEvents:gv(c,n),workflows:F}),Ps=Oa(de,N.has("@lunora/db"),I),ws=wa(g,l.jurisdiction),Is=Ia(F,{lazy:o}),Ts=Ta(u,{lazy:o}),Cs=Ca(R,e.wranglerQueueProducers),Os=Wa(mt,I),ks=La(m),vr=Da(xe.scheduler),Fe=Xo(_e(e.projectRoot,e.target)),Er=Fe.supported?Ma(I):"",xr=_a(l.tables,I,l.jurisdiction),Sr=vo(e.projectRoot)?za(I):"",Rs=Ka(l.vectorIndexes),Le=Ba(l,I),Fs=ka(N.has("@lunora/seed")),De=e.apiSpec??"openapi",ht=De==="openapi"||De==="both",vt=De==="openrpc"||De==="both",Ls=ha(N.has("@lunora/auth")),Ds=va({agentWorkflows:u.map(p=>p.className),capabilities:f,emailAgents:u.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:N.has("@lunora/cloudflare-access"),hasAuth:N.has("@lunora/auth"),hasFramework:N.has("@lunora/astro")||N.has("@lunora/svelte")||N.has("@lunora/vue")||K(v(e.projectRoot,"src","worker.ts")),hasGlobal:l.tables.some(p=>Jn(p)),hasHyperdriveGlobal:l.tables.some(p=>Zn(p)),hasKvIntrospector:xe.kv,hasNotify:w,hasQueue:R.some(p=>p.mode==="push"),liveStreams:L.signals.liveStreams===!0,liveStreamsWithheld:L.liveStreamsWithheld,liveStreamDeclarations:mt,hasAdminRevocations:Fe.supported,hasScheduler:xe.scheduler,hasSourcedTables:l.tables.some(p=>p.externalSource!==void 0),hasStorage:xe.storage,hasDeliveryAuthorization:hr,hasVectors:gt,hasWorkflow:F.length>0,identity:W,jurisdiction:l.jurisdiction,jurisdictionPinsAuth:l.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:l.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:I,vectorIndexCount:l.vectorIndexes.length,voiceAgents:u.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:ht,wantsOpenRpc:vt}),{openApiContent:Ms,openApiModuleContent:_s,openRpcContent:zs,openRpcModuleContent:Ks}=Sv({functions:q,httpRoutes:dt,modules:ft,projectRoot:e.projectRoot,wantsArchitecture:ke}),Se=ke&&Ee!==void 0?Gp({...Ee,crons:m,functions:q,httpRoutes:dt,modules:ft,queues:R,schema:l,services:ee,topics:ie,workflows:F}):void 0,Et=v(n,Av),Ar=K(Et),yr=e.dryRun?[]:xv(V,[{content:Ds,kind:"always",name:"app.ts"},{content:x,kind:"always",name:"dataModel.ts"},{content:hs,kind:"always",name:"api.ts"},{content:xs,kind:"always",name:"internal.ts"},{content:Z,kind:"always",name:"server.ts"},{content:Es,kind:"always",name:"functions.ts"},{files:vs,kind:"directory",name:ni},{content:Ns,kind:"always",name:"shard.ts"},{content:ks,kind:"always",name:"crons.ts"},{content:Rs,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:ws,kind:"optional",name:"containers.ts"},{content:Is,kind:"optional",name:"workflows.ts"},{content:Ts,kind:"optional",name:"agents.ts"},{content:Cs,kind:"optional",name:"queues.ts"},{content:Os,kind:"optional",name:"live.ts"},{content:vr,kind:"optional",name:"scheduler.ts"},{content:xr,kind:"optional",name:"shardRegistry.ts"},{content:Er,kind:"optional",name:"adminRevocations.ts"},{content:Sr,kind:"optional",name:"durableObjects.ts"},{content:Fs,kind:"optional",name:"seed.ts"},{content:Ls,kind:"optional",name:"authModule.ts"},{content:Ps,kind:"optional",name:"collections.ts"},{files:ms,kind:"services"},{content:ht?Ms:"",kind:"optional",name:"openapi.json"},{content:ht?_s:"",kind:"optional",name:"openapi.ts"},{content:vt?zs:"",kind:"optional",name:"openrpc.json"},{content:vt?Ks:"",kind:"optional",name:"openrpc.ts"},{content:Se===void 0?"":`${JSON.stringify(Se,void 0,2)}
31
31
  `,kind:"optional",name:"architecture.json"},{content:Se===void 0?"":Yp(Se),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Ar&&Ce(Et,Ir(pt)),t){const p=St.now(),xt=Math.round(p-s),br=Math.round(bs-s),Nr=Math.round(p-bs);console.error(`@lunora/codegen: codegen took ${xt.toString()}ms (discovery ${br.toString()}ms, emit ${Nr.toString()}ms)`)}return{advisories:As,advisorContext:Re,agents:u,architecture:Se,containers:g,cronTriggers:[...new Set([...$a(m),...pe])],generated:{agents:Ts,api:hs,app:Ds,authModule:Ls,collections:Ps,containers:ws,crons:ks,dataModel:x,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:vs,functions:Es,internal:xs,live:Os,openApi:Ms,openApiModule:_s,openRpc:zs,openRpcModule:Ks,queues:Cs,seed:Fs,server:Z,shard:Ns,vectors:Rs,workflows:Is},migrations:Oe,outputDirectory:V,platformDiagnostics:Fe.diagnostic===void 0?L.diagnostics:[...L.diagnostics,Fe.diagnostic],queues:R,indexReferences:gr,schemaSnapshot:pt,schemaSnapshotPath:Et,schemaTables:l.tables,workflows:F,writtenFiles:yr}},WE=e=>Dr(()=>wv(e));export{Av as SCHEMA_SNAPSHOT_FILENAME,To as createCodegenProject,HE as findTsconfig,GE as refreshCodegenProject,WE as runCodegen,YE as tsconfigFingerprint};
@@ -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-BfamDqXW.mjs";import"./shared-DhqnD5R3.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-BHljpfS5.mjs";import"./shared-DhqnD5R3.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-BuNEmlCO.mjs";import{i as q}from"./schema-BgM8A3XV.mjs";import{a as I,I as L,G as y}from"./shared-DhqnD5R3.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...N.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>q(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as N}from"./schema-BgM8A3XV.mjs";import{a as I,I as L,G as y}from"./shared-DhqnD5R3.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...q.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>N(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=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);
@@ -138,22 +138,14 @@ import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";impor
138
138
  * deployed; the dashboard's own metric is per-database and can't name the query.
139
139
  * The emit is best-effort — instrumentation must never fail a served query.
140
140
  */
141
- const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
141
+ const buildSessionExec = (database: D1DatabaseLike, constraint: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
142
142
  // Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
143
143
  // below so a hand-rolled test double that omits it keeps working via
144
- // \`prepare()\` straight on the raw binding — today's behaviour. With no
145
- // inbound bookmark, \`"first-unconstrained"\` is the documented no-op
146
- // equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
147
- const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
144
+ // \`prepare()\` straight on the raw binding — today's behaviour. \`constraint\`
145
+ // is the Sessions API constraint the session opens with (see \`buildExec\`).
146
+ const session = typeof database.withSession === "function" ? database.withSession(constraint) : undefined;
148
147
  const target = session ?? database;
149
148
  const batchFn = target.batch;
150
- const meter = (sql: string, meta: Record<string, unknown> | undefined): void => {
151
- try {
152
- emitD1QueryCost(sql, meta);
153
- } catch {
154
- // Best-effort: never let cost accounting fail the query it measures.
155
- }
156
- };
157
149
 
158
150
  return retryingExec({
159
151
  all: async (sql, parameters) => {
@@ -225,6 +217,56 @@ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bo
225
217
  });
226
218
  };
227
219
 
220
+ const meter = (sql: string, meta: Record<string, unknown> | undefined): void => {
221
+ try {
222
+ emitD1QueryCost(sql, meta);
223
+ } catch {
224
+ // Best-effort: never let cost accounting fail the query it measures.
225
+ }
226
+ };
227
+
228
+ /**
229
+ * The primary exec, for a read that must see every committed write (a policy check on a write
230
+ * path). Every statement opens its own \`"first-primary"\` session, and so does every retry:
231
+ * that constraint covers only a session's first read, so one session shared by two reads, or by
232
+ * a retry, can serve the later read from a replica that has not caught up. It reports no
233
+ * bookmark: the sink keeps the last value it is given, and a later replica read reports an older
234
+ * one, which would move the client's bookmark backwards.
235
+ */
236
+ const buildPrimaryExec = (database: D1DatabaseLike): D1Exec => {
237
+ const statement = (sql: string, parameters: ReadonlyArray<unknown>) =>
238
+ (typeof database.withSession === "function" ? database.withSession("first-primary") : database).prepare(sql).bind(...parameters);
239
+
240
+ return retryingExec({
241
+ all: async (sql, parameters) => {
242
+ const result = await statement(sql, parameters).all<Record<string, unknown>>();
243
+
244
+ meter(sql, result.meta);
245
+
246
+ return result.results;
247
+ },
248
+ run: async (sql, parameters) => {
249
+ const result = await statement(sql, parameters).run();
250
+
251
+ meter(sql, result.meta);
252
+ },
253
+ });
254
+ };
255
+
256
+ /**
257
+ * The replica exec reads at the caller's bookmark, or \`"first-unconstrained"\` (lowest latency,
258
+ * any replica) without one. \`primary\` is the per-statement primary exec (see \`buildPrimaryExec\`).
259
+ */
260
+ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
261
+ const replica = buildSessionExec(database, bookmark ?? "first-unconstrained", onBookmark);
262
+
263
+ if (typeof database.withSession !== "function") {
264
+ return replica;
265
+ }
266
+
267
+ return { ...replica, primary: buildPrimaryExec(database) };
268
+ };
269
+
228
270
  /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
229
271
  const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
230
272
  const exec = buildExec(database);
@@ -544,7 +586,7 @@ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`
544
586
  }`],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(I(r.exportName,"live stream export name"),!L.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}) },`}),ne=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],se=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],oe=e=>p(e)?`liveStreamRouter([
545
587
  ${S(e).join(`
546
588
  `)}
547
- ], host)`:"host",ie=e=>[...re(e),...e.hasAdminRevocations===!1?[]:ae,...e.hasScheduler?[` if (this.schedulerDeclaration) {
589
+ ], host)`:"host",ie=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],ce=e=>[...re(e),...e.hasAdminRevocations===!1?[]:ae,...e.hasScheduler?[` if (this.schedulerDeclaration) {
548
590
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
549
591
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
550
592
  const source = workflowEnv as Record<string, unknown>;
@@ -810,13 +852,13 @@ ${S(e).join(`
810
852
  options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
811
853
  }`:` if (this.accessSelector) {
812
854
  options.resolveIdentity = createAccessResolver(this.accessSelector(env));
813
- }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
855
+ }`]:[],...ie(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
814
856
  ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
815
857
  `)}
816
- };`]:[]],ce=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(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], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"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>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],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,"]:[],...ce(e),...ne(e),...se(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],de=e=>e?`
858
+ };`]:[]],le=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(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], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"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>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],de=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,"]:[],...le(e),...ne(e),...se(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],he=e=>e?`
817
859
  /** The identity memo per \`env\` object, owned by one assembled worker. */
818
860
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
819
- `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,he=e=>{if(!E(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`
861
+ `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ue=e=>{if(!E(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`
820
862
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
821
863
  interface DeferredModules {
822
864
  ${t.map(([a,n])=>` ${a}: ${n};`).join(`
@@ -833,13 +875,13 @@ ${t.map(([a,,n])=>` ${a}: ${n},`).join(`
833
875
  `)}
834
876
  };
835
877
  })());
836
- `},ue=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
878
+ `},pe=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
837
879
  await ensureAuth(env);`:"",n=e?`
838
880
  await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"target",eventWorkerLine:`
839
881
  const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:n,eventWorker:"worker",eventWorkerLine:`
840
- worker ??= ${t};`}},pe=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
841
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},fe=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
842
- `:"",me=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(n=>`${a}{ agent: lunoraAgentDefinitions.${n.exportName}, className: ${JSON.stringify(n.className)} },`).join(`
882
+ worker ??= ${t};`}},me=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
883
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},we=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
884
+ `:"",be=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(n=>`${a}{ agent: lunoraAgentDefinitions.${n.exportName}, className: ${JSON.stringify(n.className)} },`).join(`
843
885
  `);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
844
886
  ${t(" ")}
845
887
  ]);
@@ -858,7 +900,7 @@ ${t(" ")}
858
900
  return agentEmail(message, rawEnv, context);
859
901
  };
860
902
 
861
- `},be=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),we=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=M(t),s=ie(t),i=a?` let auth: LunoraAuth | null = null;
903
+ `},ge=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),ke=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,n=M(t),s=ce(t),i=a?` let auth: LunoraAuth | null = null;
862
904
  let authInit: Promise<void> | null = null;
863
905
  // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
864
906
  // \`assemble()\` has its own auth closure and must not share.
@@ -929,8 +971,8 @@ ${t(" ")}
929
971
  return false;
930
972
  },
931
973
  );
932
- `:"",{asyncIfDeferred:c,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=pe(t),{ensureAuthCall:R,ensureRawAuthCall:D,eventWorker:m,eventWorkerLine:b}=ue(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,A=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,x=t.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
933
- host ? withFrameworkWorker(${oe(t)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,C=t.hasFramework?"host?: FrameworkHostHandler":"",O=me(t),T=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
974
+ `:"",{asyncIfDeferred:c,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=me(t),{ensureAuthCall:R,ensureRawAuthCall:D,eventWorker:m,eventWorkerLine:b}=pe(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,A=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,x=t.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
975
+ host ? withFrameworkWorker(${oe(t)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,C=t.hasFramework?"host?: FrameworkHostHandler":"",O=be(t),T=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
934
976
  public build(): ComposedApp {
935
977
  return this.assemble();
936
978
  }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${Z(t).join(`
@@ -941,7 +983,7 @@ type Selector<Env, T> = (env: Env) => T | undefined;
941
983
 
942
984
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
943
985
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
944
- ${de(a)}${he(t)}${t.jurisdiction?`
986
+ ${he(a)}${ue(t)}${t.jurisdiction?`
945
987
  // Module scope, so every isolate loading this script (the worker and each Durable
946
988
  // Object class it exports) knows the schema's jurisdiction before a request runs.
947
989
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
@@ -1034,7 +1076,7 @@ ${$(t)}${G(t.hasStorage)}
1034
1076
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
1035
1077
  private buildWorkerOptions(env: Env, ${A}): WorkerOptions {
1036
1078
  const options: WorkerOptions = {
1037
- ${le(t).join(`
1079
+ ${de(t).join(`
1038
1080
  `)}
1039
1081
  };
1040
1082
 
@@ -1094,5 +1136,5 @@ interface LunoraConfig<Env extends object = object> {
1094
1136
  const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
1095
1137
 
1096
1138
  export { AppBuilder, defineApp };
1097
- export type { ${be(t)} };
1098
- `};export{we as emitApp,fe as emitAuthModule};
1139
+ export type { ${ge(t)} };
1140
+ `};export{ke as emitApp,we as emitAuthModule};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CVJYK961.mjs";import"./shard-runtime-BfamDqXW.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DXVp_Iht.mjs";import"./shard-runtime-BHljpfS5.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};