@lunora/codegen 1.0.0-alpha.115 → 1.0.0-alpha.117
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 +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-hlnTcuPd.mjs → GENERATED_HEADER-TYN36IWp.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-DpRms_jN.mjs → OPENRPC_VERSION-BGbPExk0.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CGCzlXbr.mjs → SCHEMA_SNAPSHOT_FILENAME-ks41Eeih.mjs} +1 -1
- package/dist/packem_shared/{SDK_LANGUAGES-DcXlLVZ1.mjs → SDK_LANGUAGES-BHYgTciL.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-ClEtrbbS.mjs → buildOpenApiDocument-Dk1RRaq3.mjs} +1 -1
- package/dist/packem_shared/{emit-CV6JjAt9.mjs → emit-B6siM7LU.mjs} +73 -68
- package/dist/packem_shared/{emitApp-BBcZ_fPU.mjs → emitApp-C6P6ckvr.mjs} +1 -1
- package/package.json +1 -1
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-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4eSpCR6m.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DOirwCWw.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-D-09Qb8S.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-sGAt-yC1.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-DhNToI6C.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-CTZI61e3.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-B6e4j4rD.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Pw0_c1aS.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-D_wHstA-.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-DthHu3mC.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4eSpCR6m.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DOirwCWw.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-D-09Qb8S.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-sGAt-yC1.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-DhNToI6C.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-CTZI61e3.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-B6e4j4rD.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Pw0_c1aS.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-D_wHstA-.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-DthHu3mC.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-B6siM7LU.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-C6P6ckvr.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-Dk1RRaq3.mjs";import{OPENRPC_VERSION as je,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-BGbPExk0.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as qe,readProjectTarget as Be,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CIH5PRk1.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Xe,createCodegenProject as Ze,findTsconfig as $e,refreshCodegenProject as er,runCodegen as rr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-ks41Eeih.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-Dc1aZAph.mjs";import{schemaFromIr as dr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as cr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as Sr,SDK_TARGETS as lr,generateSdk as Er}from"./packem_shared/SDK_LANGUAGES-BHYgTciL.mjs";import{redact as Ar,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Nr,findSolutionByMessage as gr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-BBIBMZTg.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,T as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Nr as LUNORA_SOLUTION_RULES,j as MUTATORS_FILENAME,w as NOTIFY_FILENAME,je as OPENRPC_VERSION,ee as QUEUES_FILENAME,Xe as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Sr as SDK_LANGUAGES,lr as SDK_TARGETS,ne as SHAPES_FILENAME,tr as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,sr as buildSchemaSnapshot,Ze as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,g as discoverAuthApiCalls,M as discoverContainers,C as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,z as discoverNondeterministicCalls,q as discoverNotifyCalls,B as discoverNotifyConfig,Z as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,ge as emitAgents,Oe as emitApi,Ge as emitApp,Re as emitCollections,Me as emitContainers,he as emitCrons,Ce as emitDataModel,_e as emitDrizzleSchema,Te as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Ve as emitOpenRpc,ze as emitOpenRpcModule,Ie as emitServer,Le as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ar as evaluateSchemaDrift,gr as findLunoraSolution,$e as findTsconfig,m as formatAdvisories,Er as generateSdk,Rr as isTypedSchema,d as lintSchema,ir as parseSchemaSnapshot,qe as platformMatrixIds,Y as readPackageDependencies,Be as readProjectTarget,Ar as redact,er as refreshCodegenProject,Je as resolveCodegenTarget,rr as runCodegen,dr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,cr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-B6siM7LU.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-B6siM7LU.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
2
|
`,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-
|
|
1
|
+
import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-B6siM7LU.mjs";import{l as h,a as E,c as y,p as S,f as xt,i as gs,r as Et,e as ms}from"./discover-ast-D33zP-NZ.mjs";import hs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as xs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as Es}from"./discoverSandboxUsage-L0lV17de.mjs";import vs from"./discoverStorageRulesMetadata-DthHu3mC.mjs";import{discoverWorkflows as Ss}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as As,resolveCodegenTarget as Ns}from"./DEFAULT_TARGET-CIH5PRk1.mjs";import{i as T,a as F,e as x,c as I,r as ys,b as bs,s as te,f as Is,g as Ps,d as ws}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Ts,procedureHandler as vt,chainUsesWrappedCall as St,isDatabaseAccessor as K,chainHasStep as Cs,discoverFunctions as Rs,resolveStandardSchemaType as Os}from"./discoverFunctions-4eSpCR6m.mjs";import Fs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Ls from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Ds}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import ks from"./discoverHttpRoutes-DOirwCWw.mjs";import Ms from"./discoverInserts-YX8AmrzL.mjs";import Ks,{discoverMaskStrategies as _s,discoverMaskMetadata as zs,discoverMaskHasNonLiteralPolicy as Us}from"./discoverMaskProcedures-D-09Qb8S.mjs";import Bs from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as qs,isDefineMutatorCallee as $s,discoverMutators as js}from"./MUTATORS_FILENAME-sGAt-yC1.mjs";import Vs from"./discoverNondeterministicCalls-DhNToI6C.mjs";import{discoverNotifyConfig as Ws,discoverNotifyCalls as Hs}from"./NOTIFY_FILENAME-CTZI61e3.mjs";import Gs from"./discoverR2sqlCalls-B6e4j4rD.mjs";import Ys,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-Pw0_c1aS.mjs";import Xs from"./discoverSchema-D_wHstA-.mjs";import{secretKindOf as Zs,redact as Js,isHeuristicSecretKind as en,isSecretishName as tn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as sn}from"./SHAPES_FILENAME-DTp6VI6K.mjs";import{emitApp as nn}from"./emitApp-C6P6ckvr.mjs";import{buildOpenApiDocument as rn,emitOpenApiModule as on}from"./buildOpenApiDocument-Dk1RRaq3.mjs";import{buildOpenRpcDocument as an,emitOpenRpcModule as cn}from"./OPENRPC_VERSION-BGbPExk0.mjs";import{s as ln}from"./parse-validator-C5ycrhR3.mjs";import{buildSchemaSnapshot as un}from"./SchemaSnapshotParseError-Dc1aZAph.mjs";const dn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(n=>n.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},fn=(e,t)=>{if(t===void 0)return;const s=dn(e).filter(o=>!t.has(o.name));if(s.length===0)return;const n=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
2
2
|
`);throw new O("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${n}
|
|
4
4
|
|
|
@@ -268,7 +268,7 @@ serde = { version = "1", features = ["derive"] }
|
|
|
268
268
|
serde_json = "1"
|
|
269
269
|
`,Qn=new Set(["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","static","struct","super","trait","true","try","type","typeof","unsafe","unsized","use","virtual","where","while","yield"]),O=e=>{const n=B(e);return Qn.has(n)?`r#${n}`:n},er=e=>`Verb::${o(e)}`,Se=e=>e.length===0?"&[]":`&[${e.map(n=>`&["${n.map(r=>$(r)).join('", "')}"][..]`).join(", ")}]`,oe=e=>{const n=p(e,{none:"&self, shard_key: Option<&str>",typed:a=>`&self, args: &${a}, shard_key: Option<&str>`,untyped:"&self, args: &WireValue, shard_key: Option<&str>"}),r=p(e,{none:"&WireValue::Object(Vec::new())",typed:()=>`&from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Se(e.argsNullPaths.optional)})`,untyped:"args"}),t=`self.client.call(${er(e.verb)}, "${$(e.functionPath)}", ${r}, shard_key)`;return e.resultType===void 0?[` /// ${l(e.summary)}`,` pub fn ${O(e.functionName)}(${n}) -> Result<WireValue, ClientError> {`,` ${t}`," }"].join(`
|
|
270
270
|
`):[` /// ${l(e.summary)}`,` pub fn ${O(e.functionName)}(${n}) -> Result<${e.resultType}, ClientError> {`,` let raw = ${t}?;`," let json = encode_wire(&raw).map_err(ClientError::Wire)?;"," serde_json::from_value(json).map_err(|error| ClientError::Transport(error.to_string()))"," }"].join(`
|
|
271
|
-
`)},nr=e=>{const n=p(e,{none:"",typed:t=>`args: &${t}, `,untyped:"args: &WireValue, "}),r=p(e,{none:"WireValue::Object(Vec::new())",typed:()=>`from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Se(e.argsNullPaths.optional)})`,untyped:"args.clone()"});return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` pub fn subscribe_${O(e.functionName)}(`," &mut self,",` ${n}on_data: DataHandler,`," on_error: ErrorHandler,"," shard_key: Option<&str>,"," ) -> Result<String, ClientError> {"
|
|
271
|
+
`)},nr=e=>{const n=p(e,{none:"",typed:t=>`args: &${t}, `,untyped:"args: &WireValue, "}),r=p(e,{none:"WireValue::Object(Vec::new())",typed:()=>`from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Se(e.argsNullPaths.optional)})`,untyped:"args.clone()"});return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` pub fn subscribe_${O(e.functionName)}(`," &mut self,",` ${n}on_data: DataHandler,`," on_error: ErrorHandler,"," shard_key: Option<&str>,"," ) -> Result<String, ClientError> {",` Ok(self.client.subscribe_on_shard("${$(e.functionPath)}", ${r}, on_data, on_error, shard_key))`," }"].join(`
|
|
272
272
|
`)},rr=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${oe(t)}
|
|
273
273
|
|
|
274
274
|
${nr(t)}`:oe(t)).join(`
|
package/dist/packem_shared/{buildOpenApiDocument-ClEtrbbS.mjs → buildOpenApiDocument-Dk1RRaq3.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-B6siM7LU.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
|
|
2
2
|
`,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
|
|
@@ -15,7 +15,7 @@ import{agentComponent as ot}from"@lunora/agent/component";import{LunoraError as
|
|
|
15
15
|
/**
|
|
16
16
|
* R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
|
|
17
17
|
*/
|
|
18
|
-
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],gn=at,fn=new Map(gn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),
|
|
18
|
+
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],gn=at,fn=new Map(gn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Wr=at.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),st=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,bn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),it=e=>e.column!==void 0,yn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
|
|
19
19
|
`;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
|
|
20
20
|
`;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
|
|
21
21
|
`;case"null":return`if (${t} !== null) return DEFER;
|
|
@@ -46,7 +46,7 @@ ${r.pre}return { ${r.entries} };
|
|
|
46
46
|
${t}
|
|
47
47
|
`:"";return`export interface Insert_${e.name} {
|
|
48
48
|
_id?: Id<"${e.name}">;
|
|
49
|
-
_creationTime?: number;${n}}`},Ue="schema",
|
|
49
|
+
_creationTime?: number;${n}}`},Ue="schema",Ur=e=>{for(const u of e.tables)g(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,w])=>{const v=_(x);if(w.kind==="optional"){const I=w.inner?N(w.inner):"unknown";return` ${v}?: ${I};`}return` ${v}: ${N(w)};`}).join(`
|
|
50
50
|
`),f=l?`
|
|
51
51
|
${l}
|
|
52
52
|
`:"";return`export interface Doc_${u.name} {
|
|
@@ -220,7 +220,7 @@ ${r}
|
|
|
220
220
|
export const httpStreams: HttpStreamsRef = {
|
|
221
221
|
${o}
|
|
222
222
|
};
|
|
223
|
-
`,body:r}},
|
|
223
|
+
`,body:r}},Kr=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=ne(s),c=[...n.filter($=>$.visibility!=="internal"),...Un(t,n),...Kn(o,n)],d=n.filter($=>$.visibility==="internal"),p=nt(c),h=nt(d),b=Qn(r),u=`${p}
|
|
224
224
|
${h}
|
|
225
225
|
${b.body}`,l=Ke(u),f=l.length>0?`
|
|
226
226
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
@@ -239,7 +239,7 @@ export const internal = anyApi as unknown as InternalApiTypes;
|
|
|
239
239
|
${v.block}${b.block}`,P=[...I.includes("FunctionReference<")?["FunctionReference"]:[],...b.block===""?[]:["HttpStreamRef"]],C=P.length>0?`import type { ${P.join(", ")} } from "${a.client}";
|
|
240
240
|
`:"";return ht(`${R}import { anyApi } from "${a.client}";
|
|
241
241
|
${C}${v.importLine}${f}
|
|
242
|
-
${I}`,s)},
|
|
242
|
+
${I}`,s)},Qr=e=>e?`${R}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
243
243
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
244
244
|
|
|
245
245
|
import schema from "../schema.js";
|
|
@@ -256,7 +256,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
256
256
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
257
257
|
*/
|
|
258
258
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
259
|
-
`:"",
|
|
259
|
+
`:"",Vr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ne(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{g(c.exportName,"shape export name");const d=o(c),p=E(ke(c.args),c.filePath),h=Object.keys(c.args).length>0,b=h?` args: ${p};`:` args?: ${p};`,u=h?`(args: ${p}) => void`:`(args?: ${p}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
|
|
260
260
|
export interface ${qe(l)} {
|
|
261
261
|
${b}
|
|
262
262
|
/**
|
|
@@ -310,7 +310,7 @@ import type { Collection } from "@tanstack/db";
|
|
|
310
310
|
import { createCollection } from "@tanstack/db";
|
|
311
311
|
${a}
|
|
312
312
|
${s}
|
|
313
|
-
`},
|
|
313
|
+
`},Vn=(e,t)=>`lunora_${S(e)}_${String(t)}`,Hn=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
314
314
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
315
315
|
|
|
316
316
|
if (!registered) {
|
|
@@ -318,7 +318,7 @@ ${s}
|
|
|
318
318
|
}
|
|
319
319
|
|
|
320
320
|
return (await registered.handler(context, args ?? {})) as R;
|
|
321
|
-
};`,
|
|
321
|
+
};`,Jn=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,Vn(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,f])=>{if(!Rn.test(l))throw new te("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${f} from "../${l}.js";`}).join(`
|
|
322
322
|
`),a=e.map(l=>` "${S(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
323
323
|
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
324
324
|
`),d=n.map(l=>` "${S(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
@@ -333,7 +333,7 @@ ${b}
|
|
|
333
333
|
${c}
|
|
334
334
|
`:"",mutatorPaths:h,shapeBody:p.length>0?`
|
|
335
335
|
${p}
|
|
336
|
-
`:""}},
|
|
336
|
+
`:""}},Gn=e=>{const t=Qe(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=E(ke(a.args),a.filePath),d=c==="{}"?"?":"",p=E(a.returnType,a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
|
|
337
337
|
`);return` ${_(S(o))}: {
|
|
338
338
|
${i}
|
|
339
339
|
};`}).join(`
|
|
@@ -341,7 +341,7 @@ ${i}
|
|
|
341
341
|
`);return` ${_(i)}: {
|
|
342
342
|
${a}
|
|
343
343
|
},`}).join(`
|
|
344
|
-
`),types:n}},zn=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=re(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},
|
|
344
|
+
`),types:n}},zn=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=re(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},Hr=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:s=!1,hasBrowser:i=!1,hasFlags:a=!1,hasHyperdrive:c=!1,hasImages:d=!1,hasKv:p=!1,hasNotify:h=!1,hasPayments:b=!1,hasPipelines:u=!1,hasR2sql:l=!1,hasX402:f=!1,identity:x,queues:w=[],schema:v,storageRuleBuckets:I=[],useUmbrella:P=!1,workflows:C=[]}={})=>{const $=ne(P),k=zn(v??{tables:[]},I).map(m=>JSON.stringify(m)).join(" | "),M=o?`import type { LunoraAi } from "@lunora/ai";
|
|
345
345
|
`:"",oe=o?`
|
|
346
346
|
readonly ai: LunoraAi;`:"",B=b?`import type { LunoraPayment } from "@lunora/payment";
|
|
347
347
|
`:"",ae=b?`
|
|
@@ -374,9 +374,9 @@ ${O}`:""}
|
|
|
374
374
|
}
|
|
375
375
|
|
|
376
376
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
377
|
-
export type Env = CloudflareBindings;`,j=(m,Me)=>Me?fn.get(m)?.field??"":"",ie=j("kv",p),le=j("analytics",s),Se=j("hyperdrive",c),Ne=j("browser",i),Te=j("images",d),ce=j("pipelines",u),
|
|
377
|
+
export type Env = CloudflareBindings;`,j=(m,Me)=>Me?fn.get(m)?.field??"":"",ie=j("kv",p),le=j("analytics",s),Se=j("hyperdrive",c),Ne=j("browser",i),Te=j("images",d),ce=j("pipelines",u),V=j("r2sql",l),F=(v?.vectorIndexes.length??0)>0,H=F?' | "vectors"':"",Z=F?`
|
|
378
378
|
readonly vectors: VectorSearch<VectorIndexName>;`:"",de=F?`
|
|
379
|
-
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",
|
|
379
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=F?`import type { VectorSearch, VectorSearchReader } from "${$.server}";
|
|
380
380
|
import type { VectorIndexName } from "./dataModel.js";
|
|
381
381
|
`:"",U=r?`
|
|
382
382
|
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
@@ -491,7 +491,7 @@ export type {
|
|
|
491
491
|
} from "${$.serverDataModel}";
|
|
492
492
|
|
|
493
493
|
import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
494
|
-
${
|
|
494
|
+
${J}${M}${B}${se}${A}${ee}${Oe}${Ce}${_e}${Fe}
|
|
495
495
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
496
496
|
|
|
497
497
|
/**
|
|
@@ -614,22 +614,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
|
|
|
614
614
|
*/
|
|
615
615
|
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
616
616
|
|
|
617
|
-
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${
|
|
617
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${H}${me}${ge}> {
|
|
618
618
|
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
619
619
|
readonly orm: OrmReader;
|
|
620
620
|
readonly storage: ReadOnlyStorage<StorageBucketName>;${de}${U}${ie}${K}${Q}${le}${fe}${he}
|
|
621
621
|
}
|
|
622
622
|
|
|
623
|
-
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${
|
|
623
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${H}${xe}${me}${ge}> {
|
|
624
624
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
625
625
|
readonly orm: OrmWriter;
|
|
626
626
|
readonly storage: ReadOnlyStorage<StorageBucketName>;${Z}${U}${ie}${K}${Q}${le}${fe}${we}${ve}${$e}${he}
|
|
627
627
|
}
|
|
628
628
|
|
|
629
|
-
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${
|
|
629
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${H}${xe}${me}${ge}> {
|
|
630
630
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
631
631
|
readonly orm: OrmWriter;
|
|
632
|
-
readonly storage: StorageBase<StorageBucketName>;${Z}${U}${oe}${ae}${W}${X}${ie}${K}${Q}${Se}${Ne}${Te}${le}${ce}${
|
|
632
|
+
readonly storage: StorageBase<StorageBucketName>;${Z}${U}${oe}${ae}${W}${X}${ie}${K}${Q}${Se}${Ne}${Te}${le}${ce}${V}${fe}${we}${ve}${$e}${he}
|
|
633
633
|
}
|
|
634
634
|
|
|
635
635
|
/**
|
|
@@ -704,7 +704,7 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${De}>();
|
|
|
704
704
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
705
705
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
706
706
|
};
|
|
707
|
-
`},Yn=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${S(n.filePath)}:${n.exportName}`);return t},
|
|
707
|
+
`},Yn=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${S(n.filePath)}:${n.exportName}`);return t},Jr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=ne(i),{dispatchBody:p,importBlock:h,installBlock:b,migrationBody:u,mutatorPaths:l,shapeBody:f}=Jn(n,r,o,s),x=qn(t,n),w=Wn(a,n),v=[x.lines,w.lines].filter(L=>L.length>0).join(`
|
|
708
708
|
`);let I=p;v.length>0&&(I=p.length>0?`${p.trimEnd()}
|
|
709
709
|
${v}
|
|
710
710
|
`:`
|
|
@@ -733,12 +733,12 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(L=>JSO
|
|
|
733
733
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
734
734
|
*/
|
|
735
735
|
${b}
|
|
736
|
-
`:"",B=
|
|
736
|
+
`:"",B=Gn(n),ae=B.types?`
|
|
737
737
|
${B.types}
|
|
738
738
|
`:"",se=B.implementation?`
|
|
739
739
|
${B.implementation}
|
|
740
740
|
`:"",W=Ke(B.types),A=W.length>0?`import type { ${W.join(", ")} } from "./dataModel.js";
|
|
741
|
-
`:"",X=c?"context":"_context",O=c?`${
|
|
741
|
+
`:"",X=c?"context":"_context",O=c?`${Hn}
|
|
742
742
|
|
|
743
743
|
`:"";return ht(`${R}${h}${x.importLine}${w.importLine}${M}${C}import { LunoraError } from "${d.server}";
|
|
744
744
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
@@ -836,7 +836,7 @@ export interface RegisteredDataMigration {
|
|
|
836
836
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
837
837
|
*/
|
|
838
838
|
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
|
|
839
|
-
`,i)},Xn=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=re(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},Zn=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))re(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},er=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(o=>({fields:[...o.fields],name:o.name,type:"index",...o.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(o=>({fields:[o.field,...o.filterFields??[]],name:o.name,type:"search"})),...(n.geoIndexes??[]).map(o=>({fields:[o.field],name:o.name,type:"geo"})),...n.rankIndexes.map(o=>({fields:o.sortBy.map(s=>s.field),name:o.name,type:"rank"})),...n.vectorIndexes.map(o=>({fields:o.field===void 0?[]:[o.field],name:o.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},tr=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},nr=e=>{const t=
|
|
839
|
+
`,i)},Xn=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=re(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},Zn=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))re(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},er=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(o=>({fields:[...o.fields],name:o.name,type:"index",...o.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(o=>({fields:[o.field,...o.filterFields??[]],name:o.name,type:"search"})),...(n.geoIndexes??[]).map(o=>({fields:[o.field],name:o.name,type:"geo"})),...n.rankIndexes.map(o=>({fields:o.sortBy.map(s=>s.field),name:o.name,type:"rank"})),...n.vectorIndexes.map(o=>({fields:o.field===void 0?[]:[o.field],name:o.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},tr=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},nr=e=>{if(e.kind!=="union"||e.members===void 0||e.members.length===0)return;const t=[];for(const n of e.members){if(n.kind!=="literal"||n.literalValue===void 0)return;try{const r=JSON.parse(n.literalValue);if(typeof r!="string")return;t.push(r)}catch{return}}return t},rr=(e,t)=>{const n=re(t),r={name:e,optional:ut(t),type:n.kind};n.kind==="id"&&n.tableName!==void 0&&(r.ref=n.tableName),n.kind==="storage"&&(r.isStorage=!0,n.bucket!==void 0&&(r.bucket=n.bucket));const o=nr(n);return o!==void 0&&(r.enumValues=o),n.column?.notNull===!1&&(r.nullable=!0),r},or=e=>{const t={};for(const n of e.tables){const r=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"}];for(const[o,s]of Object.entries(n.shape))r.push(rr(o,s));t[n.name]=r}return t},ar=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
840
840
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
841
841
|
this.ensureMigrated();
|
|
842
842
|
|
|
@@ -844,7 +844,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}}
|
|
|
844
844
|
|
|
845
845
|
return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
|
|
846
846
|
}
|
|
847
|
-
`}:{importFragment:"",override:""},
|
|
847
|
+
`}:{importFragment:"",override:""},sr=e=>{if(!e)return{build:"",configField:"",contextField:"",stub:""};const t='throw new Error("ctx.ai: no AI binding found. Add an \\`ai\\` binding (env.AI) to wrangler.jsonc, or pass \\`ai\\` to createShardDO().");';return{build:`
|
|
848
848
|
const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
|
|
849
849
|
// Correlate AI-Gateway-routed calls with the Lunora trace: thread the
|
|
850
850
|
// function path + trace id into createAi, which folds them into the
|
|
@@ -882,12 +882,12 @@ const aiStub: LunoraAi = {
|
|
|
882
882
|
const ${e} = {
|
|
883
883
|
${s}
|
|
884
884
|
}${r};
|
|
885
|
-
`},D={build:"",configField:"",contextField:"",importLines:[],stub:""},
|
|
885
|
+
`},D={build:"",configField:"",contextField:"",importLines:[],stub:""},ir=e=>e?{build:`
|
|
886
886
|
const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
|
|
887
887
|
const kv: Kv = kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub;
|
|
888
888
|
`,configField:`
|
|
889
889
|
kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
|
|
890
|
-
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:T("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:D,
|
|
890
|
+
kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:T("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:D,lr=(e,t)=>e?{build:`
|
|
891
891
|
const flags: import("${t}").LunoraFlags = createFlags({
|
|
892
892
|
hooks: flagsConfig.hooks,
|
|
893
893
|
logger: flagsConfig.logger,
|
|
@@ -896,17 +896,17 @@ ${s}
|
|
|
896
896
|
});
|
|
897
897
|
`,configField:`
|
|
898
898
|
flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
|
|
899
|
-
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,
|
|
899
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,cr=e=>e?{build:`
|
|
900
900
|
const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
|
|
901
901
|
`,configField:"",contextField:`
|
|
902
902
|
notify,
|
|
903
|
-
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,
|
|
903
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,dr=e=>e?{build:`
|
|
904
904
|
const envConfig = lunoraEnvContract.${e.exportName}(env);
|
|
905
905
|
`,configField:"",contextField:`
|
|
906
|
-
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,
|
|
906
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,ur=e=>e?{build:`
|
|
907
907
|
const access = accessFacade(identity, userId);
|
|
908
908
|
`,configField:"",contextField:`
|
|
909
|
-
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,
|
|
909
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,pr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=a=>`
|
|
910
910
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
911
911
|
const flags: import("${n}").LunoraFlags = createFlags({
|
|
912
912
|
hooks: flagsConfig.hooks,
|
|
@@ -970,25 +970,25 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
970
970
|
|
|
971
971
|
return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
|
|
972
972
|
}
|
|
973
|
-
`;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},
|
|
973
|
+
`;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},mr=e=>e?{build:`
|
|
974
974
|
const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
|
|
975
975
|
const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
|
|
976
976
|
`,configField:`
|
|
977
977
|
analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
|
|
978
|
-
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:T("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:D,
|
|
978
|
+
analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:T("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:D,hr=e=>e?{build:`
|
|
979
979
|
const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
|
|
980
980
|
const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
|
|
981
981
|
`,configField:`
|
|
982
982
|
images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
|
|
983
|
-
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:T("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:D,
|
|
983
|
+
images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:T("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:D,gr=e=>e?{build:`
|
|
984
984
|
const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
|
|
985
985
|
`,configField:`
|
|
986
986
|
sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
|
|
987
|
-
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:T("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:D,
|
|
987
|
+
sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:T("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:D,fr=e=>e?{build:`
|
|
988
988
|
const browser: Browser = config.browser ? config.browser(env) : browserStub;
|
|
989
989
|
`,configField:`
|
|
990
990
|
browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
|
|
991
|
-
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:T("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:D,
|
|
991
|
+
browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:T("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:D,br=e=>e?{build:`
|
|
992
992
|
const r2sqlEnv = env as Record<string, unknown>;
|
|
993
993
|
const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
|
|
994
994
|
const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
|
|
@@ -999,11 +999,11 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
999
999
|
? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
|
|
1000
1000
|
: r2sqlStub;
|
|
1001
1001
|
`,configField:`
|
|
1002
|
-
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:T("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:D,
|
|
1002
|
+
r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:T("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:D,yr=e=>e?{build:`
|
|
1003
1003
|
const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
|
|
1004
1004
|
const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
|
|
1005
1005
|
`,configField:`
|
|
1006
|
-
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:T("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:D,
|
|
1006
|
+
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:T("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:D,Gr=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(g(s.exportName,`container export "${s.exportName}"`),g(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
|
|
1007
1007
|
export class ${s.className} extends LunoraContainer {
|
|
1008
1008
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1009
1009
|
super(ctx, env, ${s.exportName}, "${s.exportName}"${n});
|
|
@@ -1028,7 +1028,7 @@ import { ${o} } from "../containers.js";
|
|
|
1028
1028
|
|
|
1029
1029
|
export { ContainerProxy } from "@lunora/container/do";
|
|
1030
1030
|
|
|
1031
|
-
${r}`},
|
|
1031
|
+
${r}`},kr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)g(r.exportName,`container export "${r.exportName}"`),g(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
|
|
1032
1032
|
`);return{build:`
|
|
1033
1033
|
const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
|
|
1034
1034
|
`,contextField:`
|
|
@@ -1037,7 +1037,7 @@ ${r}`},br=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1037
1037
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1038
1038
|
${n}
|
|
1039
1039
|
];
|
|
1040
|
-
`}},
|
|
1040
|
+
`}},zr=e=>{if(e.length===0)return"";const t=e.map(r=>(g(r.exportName,`workflow export "${r.exportName}"`),g(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
|
|
1041
1041
|
export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
|
|
1042
1042
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1043
1043
|
super(ctx, env, ${r.exportName}, "${r.exportName}");
|
|
@@ -1065,7 +1065,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
1065
1065
|
/** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
|
|
1066
1066
|
type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
|
|
1067
1067
|
|
|
1068
|
-
${t}`},
|
|
1068
|
+
${t}`},Yr=e=>{if(e.length===0)return"";const n=e.filter(a=>a.voice).length>0,r=e.map(a=>{g(a.exportName,`agent export "${a.exportName}"`),g(a.className,`agent class "${a.className}"`);const c=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
|
|
1069
1069
|
export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1070
1070
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1071
1071
|
super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
|
|
@@ -1093,7 +1093,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
|
1093
1093
|
|
|
1094
1094
|
import { ${o} } from "../agents.js";
|
|
1095
1095
|
|
|
1096
|
-
${r}`},
|
|
1096
|
+
${r}`},Xr=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)g(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
|
|
1097
1097
|
`);return`${R}/**
|
|
1098
1098
|
* Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
|
|
1099
1099
|
* composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
|
|
@@ -1108,7 +1108,7 @@ import { ${n} } from "../queues.js";
|
|
|
1108
1108
|
export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
|
|
1109
1109
|
${r}
|
|
1110
1110
|
};
|
|
1111
|
-
`},
|
|
1111
|
+
`},xr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`workflow export "${n.exportName}"`),g(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
|
|
1112
1112
|
`);return{build:`
|
|
1113
1113
|
const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
|
|
1114
1114
|
`,contextField:`
|
|
@@ -1117,7 +1117,7 @@ ${r}
|
|
|
1117
1117
|
const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
|
|
1118
1118
|
${t}
|
|
1119
1119
|
];
|
|
1120
|
-
`}},
|
|
1120
|
+
`}},wr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`queue export "${n.exportName}"`),g(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
|
|
1121
1121
|
`);return{build:`
|
|
1122
1122
|
const queues = createQueueContext(env, LUNORA_QUEUES);
|
|
1123
1123
|
`,contextField:`
|
|
@@ -1126,7 +1126,7 @@ ${t}
|
|
|
1126
1126
|
const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
|
|
1127
1127
|
${t}
|
|
1128
1128
|
];
|
|
1129
|
-
`}},
|
|
1129
|
+
`}},vr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)g(n.exportName,`agent export "${n.exportName}"`),g(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
|
|
1130
1130
|
`);return{build:`
|
|
1131
1131
|
const agents = createAgentContext(env, LUNORA_AGENTS);
|
|
1132
1132
|
`,contextField:`
|
|
@@ -1142,21 +1142,21 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
|
1142
1142
|
protected override ${n}(): ${t} {
|
|
1143
1143
|
return ${e};
|
|
1144
1144
|
}
|
|
1145
|
-
`})
|
|
1145
|
+
`}),$r=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return ft("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Rr=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return ft("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Sr=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
|
|
1146
1146
|
const payments: LunoraPayment = config.payment
|
|
1147
1147
|
? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
1148
1148
|
: paymentStub;
|
|
1149
1149
|
`,configField:`
|
|
1150
1150
|
payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
|
|
1151
|
-
payments,`,stub:T("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},
|
|
1151
|
+
payments,`,stub:T("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},Nr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
|
|
1152
1152
|
const x402: X402Pay = config.x402
|
|
1153
1153
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1154
1154
|
: x402Stub;
|
|
1155
1155
|
`,configField:`
|
|
1156
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:T("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},
|
|
1156
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:T("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Tr=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Zr=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:h=!1,hasImages:b=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:x=!1,hasR2sql:w=!1,hasX402:v=!1,maskMetadata:I,mutators:P=[],queues:C=[],rlsMetadata:$,schema:k,schemaSnapshot:M,shapes:oe=[],storageRules:B,studioFeatures:ae,useUmbrella:se=!1,workflows:W=[]})=>{const A=ne(se),X=P.length>0,O=oe.length>0,L=M===void 0?"":mn(M),j=M===void 0?"":`
|
|
1157
1157
|
/** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
|
|
1158
1158
|
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(hn(M))}, json: ${JSON.stringify(L)} };
|
|
1159
|
-
`,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Se,contextField:Ne,stub:Te}=
|
|
1159
|
+
`,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Se,contextField:Ne,stub:Te}=sr(a),ce=ur(i),V=ir(u),F=lr(p,A.flags),H=pr(s,p,A.flags),Z=cr(l),de=dr(o),J=mr(c),U=hr(b),K=gr(h),Q=fr(d),q=br(w),ee=yr(x),{build:Ae,contextField:xe,importLines:we,specs:ue}=wr(C),{build:Oe,contextField:Ie,importLines:ve,specs:pe}=kr(r,k.jurisdiction),{build:Ce,contextField:Le,importLines:$e,specs:_e}=xr(W),{build:Ee,contextField:me,importLines:he,specs:De}=vr(n),{build:Fe,configField:Pe,contextField:ge,imports:fe,stub:He}=Sr(f),{build:m,configField:Me,imports:yt,stub:kt}=Nr(v),xt=e,wt=t,vt=$??{policies:[],roles:[]},$t=I??{columns:[]},Rt=B??{rules:[]},St=ae??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Nt,override:Tt}=$r(W),{constant:At,override:Ot}=Rr(C),G=k.vectorIndexes.length>0,Je=new Set(k.tables.filter(y=>typeof y.shardMode=="object"&&y.shardMode.kind==="shardBy").map(y=>y.name)),Re=k.vectorIndexes.some(y=>Je.has(y.table)),be=k.tables.some(y=>y.shardMode==="global"),Be=k.tables.some(y=>y.shardMode==="global"&&y.globalBackend==="hyperdrive"),Ge=k.tables.some(y=>y.shardMode==="global"&&y.globalBackend!=="hyperdrive"),z=k.tables.some(y=>y.externalSource!==void 0);if(Ge&&Be)throw new te("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const je=k.tables.length>0,It=Xn(k),Ct=er(k),Lt=or(k),_t=Zn(k),ze=tr(k),Ye=Tr(G,W.length>0,C.length>0,p);O&&Ye.push("WhereInput");const Xe=ar(be),Et=O?`
|
|
1160
1160
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
1161
1161
|
const shape = LUNORA_SHAPES[name];
|
|
1162
1162
|
|
|
@@ -1213,21 +1213,21 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1213
1213
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1214
1214
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1215
1215
|
}
|
|
1216
|
-
`:"",Ft=O?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Pt=O?"assertShapeShardable, ":"",ye=[`import type { ${Ye.join(", ")} } from "${A.do}";`,`import { applyCdcChanges, buildReprojectionMigration, ${Pt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${z?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${Re?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Xe.importFragment}ShardDO as ShardDOBase } from "${A.do}";`,...z?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${A.do}";`]:[],O?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${A.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${A.server}";`];je&&ye.push(`import { bindOrm, bindTableFacade } from "${A.server}";`),
|
|
1217
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Bt=
|
|
1216
|
+
`:"",Ft=O?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Pt=O?"assertShapeShardable, ":"",ye=[`import type { ${Ye.join(", ")} } from "${A.do}";`,`import { applyCdcChanges, buildReprojectionMigration, ${Pt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${z?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${Re?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Xe.importFragment}ShardDO as ShardDOBase } from "${A.do}";`,...z?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${A.do}";`]:[],O?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${A.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${A.server}";`];je&&ye.push(`import { bindOrm, bindTableFacade } from "${A.server}";`),G&&ye.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&ye.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ye.push(...ce.importLines,...V.importLines,...F.importLines,...Z.importLines,...de.importLines,...J.importLines,...U.importLines,...K.importLines,...Q.importLines,...q.importLines,...ee.importLines,...ve,...$e,...we,...he,...fe,...yt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...X?["LUNORA_MUTATOR_PATHS"]:[],...O?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Mt=G?`
|
|
1217
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Bt=Ge?`
|
|
1218
1218
|
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",jt=Be?`
|
|
1219
1219
|
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",qt=z?`
|
|
1220
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Wt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Ut='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Kt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Qt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',
|
|
1220
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Wt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Ut='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Kt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Qt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Vt=be?T("globalDbStub: DatabaseWriterLike",Wt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Ht=G?T("vectorsStub: VectorSearchLike",Ut,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Jt=Re?`
|
|
1221
1221
|
const vectorShardKey = this.currentShardKey();
|
|
1222
|
-
`:"",
|
|
1222
|
+
`:"",Gt=Re?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",zt=Re?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${k.vectorIndexes.filter(y=>Je.has(y.table)).map(y=>JSON.stringify(y.name)).join(", ")}] }`:"",Yt=G?`
|
|
1223
1223
|
let vectors: VectorSearchLike;
|
|
1224
1224
|
let onWrite: WriteHook | undefined;
|
|
1225
1225
|
|
|
1226
1226
|
if (config.vectors) {
|
|
1227
1227
|
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1228
|
-
${
|
|
1228
|
+
${Jt}
|
|
1229
1229
|
vectors = createContextVectors(lunora${zt});
|
|
1230
|
-
onWrite = createVectorSyncHook({ ${
|
|
1230
|
+
onWrite = createVectorSyncHook({ ${Gt}schema: schema as unknown as VectorSchemaLike, vectors });
|
|
1231
1231
|
} else {
|
|
1232
1232
|
vectors = vectorsStub;
|
|
1233
1233
|
onWrite = undefined;
|
|
@@ -1242,7 +1242,7 @@ ${Gt}
|
|
|
1242
1242
|
headroom: options.headroom ?? this.transactionHeadroom(),
|
|
1243
1243
|
onIndexUse: this.getCtxDbIndexUseHook(),
|
|
1244
1244
|
onRead: options.onRead ?? this.getCtxDbReadHook(),
|
|
1245
|
-
onReadRange: options.onReadRange,${
|
|
1245
|
+
onReadRange: options.onReadRange,${G?`
|
|
1246
1246
|
onWrite,`:""}
|
|
1247
1247
|
scheduler,
|
|
1248
1248
|
schema: schema as unknown as SchemaLike,
|
|
@@ -1259,7 +1259,7 @@ ${Gt}
|
|
|
1259
1259
|
scheduler,
|
|
1260
1260
|
schema: schema as unknown as SchemaLike,
|
|
1261
1261
|
sql: this.sql as SqlExec,
|
|
1262
|
-
});`,Zt=
|
|
1262
|
+
});`,Zt=G?`
|
|
1263
1263
|
vectors,`:"",en=je?`
|
|
1264
1264
|
orm: bindOrm(facade),`:"",Ze=Be?"config.hyperdriveGlobal":"config.d1",tn=be?` const globalRequest = { bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
|
|
1265
1265
|
const globalDb: DatabaseWriterLike = ${Ze}?.(env, globalRequest) ?? globalDbStub;
|
|
@@ -1457,9 +1457,9 @@ ${z?`
|
|
|
1457
1457
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1458
1458
|
${k.tables.map(y=>` facade[${JSON.stringify(y.name)}] = bindTableFacade(db, ${JSON.stringify(y.name)});`).join(`
|
|
1459
1459
|
`)}
|
|
1460
|
-
`:"",ln=`${ce.build}${
|
|
1460
|
+
`:"",ln=`${ce.build}${V.build}${F.build}${J.build}${de.build}
|
|
1461
1461
|
const secrets = createSecrets(env);
|
|
1462
|
-
`,cn=`${ce.contextField}${
|
|
1462
|
+
`,cn=`${ce.contextField}${V.contextField}${F.contextField}${Z.contextField}${J.contextField}${de.contextField}
|
|
1463
1463
|
secrets,`,dn=Z.build,tt=b||h||d||w||x||v,un=tt?`
|
|
1464
1464
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1465
1465
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
@@ -1484,7 +1484,10 @@ const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringi
|
|
|
1484
1484
|
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Ct,void 0,4)};
|
|
1485
1485
|
|
|
1486
1486
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1487
|
-
const LUNORA_TABLE_COLUMNS: Record<
|
|
1487
|
+
const LUNORA_TABLE_COLUMNS: Record<
|
|
1488
|
+
string,
|
|
1489
|
+
Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }>
|
|
1490
|
+
> = ${JSON.stringify(Lt,void 0,4)};
|
|
1488
1491
|
|
|
1489
1492
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1490
1493
|
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(_t,void 0,4)};
|
|
@@ -1509,16 +1512,16 @@ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Rt,void 0,4)};
|
|
|
1509
1512
|
|
|
1510
1513
|
/** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
|
|
1511
1514
|
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(St,void 0,4)};
|
|
1512
|
-
${j}${
|
|
1515
|
+
${j}${H.constant}${Ft}${Nt}${At}${pe}${_e}${ue}${De}
|
|
1513
1516
|
export interface ShardDOConfig {
|
|
1514
1517
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1515
1518
|
cdc?: boolean;
|
|
1516
1519
|
/** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
|
|
1517
1520
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1518
1521
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1519
|
-
storage?: (env: Record<string, unknown>) => unknown;${Mt}${Se}${
|
|
1522
|
+
storage?: (env: Record<string, unknown>) => unknown;${Mt}${Se}${V.configField}${F.configField}${J.configField}${U.configField}${K.configField}${Q.configField}${q.configField}${ee.configField}${Pe}${Me}${Bt}${jt}${qt}
|
|
1520
1523
|
}
|
|
1521
|
-
${T("schedulerStub",Kt,["cancel","runAfter","runAt"])}${T("storageStub",Qt,["delete","download","getMetadata","getSignedUrl","getUrl","list","upload"],{sync:["getUrl"]})}${
|
|
1524
|
+
${T("schedulerStub",Kt,["cancel","runAfter","runAt"])}${T("storageStub",Qt,["delete","download","getMetadata","getSignedUrl","getUrl","list","upload"],{sync:["getUrl"]})}${Vt}${rn}${Ht}${Te}${V.stub}${F.stub}${J.stub}${U.stub}${K.stub}${Q.stub}${q.stub}${ee.stub}${He}${kt}
|
|
1522
1525
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1523
1526
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1524
1527
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1666,7 +1669,9 @@ ${Dt}${Et}${nn}${on}
|
|
|
1666
1669
|
return LUNORA_TTL_SWEEPS;
|
|
1667
1670
|
}
|
|
1668
1671
|
|
|
1669
|
-
protected override tableColumns(
|
|
1672
|
+
protected override tableColumns(
|
|
1673
|
+
table: string,
|
|
1674
|
+
): Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }> {
|
|
1670
1675
|
return LUNORA_TABLE_COLUMNS[table] ?? [];
|
|
1671
1676
|
}
|
|
1672
1677
|
|
|
@@ -1689,7 +1694,7 @@ ${Dt}${Et}${nn}${on}
|
|
|
1689
1694
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1690
1695
|
return LUNORA_STUDIO_FEATURES;
|
|
1691
1696
|
}
|
|
1692
|
-
${
|
|
1697
|
+
${H.evaluateOverride}${H.subscriptionOverride}${Tt}${Ot}
|
|
1693
1698
|
protected override advisories(): AdvisoryFinding[] {
|
|
1694
1699
|
return LUNORA_ADVISORIES;
|
|
1695
1700
|
}
|
|
@@ -2000,21 +2005,21 @@ ${pn}${un}
|
|
|
2000
2005
|
return ctx;
|
|
2001
2006
|
}
|
|
2002
2007
|
};
|
|
2003
|
-
`},
|
|
2008
|
+
`},Ve=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:N(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:N(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Ve(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},bt=(e,t)=>{const n=re(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Ar=(e,t,n)=>{g(e,"drizzle column name");const r=Ve(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=bt(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},Or=e=>{g(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(g(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},Ir=(e,t)=>{g(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${Ar(o,s,t)},`)].join(`
|
|
2004
2009
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2005
|
-
${e.indexes.map(o=>
|
|
2010
|
+
${e.indexes.map(o=>Or(o)).join(`
|
|
2006
2011
|
`)}
|
|
2007
2012
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2008
2013
|
${n}
|
|
2009
|
-
}${r});`},
|
|
2010
|
-
`;const n=ne(t),r=new Set(e.map(h=>h.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=
|
|
2014
|
+
}${r});`},Cr=e=>e.typeAnnotation?.includes('Id<"')??!1,Lr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Ve(a);n.add(c.builder),s=s||Cr(c),o=o||bt(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},rt=(e,t=!1)=>{if(e.length===0)return`${R}export {};
|
|
2015
|
+
`;const n=ne(t),r=new Set(e.map(h=>h.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=Lr(e,r),c=[...s,...o].toSorted((h,b)=>h.localeCompare(b)),d=e.map(h=>Ir(h,r)).join(`
|
|
2011
2016
|
|
|
2012
2017
|
`),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2013
2018
|
`:"",a?`import type { Id } from "./dataModel.js";
|
|
2014
2019
|
`:""].join("");return`${R}import { ${c.join(", ")} } from "${n.serverDrizzle}";
|
|
2015
2020
|
${p}
|
|
2016
2021
|
${d}
|
|
2017
|
-
`},
|
|
2022
|
+
`},eo=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:E(rt(n,t),Ue),shard:E(rt(r,t),Ue)}},to=e=>{const t=new Map;for(const i of e){const a=t.get(i.cron);a?a.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
|
|
2018
2023
|
`),r=n.length>0?`
|
|
2019
2024
|
${n}
|
|
2020
2025
|
`:"",o=[...t.entries()].map(([i,a])=>{const c=a.map(d=>{const p=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${p}, args: ${JSON.stringify(d.args)} },`}).join(`
|
|
@@ -2048,7 +2053,7 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
|
|
|
2048
2053
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2049
2054
|
*/
|
|
2050
2055
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
|
|
2051
|
-
`},
|
|
2056
|
+
`},no=e=>{const t=[...e].toSorted((r,o)=>r.name.localeCompare(o.name)).map(r=>{const o=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&o.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&o.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&o.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&o.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${o.join(", ")} },`}).join(`
|
|
2052
2057
|
`),n=t.length>0?`
|
|
2053
2058
|
${t}
|
|
2054
2059
|
`:"";return`${R}/**
|
|
@@ -2072,4 +2077,4 @@ export interface LunoraVectorIndex {
|
|
|
2072
2077
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2073
2078
|
*/
|
|
2074
2079
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2075
|
-
`},
|
|
2080
|
+
`},ro=e=>[...new Set(e.map(t=>t.cron))];export{Wr as A,gn as C,R as G,En as U,Kr as a,Vr as b,Gr as c,to as d,Yr as e,Ur as f,eo as g,Jr as h,Hr as i,Zr as j,no as k,zr as l,ro as m,Zn as n,Xr as o,Qr as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as S,G as D}from"./emit-
|
|
1
|
+
import{A as S,G as D}from"./emit-B6siM7LU.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),g=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(l),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},I=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. */
|
|
2
2
|
interface StorageDeclaration<Env> {
|
|
3
3
|
/** The default R2 bucket binding (the bare \`ctx.storage\`). */
|
|
4
4
|
bucket: Selector<Env, R2BucketLike>;
|