@lunora/codegen 1.0.0-alpha.161 → 1.0.0-alpha.162

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CRdh_pOr.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-BvqYMy81.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-B5Qmjmyk.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as h}from"./packem_shared/CONTAINERS_FILENAME-BssQL6eI.mjs";import{default as L}from"./packem_shared/discoverCrons-c0ig327z.mjs";import{FLAGS_FILENAME as I,discoverFlags as F}from"./packem_shared/FLAGS_FILENAME-Bn_wWM4d.mjs";import{default as P}from"./packem_shared/discoverFunctions-DeuEs6Ce.mjs";import{default as G}from"./packem_shared/discoverHttpRoutes-zWSSyyOj.mjs";import{default as b}from"./packem_shared/discoverHyperdriveCalls-C6kV2CPz.mjs";import{default as y}from"./packem_shared/discoverInserts-BB7o_8pU.mjs";import{d as j}from"./packem_shared/index-BsVoa-4F.mjs";import{default as V}from"./packem_shared/discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-DHX1qUP5.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-B07wjsd2.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-BH0djo6F.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-D8DheHbi.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CIfuMMG3.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-CuHe5smg.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-DXdr9YHi.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CXWVNLk4.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-BJHLHZR_.mjs";import{default as xe}from"./packem_shared/discoverSchema-C4znXEB-.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-DhZ3JkkH.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-CSqONfHS.mjs";import{G as Me,e as he,a as _e,b as Le,c as Te,d as Ie,f as Fe,g as De,h as Pe,i as Ue,j as Ge,k as He,l as be,m as ke}from"./packem_shared/emit-BNdsZPcd.mjs";import{emitApp as We}from"./packem_shared/emitApp-x-gjOrYL.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-qYjkmRTX.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as qe,emitOpenRpc as Be,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-BgLkvCYK.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-lPq34YeN.mjs";import{SCHEMA_SNAPSHOT_FILENAME as or,createCodegenProject as tr,findTsconfig as sr,refreshCodegenProject as ar,runCodegen as ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-DqFQB0lY.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as fr,evaluateSchemaDrift as pr,parseSchemaSnapshot as cr}from"./packem_shared/SchemaSnapshotParseError-yrVM8bTa.mjs";import{schemaFromIr as lr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as xr,validatorIrToJsonSchema as Er}from"./packem_shared/LUNORA_ERROR_CODES-CW7-uASH.mjs";import{SDK_LANGUAGES as ur,SDK_TARGETS as vr,generateSdk as Nr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Or,secretKindOf as Rr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Mr,findSolutionByMessage as hr}from"@lunora/errors";import{isTypedSchema as Lr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,Xe as DEFAULT_TARGET,I as FLAGS_FILENAME,Me as GENERATED_HEADER,xr as LUNORA_ERROR_CODES,Mr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,we as OPENRPC_VERSION,se as QUEUES_FILENAME,or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ur as SDK_LANGUAGES,vr as SDK_TARGETS,Ae as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,qe as buildOpenRpcDocument,fr as buildSchemaSnapshot,tr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,R as discoverAuthApiCalls,h as discoverContainers,L as discoverCrons,F as discoverFlags,P as discoverFunctions,G as discoverHttpRoutes,b as discoverHyperdriveCalls,y as discoverInserts,j as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Re as discoverWorkflows,he as emitAgents,_e as emitApi,We as emitApp,Le as emitCollections,Te as emitContainers,Ie as emitCrons,Fe as emitDataModel,De as emitDrizzleSchema,Pe as emitFunctions,Ve as emitOpenApi,ze as emitOpenApiModule,Be as emitOpenRpc,Je as emitOpenRpcModule,Ue as emitServer,Ge as emitShard,He as emitVectors,be as emitWorkflows,ke as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,pr as evaluateSchemaDrift,hr as findLunoraSolution,sr as findTsconfig,m as formatAdvisories,Nr as generateSdk,Lr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,cr as parseSchemaSnapshot,Ze as platformMatrixIds,ee as readPackageDependencies,$e as readProjectTarget,Or as redact,ar as refreshCodegenProject,er as resolveCodegenTarget,ir as runCodegen,lr as schemaFromIr,Rr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Er as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CRdh_pOr.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-BvqYMy81.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-B5Qmjmyk.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as h}from"./packem_shared/CONTAINERS_FILENAME-BssQL6eI.mjs";import{default as L}from"./packem_shared/discoverCrons-c0ig327z.mjs";import{FLAGS_FILENAME as I,discoverFlags as F}from"./packem_shared/FLAGS_FILENAME-Bn_wWM4d.mjs";import{default as P}from"./packem_shared/discoverFunctions-DeuEs6Ce.mjs";import{default as G}from"./packem_shared/discoverHttpRoutes-zWSSyyOj.mjs";import{default as b}from"./packem_shared/discoverHyperdriveCalls-C6kV2CPz.mjs";import{default as y}from"./packem_shared/discoverInserts-BB7o_8pU.mjs";import{d as j}from"./packem_shared/index-BsVoa-4F.mjs";import{default as V}from"./packem_shared/discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-DHX1qUP5.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-B07wjsd2.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-BH0djo6F.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-D8DheHbi.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CIfuMMG3.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-CuHe5smg.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-DXdr9YHi.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CXWVNLk4.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-BJHLHZR_.mjs";import{default as xe}from"./packem_shared/discoverSchema-C4znXEB-.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-DhZ3JkkH.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-CSqONfHS.mjs";import{G as Me,e as he,a as _e,b as Le,c as Te,d as Ie,f as Fe,g as De,h as Pe,i as Ue,j as Ge,k as He,l as be,m as ke}from"./packem_shared/emit-BNdsZPcd.mjs";import{emitApp as We}from"./packem_shared/emitApp-CxmA4W3C.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-qYjkmRTX.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as qe,emitOpenRpc as Be,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-BgLkvCYK.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-lPq34YeN.mjs";import{SCHEMA_SNAPSHOT_FILENAME as or,createCodegenProject as tr,findTsconfig as sr,refreshCodegenProject as ar,runCodegen as ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-B9S14dpw.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as fr,evaluateSchemaDrift as pr,parseSchemaSnapshot as cr}from"./packem_shared/SchemaSnapshotParseError-yrVM8bTa.mjs";import{schemaFromIr as lr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as xr,validatorIrToJsonSchema as Er}from"./packem_shared/LUNORA_ERROR_CODES-CW7-uASH.mjs";import{SDK_LANGUAGES as ur,SDK_TARGETS as vr,generateSdk as Nr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Or,secretKindOf as Rr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Mr,findSolutionByMessage as hr}from"@lunora/errors";import{isTypedSchema as Lr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,Xe as DEFAULT_TARGET,I as FLAGS_FILENAME,Me as GENERATED_HEADER,xr as LUNORA_ERROR_CODES,Mr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,we as OPENRPC_VERSION,se as QUEUES_FILENAME,or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ur as SDK_LANGUAGES,vr as SDK_TARGETS,Ae as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,qe as buildOpenRpcDocument,fr as buildSchemaSnapshot,tr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,R as discoverAuthApiCalls,h as discoverContainers,L as discoverCrons,F as discoverFlags,P as discoverFunctions,G as discoverHttpRoutes,b as discoverHyperdriveCalls,y as discoverInserts,j as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Re as discoverWorkflows,he as emitAgents,_e as emitApi,We as emitApp,Le as emitCollections,Te as emitContainers,Ie as emitCrons,Fe as emitDataModel,De as emitDrizzleSchema,Pe as emitFunctions,Ve as emitOpenApi,ze as emitOpenApiModule,Be as emitOpenRpc,Je as emitOpenRpcModule,Ue as emitServer,Ge as emitShard,He as emitVectors,be as emitWorkflows,ke as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,pr as evaluateSchemaDrift,hr as findLunoraSolution,sr as findTsconfig,m as formatAdvisories,Nr as generateSdk,Lr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,cr as parseSchemaSnapshot,Ze as platformMatrixIds,ee as readPackageDependencies,$e as readProjectTarget,Or as redact,ar as refreshCodegenProject,er as resolveCodegenTarget,ir as runCodegen,lr as schemaFromIr,Rr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Er as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as P,mkdirSync as ls,readFileSync as Pt,writeFileSync as us,rmSync as ds}from"node:fs";import{join as f,dirname as Z}from"node:path";import{performance as me}from"node:perf_hooks";import{runAdvisor as fs}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as et}from"ts-morph";import{serializeSchemaSnapshot as gs}from"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{toAdvisorContext as ps}from"./formatAdvisories-CkEu1eye.mjs";import{s as ms}from"./paths-C-9fwEgQ.mjs";import{discoverAgents as hs}from"./AGENTS_FILENAME-CRdh_pOr.mjs";import{discoverContainers as xs}from"./CONTAINERS_FILENAME-BssQL6eI.mjs";import Es from"./discoverCrons-c0ig327z.mjs";import{diagnosticAt as oe}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ie}from"./module-specifiers-WF8iAydP.mjs";import{C as he,n as It,i as vs,f as Ss,j as ys,b as As,c as Ns,l as bs,e as Ps,o as Is,d as ws,k as Ts,g as Cs,p as Fs,m as Os,a as Rs,h as Ls}from"./emit-BNdsZPcd.mjs";import{listLunoraSourceFiles as m,unwrapExpression as V,lunoraRelativePath as v,collectCallRows as w,collectSecurityCallRows as Ds,propertyInitializer as b,listSecurityScanFiles as wt,limitNameOf as Tt,isContextIdentifier as Se,handlerOf as ks,isDatabaseAccessor as M,readTargetOf as Ct,enclosingExportName as Ms}from"./listLunoraSourceFiles-BvqYMy81.mjs";import Ks from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as _s}from"./QUEUES_FILENAME-CIfuMMG3.mjs";import{discoverSandboxUsage as zs}from"./discoverSandboxUsage-BJHLHZR_.mjs";import Us from"./discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{discoverWorkflows as Bs}from"./WORKFLOWS_FILENAME-CSqONfHS.mjs";import{gatePlatformFeatures as $s,resolveCodegenTarget as qs}from"./DEFAULT_TARGET-lPq34YeN.mjs";import{i as R,a as _,e as E,r as js,b as Vs,s as ae,c as Ws,f as Hs,d as Gs}from"./queries-D8DheHbi.mjs";import{a as y,c as z,d as Ft,e as Ys}from"./classify-procedure-call-CRm5Etni.mjs";import Xs from"./discoverAuthApiCalls-B5Qmjmyk.mjs";import tt from"./discoverFunctions-DeuEs6Ce.mjs";import{i as Qs,r as Zs,e as Js}from"./unwrap-handler-return-CmIWbykC.mjs";import st from"./discoverHttpRoutes-zWSSyyOj.mjs";import en from"./discoverHyperdriveCalls-C6kV2CPz.mjs";import tn from"./discoverInserts-BB7o_8pU.mjs";import{m as Pe,a as ee,s as Ot,d as sn}from"./index-BsVoa-4F.mjs";import{e as Rt}from"./exported-procedure-chains-Cmt3Pr92.mjs";import nn from"./discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as rn,isDefineMutatorCallee as on,discoverMutators as nt}from"./MUTATORS_FILENAME-DHX1qUP5.mjs";import an from"./discoverNondeterministicCalls-B07wjsd2.mjs";import{discoverNotifyConfig as cn,discoverNotifyCalls as ln}from"./NOTIFY_FILENAME-BH0djo6F.mjs";import un from"./discoverR2sqlCalls-CuHe5smg.mjs";import dn from"./discoverRlsProcedures-DXdr9YHi.mjs";import fn from"./discoverRlsMetadata-CXWVNLk4.mjs";import gn from"./discoverSchema-C4znXEB-.mjs";import{secretKindOf as pn,redact as mn,isHeuristicSecretKind as hn,isSecretishName as xn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as En}from"./SHAPES_FILENAME-DhZ3JkkH.mjs";import{emitApp as vn}from"./emitApp-x-gjOrYL.mjs";import{buildOpenApiDocument as Sn,emitOpenApiModule as yn}from"./buildOpenApiDocument-qYjkmRTX.mjs";import{buildOpenRpcDocument as An,emitOpenRpcModule as Nn}from"./OPENRPC_VERSION-BgLkvCYK.mjs";import{s as bn}from"./parse-validator-CMV0eq2a.mjs";import{buildSchemaSnapshot as Pn}from"./SchemaSnapshotParseError-yrVM8bTa.mjs";const rt=(e,t="api")=>{const s=new Map;for(const n of e){const o=ms(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new k("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},In=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1}=t,r=[],a=e.tables.filter(c=>c.shardMode==="global");return a.some(c=>c.globalBackend!=="hyperdrive")&&r.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),a.some(c=>c.globalBackend==="hyperdrive")&&r.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&r.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&r.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&r.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"}),r},wn=(e,t,s={})=>{if(t===void 0)return;const n=In(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
1
+ import{existsSync as P,mkdirSync as ls,readFileSync as Pt,writeFileSync as us,rmSync as ds}from"node:fs";import{join as f,dirname as Z}from"node:path";import{performance as me}from"node:perf_hooks";import{runAdvisor as fs}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as et}from"ts-morph";import{serializeSchemaSnapshot as gs}from"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{toAdvisorContext as ps}from"./formatAdvisories-CkEu1eye.mjs";import{s as ms}from"./paths-C-9fwEgQ.mjs";import{discoverAgents as hs}from"./AGENTS_FILENAME-CRdh_pOr.mjs";import{discoverContainers as xs}from"./CONTAINERS_FILENAME-BssQL6eI.mjs";import Es from"./discoverCrons-c0ig327z.mjs";import{diagnosticAt as oe}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ie}from"./module-specifiers-WF8iAydP.mjs";import{C as he,n as It,i as vs,f as Ss,j as ys,b as As,c as Ns,l as bs,e as Ps,o as Is,d as ws,k as Ts,g as Cs,p as Fs,m as Os,a as Rs,h as Ls}from"./emit-BNdsZPcd.mjs";import{listLunoraSourceFiles as m,unwrapExpression as V,lunoraRelativePath as v,collectCallRows as w,collectSecurityCallRows as Ds,propertyInitializer as b,listSecurityScanFiles as wt,limitNameOf as Tt,isContextIdentifier as Se,handlerOf as ks,isDatabaseAccessor as M,readTargetOf as Ct,enclosingExportName as Ms}from"./listLunoraSourceFiles-BvqYMy81.mjs";import Ks from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as _s}from"./QUEUES_FILENAME-CIfuMMG3.mjs";import{discoverSandboxUsage as zs}from"./discoverSandboxUsage-BJHLHZR_.mjs";import Us from"./discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{discoverWorkflows as Bs}from"./WORKFLOWS_FILENAME-CSqONfHS.mjs";import{gatePlatformFeatures as $s,resolveCodegenTarget as qs}from"./DEFAULT_TARGET-lPq34YeN.mjs";import{i as R,a as _,e as E,r as js,b as Vs,s as ae,c as Ws,f as Hs,d as Gs}from"./queries-D8DheHbi.mjs";import{a as y,c as z,d as Ft,e as Ys}from"./classify-procedure-call-CRm5Etni.mjs";import Xs from"./discoverAuthApiCalls-B5Qmjmyk.mjs";import tt from"./discoverFunctions-DeuEs6Ce.mjs";import{i as Qs,r as Zs,e as Js}from"./unwrap-handler-return-CmIWbykC.mjs";import st from"./discoverHttpRoutes-zWSSyyOj.mjs";import en from"./discoverHyperdriveCalls-C6kV2CPz.mjs";import tn from"./discoverInserts-BB7o_8pU.mjs";import{m as Pe,a as ee,s as Ot,d as sn}from"./index-BsVoa-4F.mjs";import{e as Rt}from"./exported-procedure-chains-Cmt3Pr92.mjs";import nn from"./discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as rn,isDefineMutatorCallee as on,discoverMutators as nt}from"./MUTATORS_FILENAME-DHX1qUP5.mjs";import an from"./discoverNondeterministicCalls-B07wjsd2.mjs";import{discoverNotifyConfig as cn,discoverNotifyCalls as ln}from"./NOTIFY_FILENAME-BH0djo6F.mjs";import un from"./discoverR2sqlCalls-CuHe5smg.mjs";import dn from"./discoverRlsProcedures-DXdr9YHi.mjs";import fn from"./discoverRlsMetadata-CXWVNLk4.mjs";import gn from"./discoverSchema-C4znXEB-.mjs";import{secretKindOf as pn,redact as mn,isHeuristicSecretKind as hn,isSecretishName as xn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as En}from"./SHAPES_FILENAME-DhZ3JkkH.mjs";import{emitApp as vn}from"./emitApp-CxmA4W3C.mjs";import{buildOpenApiDocument as Sn,emitOpenApiModule as yn}from"./buildOpenApiDocument-qYjkmRTX.mjs";import{buildOpenRpcDocument as An,emitOpenRpcModule as Nn}from"./OPENRPC_VERSION-BgLkvCYK.mjs";import{s as bn}from"./parse-validator-CMV0eq2a.mjs";import{buildSchemaSnapshot as Pn}from"./SchemaSnapshotParseError-yrVM8bTa.mjs";const rt=(e,t="api")=>{const s=new Map;for(const n of e){const o=ms(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new k("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},In=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1}=t,r=[],a=e.tables.filter(c=>c.shardMode==="global");return a.some(c=>c.globalBackend!=="hyperdrive")&&r.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),a.some(c=>c.globalBackend==="hyperdrive")&&r.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&r.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&r.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&r.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"}),r},wn=(e,t,s={})=>{if(t===void 0)return;const n=In(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
2
2
  `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${o}
4
4
 
@@ -1,9 +1,9 @@
1
- import{A as S,G as E}from"./emit-BNdsZPcd.mjs";const D=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[D(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),x=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],A=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],R=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],C=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],O=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],T=e=>e?['import notifyConfig from "../notify.js";']:[],f=e=>(e.emailAgents?.length??0)>0,I=e=>f(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>f(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],q=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:o,hasKvIntrospector:h,hasQueue:c,hasScheduler:i,hasStorage:u,hasWorkflow:p,useUmbrella:b,wantsOpenApi:l,wantsOpenRpc:g}=e,d=b?"lunorash/runtime":"@lunora/runtime",s=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];c&&s.push("TriggerTrace"),n&&s.push("GlobalIntrospector","AdminTableResolver"),r&&s.push("FrameworkHostHandler");const k=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...A(t,a),...O(n),...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(h),...C(e.hasVectors===!0),...i?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...p?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...I(e),`import type { ${[...s].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${d}";`,`import { ${k} } from "${d}";`,"",...x(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...T(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...c?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...l?['import { openApiSpec } from "./openapi.js";']:[],...g?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},N=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;"," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],G=e=>v.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
1
+ import{A as f,G as w}from"./emit-BNdsZPcd.mjs";const y=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,g=f.map(({appMethod:e,key:t})=>[y(t),e.method,e.configKey,e.doc]),u=e=>g.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],A=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],R=e=>e?['import notifyConfig from "../notify.js";']:[],m=e=>(e.emailAgents?.length??0)>0,C=e=>m(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>m(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",c=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...c].toSorted((l,d)=>l.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:c,hasStorage:s,hasWorkflow:l,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...A(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...c?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...l?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...R(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},L=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],q=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;"," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...u(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],N=e=>g.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
2
2
  public ${t}(factory: NonNullable<ShardConfig["${a}"]>): this {
3
3
  this.shardExtras.${a} = factory;
4
4
 
5
5
  return this;
6
- }`),B=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
6
+ }`),j=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
7
7
  public admin(selector: Selector<Env, string>): this {
8
8
  this.adminToken = selector;
9
9
 
@@ -52,7 +52,7 @@ import{A as S,G as E}from"./emit-BNdsZPcd.mjs";const D=e=>`has${e.charAt(0).toUp
52
52
  this.storageDeclaration = declaration;
53
53
 
54
54
  return this;
55
- }`]:[],...G(e)],W=e=>{const t=r=>e.hasScheduler?`
55
+ }`]:[],...N(e)],G=e=>{const t=r=>e.hasScheduler?`
56
56
  ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,",...e.hasGlobal?[` ...(this.globalDeclaration
57
57
  ? {
58
58
  d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
@@ -124,10 +124,10 @@ import{A as S,G as E}from"./emit-BNdsZPcd.mjs";const D=e=>`has${e.charAt(0).toUp
124
124
  ? {
125
125
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
126
126
  }
127
- : {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
127
+ : {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...u(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
128
128
  ${a.join(`
129
129
  `)}
130
- `:""},P=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
130
+ `:""},B=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
131
131
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
132
132
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
133
133
  const source = workflowEnv as Record<string, unknown>;
@@ -269,14 +269,14 @@ ${a.join(`
269
269
  }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
270
270
  ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
271
271
  `)}
272
- };`]:[]],_=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],$=e=>e.hasScheduler?`
272
+ };`]:[]],W=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],P=e=>e.hasScheduler?`
273
273
  /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
274
274
  private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
275
275
  const namespace = this.schedulerDeclaration?.namespace(env);
276
276
 
277
277
  return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
278
278
  }
279
- `:"",H=e=>e?`
279
+ `:"",_=e=>e?`
280
280
  /**
281
281
  * One bucket's \`Storage\`, signing under the name it is registered as.
282
282
  *
@@ -379,7 +379,7 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
379
379
  storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
380
380
  };
381
381
  }
382
- `:"",U=e=>e?`
382
+ `:"",$=e=>e?`
383
383
  /**
384
384
  * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
385
385
  *
@@ -583,9 +583,9 @@ const buildGlobalCdcApplier =
583
583
 
584
584
  return request.changes.length;
585
585
  };
586
- `:"",F=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),Q=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=N(t),n=P(t),o=a?` let auth: LunoraAuth | null = null;
586
+ `:"",H=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),F=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=L(t),n=B(t),i=a?` let auth: LunoraAuth | null = null;
587
587
  let authInit: Promise<void> | null = null;
588
- `:"",h=a?`
588
+ `:"",o=a?`
589
589
  const initAuth = async (env: Env): Promise<void> => {
590
590
  if (!this.authDeclaration) {
591
591
  return;
@@ -625,21 +625,21 @@ const buildGlobalCdcApplier =
625
625
  throw error;
626
626
  }));
627
627
  `:"",c=a?`
628
- await ensureAuth(env);`:"",i=a?"() => auth":"() => null",u=a?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",p=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
629
- host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${i})) : createWorker(this.buildWorkerOptions(env, ${i}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${i}));`,b=t.hasFramework?"host?: FrameworkHostHandler":"",l=t.emailAgents??[],g=l.length>0?` composed.email = dispatchAgentEmail([
630
- ${l.map(s=>` { agent: lunoraAgentDefinitions.${s.exportName}, binding: ${JSON.stringify(s.bindingName)} },`).join(`
628
+ await ensureAuth(env);`:"",s=a?"() => auth":"() => null",l=a?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",d=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
629
+ host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,h=t.hasFramework?"host?: FrameworkHostHandler":"",p=t.emailAgents??[],v=p.length>0?` composed.email = dispatchAgentEmail([
630
+ ${p.map(b=>` { agent: lunoraAgentDefinitions.${b.exportName}, binding: ${JSON.stringify(b.bindingName)} },`).join(`
631
631
  `)}
632
632
  ]);
633
633
 
634
- `:"",d=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
634
+ `:"",k=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
635
635
  public build(): ComposedApp {
636
636
  return this.assemble();
637
- }${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`${E}${q(t).join(`
637
+ }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${w}${I(t).join(`
638
638
  `)}
639
639
 
640
640
  /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
641
641
  type Selector<Env, T> = (env: Env) => T | undefined;
642
- ${m(t)?"\n/** The generated `createShardDO` config — the long-tail `.ai()` / `.kv()` / … methods pass straight through to it. */\ntype ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;\n":""}
642
+ ${u(t)?"\n/** The generated `createShardDO` config — the long-tail `.ai()` / `.kv()` / … methods pass straight through to it. */\ntype ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;\n":""}
643
643
  ${r.join(`
644
644
 
645
645
  `)}${r.length>0?`
@@ -659,27 +659,27 @@ interface ComposedApp extends LunoraWorker {
659
659
  * first request so per-isolate singletons are built once.
660
660
  */
661
661
  class AppBuilder<Env extends object> {
662
- ${j(t).join(`
662
+ ${q(t).join(`
663
663
  `)}
664
664
 
665
665
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
666
666
 
667
- ${B(t).join(`
667
+ ${j(t).join(`
668
668
 
669
669
  `)}
670
670
 
671
- ${d}
671
+ ${k}
672
672
 
673
673
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
674
- private assemble(${b}): ComposedApp {
675
- const ShardDO = createShardDO({${W(t)}});
674
+ private assemble(${h}): ComposedApp {
675
+ const ShardDO = createShardDO({${G(t)}});
676
676
 
677
677
  // Per-isolate singletons: the worker (and auth instance) are expensive to
678
678
  // build, so the first request constructs them and every later request on
679
679
  // the same isolate reuses them.
680
680
  let worker: LunoraWorker | null = null;
681
- ${o}${h}
682
- ${p}
681
+ ${i}${o}
682
+ ${d}
683
683
 
684
684
  const composed: ComposedApp = {
685
685
  ShardDO,
@@ -706,7 +706,7 @@ ${p}
706
706
  },`:""}
707
707
  };
708
708
 
709
- ${g} if (this.emailHandler) {
709
+ ${v} if (this.emailHandler) {
710
710
  const handler = this.emailHandler;
711
711
 
712
712
  composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
@@ -714,11 +714,11 @@ ${g} if (this.emailHandler) {
714
714
 
715
715
  return composed;
716
716
  }
717
- ${$(t)}${H(t.hasStorage)}
717
+ ${P(t)}${_(t.hasStorage)}
718
718
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
719
- private buildWorkerOptions(env: Env, ${u}): WorkerOptions {
719
+ private buildWorkerOptions(env: Env, ${l}): WorkerOptions {
720
720
  const options: WorkerOptions = {
721
- ${_(t).join(`
721
+ ${W(t).join(`
722
722
  `)}
723
723
  };
724
724
 
@@ -737,7 +737,7 @@ ${n.join(`
737
737
  return options;
738
738
  }
739
739
  }
740
- ${U(t.hasGlobal)}
740
+ ${$(t.hasGlobal)}
741
741
  /**
742
742
  * Start composing the app. Chain the capability methods, then \`.build()\`.
743
743
  *
@@ -751,5 +751,5 @@ ${U(t.hasGlobal)}
751
751
  const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
752
752
 
753
753
  export { AppBuilder, defineApp };
754
- export type { ${F(t)} };
755
- `};export{Q as emitApp};
754
+ export type { ${H(t)} };
755
+ `};export{F as emitApp};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.161",
3
+ "version": "1.0.0-alpha.162",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.113",
50
- "@lunora/agent": "1.0.0-alpha.92",
49
+ "@lunora/advisor": "1.0.0-alpha.114",
50
+ "@lunora/agent": "1.0.0-alpha.93",
51
51
  "@lunora/container": "1.0.0-alpha.47",
52
52
  "@lunora/errors": "1.0.0-alpha.34",
53
53
  "@lunora/platform": "1.0.0-alpha.27",
54
- "@lunora/queue": "1.0.0-alpha.49",
55
- "@lunora/scheduler": "1.0.0-alpha.56",
54
+ "@lunora/queue": "1.0.0-alpha.50",
55
+ "@lunora/scheduler": "1.0.0-alpha.57",
56
56
  "@lunora/values": "1.0.0-alpha.42",
57
57
  "@lunora/workflow": "1.0.0-alpha.47",
58
58
  "jsonc-parser": "^3.3.1",