@lunora/codegen 1.0.0-alpha.321 → 1.0.0-alpha.322
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +21 -3
- package/dist/index.d.ts +21 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-DksDPUdg.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BW62y2zs.mjs +11 -0
- package/dist/packem_shared/capabilitiesUsedBy-D3pvpeAt.mjs +1 -0
- package/dist/packem_shared/{emitApp-K6otnCNZ.mjs → emitApp-DphNN43J.mjs} +9 -9
- package/dist/packem_shared/{emitShard-C1aUZPCr.mjs → emitShard-BF--3qQv.mjs} +1 -1
- package/dist/packem_shared/{shard-CtYnaXAX.mjs → shard-ceGu_Fps.mjs} +79 -73
- package/package.json +9 -9
- package/dist/packem_shared/DEFAULT_TARGET-B0FkdiZq.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-B6NxV9VM.mjs +0 -11
- package/dist/packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs +0 -1
|
@@ -405,7 +405,7 @@ const buildGlobalCdcApplier =
|
|
|
405
405
|
this.storageDeclaration = declaration;
|
|
406
406
|
|
|
407
407
|
return this;
|
|
408
|
-
}`]:[],...T(e)],
|
|
408
|
+
}`]:[],...T(e)],q=e=>{const r=a=>e.hasScheduler?`
|
|
409
409
|
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),"," ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
410
410
|
? {
|
|
411
411
|
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
|
|
@@ -488,7 +488,7 @@ const buildGlobalCdcApplier =
|
|
|
488
488
|
: {}),`]:[],...d(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...g(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
|
|
489
489
|
${t.join(`
|
|
490
490
|
`)}
|
|
491
|
-
`:""},
|
|
491
|
+
`:""},I=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],L=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],j=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],B=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],P=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],G=e=>e?['import notifyConfig from "../notify.js";']:[],_=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],W=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],M=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:o}=e,i=o?"lunorash/runtime":"@lunora/runtime",c=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...s?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],l=[...t||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...c].toSorted((n,h)=>n.localeCompare(h)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},H=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:o,hasQueue:i,hasScheduler:c,hasStorage:l,hasWorkflow:n,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...L(r,t),...P(a),...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...j(o),...B(e.hasVectors),...c?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...n?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],..._(e),...M(e),"",...I(e.identity),...W(e),...a||s?['import schema from "../schema.js";']:[],...G(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...e.wantsArchitecture?['import { architecture } from "./architecture.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},$=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
|
|
492
492
|
// The schema's jurisdiction pins the auth object like every other DO.
|
|
493
493
|
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",U=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,F=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
|
|
494
494
|
${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${U(r.shardMode)}],`).join(`
|
|
@@ -748,10 +748,10 @@ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${U(r.shardMode)}],`)
|
|
|
748
748
|
}`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
749
749
|
${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
750
750
|
`)}
|
|
751
|
-
};`]:[]],z=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture,"]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[
|
|
751
|
+
};`]:[]],z=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture,"]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[` queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],J=e=>e?`
|
|
752
752
|
/** The identity memo per \`env\` object, owned by one assembled worker. */
|
|
753
753
|
type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
|
|
754
|
-
`:"",K=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),Z=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,
|
|
754
|
+
`:"",K=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),Z=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,s=C(t),o=Q(t),i=a?` let auth: LunoraAuth | null = null;
|
|
755
755
|
let authInit: Promise<void> | null = null;
|
|
756
756
|
// One memo per env for THIS assembled worker: a framework-hosted worker rebuilds its options per
|
|
757
757
|
// request and must reuse it, but a second \`assemble()\` has its own auth closure and must not share.
|
|
@@ -809,8 +809,8 @@ type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
|
|
|
809
809
|
throw error;
|
|
810
810
|
}));
|
|
811
811
|
`:"",l=a?`
|
|
812
|
-
await ensureAuth(env);`:"",
|
|
813
|
-
host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${
|
|
812
|
+
await ensureAuth(env);`:"",n=a?"() => auth, identityMemos":"() => null",h=a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null",u=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
813
|
+
host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${n})) : createWorker(this.buildWorkerOptions(env, ${n}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${n}));`,y=t.hasFramework?"host?: FrameworkHostHandler":"",p=t.emailAgents??[],f=p.length>0?` composed.email = dispatchAgentEmail([
|
|
814
814
|
${p.map(b=>` { agent: lunoraAgentDefinitions.${b.exportName}, className: ${JSON.stringify(b.className)} },`).join(`
|
|
815
815
|
`)}
|
|
816
816
|
]);
|
|
@@ -832,9 +832,9 @@ ${J(a)}${t.jurisdiction?`
|
|
|
832
832
|
// \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
|
|
833
833
|
declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
|
|
834
834
|
`:""}
|
|
835
|
-
${
|
|
835
|
+
${s.join(`
|
|
836
836
|
|
|
837
|
-
`)}${
|
|
837
|
+
`)}${s.length>0?`
|
|
838
838
|
|
|
839
839
|
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
840
840
|
interface ComposedApp extends LunoraWorker {
|
|
@@ -864,7 +864,7 @@ ${w}
|
|
|
864
864
|
|
|
865
865
|
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
866
866
|
private assemble(${y}): ComposedApp {
|
|
867
|
-
const ShardDO = createShardDO({${
|
|
867
|
+
const ShardDO = createShardDO({${q(t)}});
|
|
868
868
|
|
|
869
869
|
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
870
870
|
// build, so the first request constructs them and every later request on
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-ceGu_Fps.mjs";import"./shard-runtime-BpoCV-aM.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as Nt}from"@lunora/errors";import{serializeSchemaSnapshot as Mt,hashSchemaSnapshot as $t}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as qt,isD1GlobalTable as Ft}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Ut}from"./json-data-Chfs2Cz5.mjs";import{r as I,e as Bt,a as jt,b as Wt,c as Ht,d as Vt,f as Kt,g as Gt,h as Qt,i as Jt,j as zt,k as Yt,l as Xt,m as Zt,n as er,o as tr,p as rr,q as nr}from"./shard-runtime-BpoCV-aM.mjs";import{u as J,i as ar,G as sr,d as or}from"./shared-DnCokNcE.mjs";import{p as ir}from"./platform-8oj7iXQy.mjs";import{i as dr}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,oe=["categories","description","facing","level","remediation","title"],cr=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(oe.filter(s=>s in a).map(s=>[s,a[s]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([s,d])=>!oe.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},lr=` /**
|
|
2
2
|
* The bare writer every admin/maintenance entry point writes through.
|
|
3
3
|
*
|
|
4
4
|
* Admin and maintenance writes go through the SAME reactive-cache hooks as a
|
|
@@ -30,7 +30,7 @@ import{LunoraError as It}from"@lunora/errors";import{serializeSchemaSnapshot as
|
|
|
30
30
|
schema: schema as unknown as SchemaLike,
|
|
31
31
|
sql: this.sql as SqlExec,
|
|
32
32
|
});
|
|
33
|
-
}`,g=(n="")=>` const writer = this.adminWriter(${n});`,
|
|
33
|
+
}`,g=(n="")=>` const writer = this.adminWriter(${n});`,ur=`${lr}
|
|
34
34
|
|
|
35
35
|
protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
|
|
36
36
|
this.ensureMigrated();
|
|
@@ -225,13 +225,13 @@ ${g()}
|
|
|
225
225
|
await applyCdcChanges(writer, args.changes);
|
|
226
226
|
|
|
227
227
|
return { applied: args.changes.length };
|
|
228
|
-
}`,
|
|
229
|
-
orm: databaseContext.orm,`,
|
|
230
|
-
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,
|
|
228
|
+
}`,hr=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:f,everyContextField:v,facadeBlock:c,globalDatabaseLine:l,lazyFunctions:p=!1,notifyBuild:O,ormContextField:R,paymentsBuild:P,paymentsContextField:k,queuesBuild:N,queuesContextField:i,topicsBuild:b,topicsContextField:M,vectorsBuild:$,vectorsContextField:q,workflowsBuild:D,workflowsContextField:F})=>{const T=e.length>0,x=R===""?"{ db }":"{ db, orm: bindOrm(facade) }",u=R===""?"":`
|
|
229
|
+
orm: databaseContext.orm,`,C=R===""?"":`
|
|
230
|
+
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,w=T?`
|
|
231
231
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
232
232
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
233
233
|
if (isAction) {
|
|
234
|
-
${n.replaceAll(/^(?=.)/gmu," ")}${e.map(
|
|
234
|
+
${n.replaceAll(/^(?=.)/gmu," ")}${e.map(S=>` ctx.${S} = ${S};`).join(`
|
|
235
235
|
`)}
|
|
236
236
|
}
|
|
237
237
|
`:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark | undefined; functionPath?: string | undefined; headroom?: TransactionHeadroomTracker | undefined; identity?: SubscriptionIdentity | undefined; kind?: "query" | undefined; onRead?: ((table: string, idOrScan?: string) => void) | undefined; onReadRange?: ((range: KeyRange) => void) | undefined; scope?: QueryReadScope | undefined; trusted?: boolean | undefined } = {}): unknown {
|
|
@@ -261,7 +261,7 @@ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(R=>` ctx.${R} = ${R};`
|
|
|
261
261
|
};
|
|
262
262
|
})();
|
|
263
263
|
const { identity, ip, userId } = caller;
|
|
264
|
-
${
|
|
264
|
+
${$}${f}${r}${D}${N}${b}${t}
|
|
265
265
|
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
266
266
|
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
267
267
|
// admin/lifecycle path has no registered function, and so no kind. An
|
|
@@ -376,11 +376,11 @@ ${l} // \`ctx.db\`, wrapped in automatic instrumentation: by default
|
|
|
376
376
|
// mutation must rebuild its DB and table/ORM views with its own queue.
|
|
377
377
|
const makeDatabaseContext = (scheduler: SchedulerLike) => {
|
|
378
378
|
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
|
|
379
|
-
${c} return ${
|
|
379
|
+
${c} return ${x};
|
|
380
380
|
};
|
|
381
381
|
const databaseContext = makeDatabaseContext(scheduler);
|
|
382
382
|
const db = databaseContext.db;
|
|
383
|
-
${
|
|
383
|
+
${P}
|
|
384
384
|
|
|
385
385
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
386
386
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -388,7 +388,7 @@ ${k}
|
|
|
388
388
|
// writing mutation's trace from the shared per-request field.
|
|
389
389
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
390
390
|
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
391
|
-
${
|
|
391
|
+
${O}
|
|
392
392
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
393
393
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
394
394
|
// A \`query\` handler is re-run by every live subscription that reads it,
|
|
@@ -439,14 +439,14 @@ ${L}
|
|
|
439
439
|
// to the handler so code that signs its own URLs (a copy-in
|
|
440
440
|
// \`createStorage\`) can fall back to it too. \`undefined\` for a
|
|
441
441
|
// query and for a deferred dispatch, for the reasons given there.
|
|
442
|
-
origin: requestOrigin,${
|
|
442
|
+
origin: requestOrigin,${u}
|
|
443
443
|
scheduler,
|
|
444
444
|
span,
|
|
445
445
|
storage: contextStorage,
|
|
446
|
-
trace,${
|
|
446
|
+
trace,${q}${v}${k}${s}${F}${i}${M}${a}
|
|
447
447
|
};
|
|
448
|
-
${
|
|
449
|
-
`:""}${
|
|
448
|
+
${T?` const isAction = contextKind === "action";
|
|
449
|
+
`:""}${w}
|
|
450
450
|
${p?` const captureScope = (): (() => void) => {
|
|
451
451
|
const requestScope = this.captureRequestScope();
|
|
452
452
|
return () => this.restoreRequestScope(requestScope);
|
|
@@ -469,7 +469,7 @@ ${p?` const captureScope = (): (() => void) => {
|
|
|
469
469
|
|
|
470
470
|
return Object.defineProperties({}, {
|
|
471
471
|
...Object.getOwnPropertyDescriptors(target),
|
|
472
|
-
db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${
|
|
472
|
+
db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${C}
|
|
473
473
|
scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
|
|
474
474
|
storage: { configurable: true, enumerable: true, value: withDeferredDeletes(storage), writable: true },
|
|
475
475
|
});
|
|
@@ -526,7 +526,7 @@ ${p?` const captureScope = (): (() => void) => {
|
|
|
526
526
|
|
|
527
527
|
if (queryView === undefined) {
|
|
528
528
|
const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
|
|
529
|
-
${e.map(
|
|
529
|
+
${e.map(S=>` delete descriptors.${S};
|
|
530
530
|
`).join("")} // Writable and configurable, like the plain fields they replace.
|
|
531
531
|
const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
|
|
532
532
|
|
|
@@ -611,7 +611,7 @@ const dispatchRun = async (
|
|
|
611
611
|
} finally {
|
|
612
612
|
runDepth -= 1;
|
|
613
613
|
}
|
|
614
|
-
};`,
|
|
614
|
+
};`,pr=n=>n?ie.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
|
|
615
615
|
captureScope?: () => () => void,`).replace(` try {
|
|
616
616
|
// A mutation composed from an action`,` try {
|
|
617
617
|
let loaded = getLoadedFunction(functionPath);
|
|
@@ -632,7 +632,7 @@ const dispatchRun = async (
|
|
|
632
632
|
|
|
633
633
|
const loadedFunction = loaded;
|
|
634
634
|
|
|
635
|
-
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ie,
|
|
635
|
+
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ie,mr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
|
|
636
636
|
__PREPARE_FUNCTION__ const registered = LUNORA_FUNCTIONS[functionPath];
|
|
637
637
|
|
|
638
638
|
// Internal functions are reachable server-side only: via \`ctx.run*\`
|
|
@@ -816,7 +816,7 @@ __COMMITTED_CATCH__ } finally {
|
|
|
816
816
|
// \`ctx.scheduler\` call that reached the buffer in the first place.
|
|
817
817
|
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
818
818
|
return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
819
|
-
}`,
|
|
819
|
+
}`,gr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
820
820
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
821
821
|
|
|
822
822
|
if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
|
|
@@ -857,7 +857,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
|
|
|
857
857
|
// \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
|
|
858
858
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
|
|
859
859
|
};
|
|
860
|
-
}`,
|
|
860
|
+
}`,fr=` } catch (error) {
|
|
861
861
|
// The write committed before this failed. Mark the error so the caller can tell
|
|
862
862
|
// a durable write from a rollback: the rethrow still reaches the caller unchanged.
|
|
863
863
|
if (typeof error === "object" && error !== null) {
|
|
@@ -865,7 +865,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
|
|
|
865
865
|
}
|
|
866
866
|
|
|
867
867
|
throw error;
|
|
868
|
-
`,
|
|
868
|
+
`,br=(n,e=!1)=>{const t=e?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
|
|
869
869
|
|
|
870
870
|
if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
|
|
871
871
|
throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
|
|
@@ -882,7 +882,7 @@ __PREPARE_FUNCTION__ this.ensureMigrated();
|
|
|
882
882
|
}
|
|
883
883
|
}
|
|
884
884
|
|
|
885
|
-
`:"";return
|
|
885
|
+
`:"";return mr.replace("__COMMITTED_CATCH__",n?fr:"").replace("__PREPARE_FUNCTION__",`${t}${a}`)},wr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,s]of Object.entries(t.shape)){const d=J(s);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},yr=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,s]of Object.entries(t.shape))J(s).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},vr=n=>{const e={};for(const t of n.tables){const a=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(e[t.name]=a)}return e},kr=n=>{const e=[];for(const t of n.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},Sr=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const e=[];for(const t of n.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const a=JSON.parse(t.literalValue);if(typeof a!="string")return;e.push(a)}catch{return}}return e},Rr=(n,e,t)=>{const a=J(e),r={name:n,optional:ar(e),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=t.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const s=Sr(a);return s!==void 0&&(r.enumValues=s),a.column?.notNull===!1&&(r.nullable=!0),r},xr=n=>{const e={};for(const t of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))a.push(Rr(s,d,r));e[t.name]=a}return e},Ar=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
|
|
886
886
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
887
887
|
const shape = LUNORA_SHAPES[name];
|
|
888
888
|
|
|
@@ -952,7 +952,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
|
|
|
952
952
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
953
953
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
954
954
|
}
|
|
955
|
-
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},
|
|
955
|
+
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},Or=(n,e)=>n?`
|
|
956
956
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
957
957
|
const env = this.env as Record<string, unknown>;
|
|
958
958
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1018,7 +1018,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
|
|
|
1018
1018
|
|
|
1019
1019
|
return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
|
|
1020
1020
|
}
|
|
1021
|
-
`:"",
|
|
1021
|
+
`:"",Dr=n=>({externalSourceOverride:n?`
|
|
1022
1022
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1023
1023
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1024
1024
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1171,7 +1171,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
|
|
|
1171
1171
|
`:"",sourceClientCacheConst:n?`
|
|
1172
1172
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1173
1173
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1174
|
-
`:""}),
|
|
1174
|
+
`:""}),Tr=(n,e)=>{const t=e.length>0,r=n?I("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
|
|
1175
1175
|
`:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",v=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(p=>JSON.stringify(p)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
|
|
1176
1176
|
const vectorSync = this.vectorSync(env);
|
|
1177
1177
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
@@ -1215,14 +1215,14 @@ ${s} const vectors = createContextVectors(lunora${v});
|
|
|
1215
1215
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1216
1216
|
});
|
|
1217
1217
|
}
|
|
1218
|
-
`:"",vectorsBuild:c,vectorsStub:r}},
|
|
1218
|
+
`:"",vectorsBuild:c,vectorsStub:r}},Br=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:f=!1,hasNotify:v=!1,hasRooms:c=!1,lazyFunctions:l=!1,hasVectors:p=!0,liveStreams:O=!1,maskMetadata:R,mutators:P=[],queues:k=[],rlsMetadata:N,schema:i,schemaSnapshot:b,shapes:M=[],storageRules:$,studioFeatures:q,services:D=[],topics:F=[],useUmbrella:T=!1,workflows:x=[]})=>{const u=or(T),C=P.length>0,w=M.length>0,z=b===void 0?"":Mt(b),S=b===void 0?"":`
|
|
1219
1219
|
/** 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. */
|
|
1220
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1221
|
-
`,
|
|
1222
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1223
|
-
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1224
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1225
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1220
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify($t(b))}, json: ${JSON.stringify(z)} };
|
|
1221
|
+
`,de=b===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",y=Bt(a),E=jt(f,u.flags),U=Wt(d,f,u.flags),B=nr(v),j=Ht(s),{build:ce,contextField:le,importLines:ue,specs:he}=Vt(ir(k)),{build:pe,contextField:me,importLines:ge,specs:fe}=Kt(F,k),W=Gt(D,u.server),{build:be,contextField:we,importLines:ye,specs:ve}=Qt(r,i.jurisdiction),{build:ke,contextField:Se,importLines:Re,specs:xe}=Jt(x),{build:Ae,contextField:Oe,importLines:De,specs:Te}=zt(t),{build:Ce,configField:Ee,contextField:_e,imports:Le,stub:Ie}=Yt(a.has("payments")),Pe=n,{advisoryRules:Ne,advisoryRows:Me}=cr(Pe),$e=e,Y=N??{policies:[],roles:[]},qe=R??{columns:[]},Fe=$??{rules:[]},Ue=q??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Be,override:je}=Xt(x),{constant:We,override:He}=Zt(k),m=p&&i.vectorIndexes.length>0,H=new Set(i.tables.filter(o=>dr(o)).map(o=>o.name)),X=m&&i.vectorIndexes.some(o=>H.has(o.table)),A=i.tables.some(o=>o.shardMode==="global"),V=er(H),K=i.tables.some(o=>qt(o)),Z=i.tables.some(o=>Ft(o)),_=i.tables.some(o=>o.externalSource!==void 0),ee=i.tables.some(o=>o.memory===!0),G=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(Z&&K)throw new Nt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Q=i.tables.length>0,Ve=wr(i),Ke=vr(i),Ge=xr(i),Qe=yr(i),te=kr(i),re=tr(m,x.length>0,k.length>0,f,G);w&&re.push("WhereInput");const ne=rr(A),{customMutatorOverride:Je,shapeGuardImport:ze,shapeReadPolicyAssertion:Ye,shapeReadPolicyImport:Xe,shapeResolveOverride:Ze}=Ar({hasMutators:C,hasShapes:w,rlsData:Y}),L=[`import type { ${re.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, createStableIdFactory, ${G?"backfillSearchIndexes, ":""}${m?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ee?"clearMemoryTables, ":""}${ze}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${_?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${X?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ne.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,..._?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],w?`import { asBucketStorage, ${Xe}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];Q&&L.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),m&&L.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),L.push(...y.importLines,...E.importLines,...B.importLines,...j.importLines,...ye,...Re,...ue,...ge,...W.importLines,...De,...Le,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...l?["getLoadedFunction","loadFunction"]:[],...C?["LUNORA_MUTATOR_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...w?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const et=m?`
|
|
1222
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",tt=Z?`
|
|
1223
|
+
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",rt=K?`
|
|
1224
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",nt=_?`
|
|
1225
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",at="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",st="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",ot="ctx.storage: no storage configured. Pass `storage` to createShardDO().",it=A?I("globalDbStub: DatabaseWriterLike",at,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:dt,vectorsBuild:ct,vectorsStub:lt}=Tr(m,X?i.vectorIndexes.filter(o=>H.has(o.table)).map(o=>o.name):[]),ut=`{
|
|
1226
1226
|
...this.ctxDbTuning(),
|
|
1227
1227
|
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1228
1228
|
broadcast: (delta) => {
|
|
@@ -1276,9 +1276,9 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1276
1276
|
sql: this.sql as SqlExec,
|
|
1277
1277
|
storage,${A?`
|
|
1278
1278
|
globalDb,`:""}
|
|
1279
|
-
}`,
|
|
1280
|
-
vectors,`:"",
|
|
1281
|
-
orm: bindOrm(facade),`:"",ae=K?"config.hyperdriveGlobal":"config.d1",
|
|
1279
|
+
}`,ht=m?`
|
|
1280
|
+
vectors,`:"",pt=Q?`
|
|
1281
|
+
orm: bindOrm(facade),`:"",ae=K?"config.hyperdriveGlobal":"config.d1",mt=A?` const bookmark = this.getInboundBookmark();
|
|
1282
1282
|
const globalRequest = {
|
|
1283
1283
|
...this.globalCdcOptions(config.cdc ?? false),
|
|
1284
1284
|
...(bookmark === undefined ? {} : { bookmark }),
|
|
@@ -1287,22 +1287,22 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1287
1287
|
...(userId === undefined ? {} : { userId }),
|
|
1288
1288
|
};
|
|
1289
1289
|
const globalDb: DatabaseWriterLike = ${ae}?.(env, globalRequest) ?? globalDbStub;
|
|
1290
|
-
`:"",
|
|
1290
|
+
`:"",gt=Or(w&&A,ae),ft=c?` protected override roomHandlerPath(topic: string): string | undefined {
|
|
1291
1291
|
// Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
|
|
1292
1292
|
return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
|
|
1293
1293
|
}
|
|
1294
|
-
`:"",{externalSourceOverride:
|
|
1294
|
+
`:"",{externalSourceOverride:bt,sourceBootstrap:wt,sourceClientCacheConst:yt}=Dr(_),vt=`
|
|
1295
1295
|
protected override async runShardInit(): Promise<void> {
|
|
1296
1296
|
this.ensureMigrated();
|
|
1297
1297
|
${ee?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1298
1298
|
`:""}
|
|
1299
1299
|
await this.dispatchShardInit();
|
|
1300
1300
|
}
|
|
1301
|
-
`,
|
|
1301
|
+
`,kt=te.length>0?`
|
|
1302
1302
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1303
1303
|
void this.scheduleTtlSweep();
|
|
1304
1304
|
}
|
|
1305
|
-
`:"",
|
|
1305
|
+
`:"",St=`
|
|
1306
1306
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1307
1307
|
super(state, env, {
|
|
1308
1308
|
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
@@ -1319,7 +1319,7 @@ ${ee?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1319
1319
|
// exists — a trigger that fails first still flushes and fuses.
|
|
1320
1320
|
...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
|
|
1321
1321
|
});
|
|
1322
|
-
${
|
|
1322
|
+
${wt}${kt} }
|
|
1323
1323
|
|
|
1324
1324
|
protected override isCacheableQuery(functionPath: string): boolean {
|
|
1325
1325
|
// NOT \`kind === "query"\` alone. A cache hit answers without running
|
|
@@ -1358,19 +1358,25 @@ ${bt}${vt} }
|
|
|
1358
1358
|
|
|
1359
1359
|
return loadFunction(functionPath).then(() => undefined);
|
|
1360
1360
|
}
|
|
1361
|
-
`:"",
|
|
1361
|
+
`:"",Rt=se===""?`
|
|
1362
1362
|
|
|
1363
1363
|
`:`${se}
|
|
1364
|
-
`,
|
|
1364
|
+
`,xt=pr(l),At=l?` const preparation = this.prepareFunction(functionPath, "subscription");
|
|
1365
1365
|
if (preparation !== undefined) await preparation;
|
|
1366
|
-
`:"",
|
|
1366
|
+
`:"",Ot=gr.replace("__PREPARE_FUNCTION__",At),Dt=br(c,l),Tt=Q?`
|
|
1367
1367
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1368
1368
|
${i.tables.map(o=>` facade[${JSON.stringify(o.name)}] = bindTableFacade(db, ${JSON.stringify(o.name)});`).join(`
|
|
1369
1369
|
`)}
|
|
1370
|
-
`:"",
|
|
1370
|
+
`:"",Ct=`${y.everyBuild}${E.build}${j.build}
|
|
1371
1371
|
const secrets = createSecrets(env);
|
|
1372
|
-
`,
|
|
1373
|
-
secrets,`,
|
|
1372
|
+
`,Et=`${y.everyFields}${E.contextField}${B.contextField}${j.contextField}
|
|
1373
|
+
secrets,`,_t=B.build,Lt=O?`
|
|
1374
|
+
const live = {
|
|
1375
|
+
publish: async (topic: string, payload: unknown, publishOptions: { shardKey?: string; stream: string }): Promise<void> => {
|
|
1376
|
+
await this.publishLiveFromAction(topic, payload, publishOptions);
|
|
1377
|
+
},
|
|
1378
|
+
};
|
|
1379
|
+
`:"",It=[...y.actionFields,...D.length>0?["services"]:[],...O?["live"]:[]],Pt=`${y.actionBuild}${W.build}${Lt}`;return`${sr}${L.join(`
|
|
1374
1380
|
`)}
|
|
1375
1381
|
|
|
1376
1382
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1380,13 +1386,13 @@ interface FunctionReference {
|
|
|
1380
1386
|
}
|
|
1381
1387
|
|
|
1382
1388
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1383
|
-
const LUNORA_TABLE_REFS = ${h(
|
|
1389
|
+
const LUNORA_TABLE_REFS = ${h(Ve,"Record<string, Record<string, string>>")};
|
|
1384
1390
|
|
|
1385
1391
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1386
|
-
const LUNORA_TABLE_INDEXES = ${h(
|
|
1392
|
+
const LUNORA_TABLE_INDEXES = ${h(Ke,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
|
|
1387
1393
|
|
|
1388
1394
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1389
|
-
const LUNORA_TABLE_COLUMNS = ${h(
|
|
1395
|
+
const LUNORA_TABLE_COLUMNS = ${h(Ge,`Record<
|
|
1390
1396
|
string,
|
|
1391
1397
|
Array<{
|
|
1392
1398
|
bucket?: string;
|
|
@@ -1403,16 +1409,16 @@ const LUNORA_TABLE_COLUMNS = ${h(Ke,`Record<
|
|
|
1403
1409
|
>`)};
|
|
1404
1410
|
|
|
1405
1411
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1406
|
-
const LUNORA_STORAGE_COLUMNS = ${h(
|
|
1412
|
+
const LUNORA_STORAGE_COLUMNS = ${h(Qe,"Record<string, string[]>")};
|
|
1407
1413
|
|
|
1408
1414
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1409
|
-
const LUNORA_TTL_SWEEPS = ${
|
|
1415
|
+
const LUNORA_TTL_SWEEPS = ${Ut(te,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1410
1416
|
|
|
1411
1417
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1412
|
-
const LUNORA_ADVISORY_RULES = ${h(
|
|
1418
|
+
const LUNORA_ADVISORY_RULES = ${h(Ne,"Record<string, Partial<AdvisoryFinding>>")};
|
|
1413
1419
|
|
|
1414
1420
|
/** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
|
|
1415
|
-
const LUNORA_ADVISORY_ROWS = ${h(
|
|
1421
|
+
const LUNORA_ADVISORY_ROWS = ${h(Me,"Array<Partial<AdvisoryFinding> & { name: string }>")};
|
|
1416
1422
|
|
|
1417
1423
|
const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
1418
1424
|
let cached: AdvisoryFinding[] | undefined;
|
|
@@ -1420,20 +1426,20 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
|
1420
1426
|
})();
|
|
1421
1427
|
|
|
1422
1428
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1423
|
-
const LUNORA_ADVISOR_PROCEDURES = ${h(
|
|
1429
|
+
const LUNORA_ADVISOR_PROCEDURES = ${h($e,"AdvisorProcedure[]")};
|
|
1424
1430
|
|
|
1425
1431
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1426
1432
|
const LUNORA_RLS_METADATA = ${h(Y,"RlsPoliciesResult")};
|
|
1427
|
-
${
|
|
1433
|
+
${Ye}
|
|
1428
1434
|
/** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
|
|
1429
|
-
const LUNORA_MASK_METADATA = ${h(
|
|
1435
|
+
const LUNORA_MASK_METADATA = ${h(qe,"MaskPoliciesResult")};
|
|
1430
1436
|
|
|
1431
1437
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1432
|
-
const LUNORA_STORAGE_RULES = ${h(
|
|
1438
|
+
const LUNORA_STORAGE_RULES = ${h(Fe,"StorageRulesResult")};
|
|
1433
1439
|
|
|
1434
1440
|
/** 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. */
|
|
1435
|
-
const LUNORA_STUDIO_FEATURES = ${h(
|
|
1436
|
-
${
|
|
1441
|
+
const LUNORA_STUDIO_FEATURES = ${h(Ue,"StudioFeaturesResult")};
|
|
1442
|
+
${S}${V.constant}${U.constant}${Be}${We}${ve}${xe}${he}${fe}${W.specs}${Te}
|
|
1437
1443
|
export interface ShardDOConfig {
|
|
1438
1444
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1439
1445
|
cdc?: boolean;
|
|
@@ -1450,25 +1456,25 @@ export interface ShardDOConfig {
|
|
|
1450
1456
|
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1451
1457
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1452
1458
|
/** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
|
|
1453
|
-
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${
|
|
1459
|
+
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${et}${y.configFields}${E.configField}${Ee}${tt}${rt}${nt}${V.configField}
|
|
1454
1460
|
}
|
|
1455
|
-
${
|
|
1456
|
-
${
|
|
1461
|
+
${I("schedulerStub",st,["cancel","runAfter","runAt"])}${I("storageStub",ot,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${it}${yt}${lt}${y.stubs}${Ie}
|
|
1462
|
+
${xt}
|
|
1457
1463
|
|
|
1458
1464
|
/**
|
|
1459
1465
|
* Build the project's shard Durable Object. Export the result as \`ShardDO\`
|
|
1460
1466
|
* from the worker entry so wrangler binds it by name.
|
|
1461
1467
|
*/
|
|
1462
1468
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1463
|
-
class extends ShardDOBase {${
|
|
1464
|
-
private migrated = false;${
|
|
1469
|
+
class extends ShardDOBase {${St}
|
|
1470
|
+
private migrated = false;${Rt}${Dt}
|
|
1465
1471
|
${ne.override}
|
|
1466
|
-
${
|
|
1467
|
-
${
|
|
1472
|
+
${Ot}
|
|
1473
|
+
${Je}${Ze}${gt}${bt}
|
|
1468
1474
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
1469
1475
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1470
1476
|
}
|
|
1471
|
-
${
|
|
1477
|
+
${ft}${V.override}${vt}
|
|
1472
1478
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1473
1479
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1474
1480
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1567,7 +1573,7 @@ ${l?` const requestScope = this.captureRequestScope();
|
|
|
1567
1573
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1568
1574
|
return LUNORA_STUDIO_FEATURES();
|
|
1569
1575
|
}
|
|
1570
|
-
${U.evaluateOverride}${U.subscriptionOverride}${
|
|
1576
|
+
${U.evaluateOverride}${U.subscriptionOverride}${je}${He}
|
|
1571
1577
|
protected override advisories(): AdvisoryFinding[] {
|
|
1572
1578
|
return LUNORA_ADVISORIES();
|
|
1573
1579
|
}
|
|
@@ -1576,14 +1582,14 @@ ${U.evaluateOverride}${U.subscriptionOverride}${Be}${We}
|
|
|
1576
1582
|
return LUNORA_ADVISOR_PROCEDURES();
|
|
1577
1583
|
}
|
|
1578
1584
|
|
|
1579
|
-
${
|
|
1585
|
+
${ur}
|
|
1580
1586
|
|
|
1581
1587
|
protected override ensureMigrated(): void {
|
|
1582
1588
|
if (this.migrated) {
|
|
1583
1589
|
return;
|
|
1584
1590
|
}
|
|
1585
1591
|
|
|
1586
|
-
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${
|
|
1592
|
+
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${de} });
|
|
1587
1593
|
this.migrated = true;
|
|
1588
1594
|
}
|
|
1589
1595
|
${G?`
|
|
@@ -1595,7 +1601,7 @@ ${G?`
|
|
|
1595
1601
|
|
|
1596
1602
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1597
1603
|
}
|
|
1598
|
-
`:""}${
|
|
1599
|
-
${
|
|
1604
|
+
`:""}${dt}
|
|
1605
|
+
${hr({lazyFunctions:l,actionOnlyFields:It,agentsBuild:Ae,agentsContextField:Oe,containersBuild:be,containersContextField:we,databaseOptions:ut,everyContextBuild:Ct,everyContextField:Et,facadeBlock:Tt,globalDatabaseLine:mt,notifyBuild:_t,ormContextField:pt,paymentsBuild:Ce,paymentsContextField:_e,queuesBuild:ce,queuesContextField:le,topicsBuild:pe,topicsContextField:me,vectorsBuild:ct,vectorsContextField:ht,workflowsBuild:ke,workflowsContextField:Se,actionOnlyBuild:Pt})}
|
|
1600
1606
|
};
|
|
1601
|
-
`};export{
|
|
1607
|
+
`};export{yr as b,Br as e};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.322",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -50,15 +50,15 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
54
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
55
|
-
"@lunora/container": "1.0.0-alpha.
|
|
53
|
+
"@lunora/advisor": "1.0.0-alpha.231",
|
|
54
|
+
"@lunora/agent": "1.0.0-alpha.223",
|
|
55
|
+
"@lunora/container": "1.0.0-alpha.80",
|
|
56
56
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
57
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
58
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
59
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
60
|
-
"@lunora/values": "1.0.0-alpha.
|
|
61
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
57
|
+
"@lunora/platform": "1.0.0-alpha.68",
|
|
58
|
+
"@lunora/queue": "1.0.0-alpha.113",
|
|
59
|
+
"@lunora/scheduler": "1.0.0-alpha.135",
|
|
60
|
+
"@lunora/values": "1.0.0-alpha.70",
|
|
61
|
+
"@lunora/workflow": "1.0.0-alpha.82",
|
|
62
62
|
"@visulima/fs": "6.0.29",
|
|
63
63
|
"jiti": "^2.7.0",
|
|
64
64
|
"quicktype-core": "^26.0.0",
|