@lunora/codegen 1.0.0-alpha.392 → 1.0.0-alpha.394
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 +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-BAEcGpbY.mjs → SCHEMA_SNAPSHOT_FILENAME-B_VaVtUL.mjs} +2 -2
- package/dist/packem_shared/{emitAgents-IN6zekRg.mjs → emitAgents-C-Mfsx39.mjs} +1 -1
- package/dist/packem_shared/{emitApp-Bz0oVnTy.mjs → emitApp-CT3CIMwF.mjs} +26 -26
- package/dist/packem_shared/{emitFunctions-CuhcpWAQ.mjs → emitFunctions-BIMKBLQ8.mjs} +1 -1
- package/dist/packem_shared/{emitShard--7JDasb6.mjs → emitShard-CKsjGAn3.mjs} +1 -1
- package/dist/packem_shared/{shard-CVJYK961.mjs → shard-DXVp_Iht.mjs} +109 -107
- package/dist/packem_shared/{shard-runtime-BfamDqXW.mjs → shard-runtime-BHljpfS5.mjs} +35 -35
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as me}from"@lunora/errors";import{serializeSchemaSnapshot as
|
|
1
|
+
import{LunoraError as me}from"@lunora/errors";import{serializeSchemaSnapshot as tr,hashSchemaSnapshot as rr}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as nr,isD1GlobalTable as ar}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as sr}from"./json-data-Chfs2Cz5.mjs";import{r as U,e as or,a as ir,b as dr,c as cr,d as lr,f as ur,g as hr,h as pr,i as mr,j as fr,k as gr,l as br,m as yr,n as wr,o as vr,p as kr,q as Sr,s as Rr}from"./shard-runtime-BHljpfS5.mjs";import{u as F,h as xr,s as Ar,a as Or,I as Dr,c as Tr,G as _r,d as Er}from"./shared-DhqnD5R3.mjs";import{p as Ir}from"./platform-8oj7iXQy.mjs";import{i as Cr}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,fe=["categories","description","facing","level","remediation","title"],Lr=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(fe.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!fe.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Pr=` /**
|
|
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 me}from"@lunora/errors";import{serializeSchemaSnapshot as
|
|
|
30
30
|
schema: schema as unknown as SchemaLike,
|
|
31
31
|
sql: this.sql as SqlExec,
|
|
32
32
|
});
|
|
33
|
-
}`,
|
|
33
|
+
}`,g=(r="")=>` const writer = this.adminWriter(${r});`,Nr=`${Pr}
|
|
34
34
|
|
|
35
35
|
protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
|
|
36
36
|
this.ensureMigrated();
|
|
@@ -47,7 +47,7 @@ import{LunoraError as me}from"@lunora/errors";import{serializeSchemaSnapshot as
|
|
|
47
47
|
throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
${
|
|
50
|
+
${g()}
|
|
51
51
|
|
|
52
52
|
try {
|
|
53
53
|
return await runDataMigration({
|
|
@@ -86,7 +86,7 @@ ${b()}
|
|
|
86
86
|
|
|
87
87
|
this.ensureMigrated();
|
|
88
88
|
|
|
89
|
-
${
|
|
89
|
+
${g("headroom ?? this.transactionHeadroom()")}
|
|
90
90
|
|
|
91
91
|
if (args.op === "insert") {
|
|
92
92
|
const id = await writer.insert(args.table, args.doc ?? {});
|
|
@@ -141,7 +141,7 @@ ${b("headroom ?? this.transactionHeadroom()")}
|
|
|
141
141
|
protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
|
|
142
142
|
this.ensureMigrated();
|
|
143
143
|
|
|
144
|
-
${
|
|
144
|
+
${g()}
|
|
145
145
|
|
|
146
146
|
const rows: ExportRow[] = [];
|
|
147
147
|
|
|
@@ -161,7 +161,7 @@ ${b()}
|
|
|
161
161
|
this.ensureMigrated();
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
${
|
|
164
|
+
${g()}
|
|
165
165
|
|
|
166
166
|
// \`importShardRows\` inserts with \`allowExplicitId\`, so a source
|
|
167
167
|
// database's \`_id\`s carry across verbatim and every foreign key
|
|
@@ -172,7 +172,7 @@ ${b()}
|
|
|
172
172
|
protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
|
|
173
173
|
this.ensureMigrated();
|
|
174
174
|
|
|
175
|
-
${
|
|
175
|
+
${g()}
|
|
176
176
|
|
|
177
177
|
// \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
178
178
|
// but the shard writer from \`createShardCtxDb\` always defines it.
|
|
@@ -190,7 +190,7 @@ ${b()}
|
|
|
190
190
|
protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
|
|
191
191
|
this.ensureMigrated();
|
|
192
192
|
|
|
193
|
-
${
|
|
193
|
+
${g()}
|
|
194
194
|
|
|
195
195
|
// \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
196
196
|
// but the shard writer from \`createShardCtxDb\` always defines it — it
|
|
@@ -208,7 +208,7 @@ ${b()}
|
|
|
208
208
|
protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
|
|
209
209
|
this.ensureMigrated();
|
|
210
210
|
|
|
211
|
-
${
|
|
211
|
+
${g()}
|
|
212
212
|
|
|
213
213
|
// \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
214
214
|
// but the shard writer from \`createShardCtxDb\` always defines it. The sort
|
|
@@ -229,18 +229,18 @@ ${b()}
|
|
|
229
229
|
protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
|
|
230
230
|
this.ensureMigrated();
|
|
231
231
|
|
|
232
|
-
${
|
|
232
|
+
${g()}
|
|
233
233
|
|
|
234
234
|
await applyCdcChanges(writer, args.changes);
|
|
235
235
|
|
|
236
236
|
return { applied: args.changes.length };
|
|
237
|
-
}
|
|
238
|
-
orm: databaseContext.orm,`,
|
|
239
|
-
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,
|
|
237
|
+
}`,$r=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:a,containersContextField:i,databaseOptions:u,everyContextBuild:h,everyContextField:m,facadeBlock:S,globalDatabaseLine:v,hasSensitiveArgs:R=!1,lazyFunctions:d=!1,notifyBuild:x,ormContextField:A,paymentsBuild:O,paymentsContextField:B,queuesBuild:j,queuesContextField:k,topicsBuild:W,topicsContextField:c,vectorsBuild:b,vectorsContextField:L,workflowsBuild:K,workflowsContextField:H})=>{const D=t.length>0,P=A===""?"{ db }":"{ db, orm: bindOrm(facade) }",V=A===""?"":`
|
|
238
|
+
orm: databaseContext.orm,`,G=A===""?"":`
|
|
239
|
+
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,N=D?`
|
|
240
240
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
241
241
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
242
242
|
if (isAction) {
|
|
243
|
-
${r.replaceAll(/^(?=.)/gmu," ")}${t.map(
|
|
243
|
+
${r.replaceAll(/^(?=.)/gmu," ")}${t.map(y=>` ctx.${y} = ${y};`).join(`
|
|
244
244
|
`)}
|
|
245
245
|
}
|
|
246
246
|
`:"";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; replayKey?: boolean | undefined; scope?: QueryReadScope | undefined; sensitive?: SensitiveScope | undefined; trusted?: boolean | undefined } = {}): unknown {
|
|
@@ -300,7 +300,7 @@ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(l=>` ctx.${l} = ${l};`
|
|
|
300
300
|
|
|
301
301
|
return caller.ip;
|
|
302
302
|
};
|
|
303
|
-
${
|
|
303
|
+
${b}${h}${a}${K}${j}${W}${e}
|
|
304
304
|
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
305
305
|
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
306
306
|
// admin/lifecycle path has no registered function, and so no kind. An
|
|
@@ -311,7 +311,7 @@ ${d}${u}${n}${I}${U}${S}${e}
|
|
|
311
311
|
// reaches through, and pending jobs live in the SchedulerDO — nothing the
|
|
312
312
|
// CDC changelog records — so reading them must forfeit a delta resume.
|
|
313
313
|
// The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
|
|
314
|
-
const schedulerBase = markUnvouchableReads(
|
|
314
|
+
const schedulerBase = markUnvouchableReads(${n}, options.onRead, ["get", "list"]);
|
|
315
315
|
// \`ctx.scheduler.runAfter(0, ...)\` is documented as the deterministic
|
|
316
316
|
// equivalent of an \`afterCommit\` hook, and the SchedulerDO persists the
|
|
317
317
|
// job the moment it is called — so inside a mutation the call is BUFFERED
|
|
@@ -406,7 +406,7 @@ ${d}${u}${n}${I}${U}${S}${e}
|
|
|
406
406
|
// so both write to the same trace.
|
|
407
407
|
const span = this.makeDispatchSpan(traceAnchor, observability, options.sensitive);
|
|
408
408
|
|
|
409
|
-
${
|
|
409
|
+
${v} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
410
410
|
// adds aggregate counters (call count, total time, per-operation
|
|
411
411
|
// breakdown) to the wide event rather than a span per call, so a
|
|
412
412
|
// handler making hundreds of queries stays readable. See
|
|
@@ -414,12 +414,12 @@ ${R} // \`ctx.db\`, wrapped in automatic instrumentation: by default
|
|
|
414
414
|
// Schema triggers close over this DB's scheduler, so a composed
|
|
415
415
|
// mutation must rebuild its DB and table/ORM views with its own queue.
|
|
416
416
|
const makeDatabaseContext = (scheduler: SchedulerLike) => {
|
|
417
|
-
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${
|
|
418
|
-
${
|
|
417
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${u}), logFunctionPath, traceAnchor, observability, options.sensitive);
|
|
418
|
+
${S} return ${P};
|
|
419
419
|
};
|
|
420
420
|
const databaseContext = makeDatabaseContext(scheduler);
|
|
421
421
|
const db = databaseContext.db;
|
|
422
|
-
${
|
|
422
|
+
${O}
|
|
423
423
|
|
|
424
424
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
425
425
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -427,7 +427,7 @@ ${F}
|
|
|
427
427
|
// writing mutation's trace from the shared per-request field.
|
|
428
428
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor, options.sensitive);
|
|
429
429
|
const metrics = this.makeMetrics(logFunctionPath, observability, options.sensitive);
|
|
430
|
-
${
|
|
430
|
+
${x}
|
|
431
431
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
432
432
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
433
433
|
// A \`query\` handler is re-run by every live subscription that reads it,
|
|
@@ -505,16 +505,16 @@ ${c}
|
|
|
505
505
|
// to the handler so code that signs its own URLs (a copy-in
|
|
506
506
|
// \`createStorage\`) can fall back to it too. \`undefined\` for a
|
|
507
507
|
// query and for a deferred dispatch, for the reasons given there.
|
|
508
|
-
origin: requestOrigin,${
|
|
508
|
+
origin: requestOrigin,${V}
|
|
509
509
|
scheduler,
|
|
510
510
|
span,
|
|
511
511
|
storage: contextStorage,
|
|
512
|
-
trace,${
|
|
512
|
+
trace,${L}${m}${B}${i}${H}${k}${c}${o}${R?`
|
|
513
513
|
[Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
|
|
514
514
|
};
|
|
515
|
-
${
|
|
516
|
-
`:""}${
|
|
517
|
-
${
|
|
515
|
+
${D?` const isAction = contextKind === "action";
|
|
516
|
+
`:""}${N}
|
|
517
|
+
${d?` const captureScope = (): (() => void) => {
|
|
518
518
|
const requestScope = this.captureRequestScope();
|
|
519
519
|
return () => this.restoreRequestScope(requestScope);
|
|
520
520
|
};
|
|
@@ -524,7 +524,7 @@ ${f?` const captureScope = (): (() => void) => {
|
|
|
524
524
|
// The callee runs inside this invocation, so its marked arguments are scrubbed here too.
|
|
525
525
|
this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
|
|
526
526
|
|
|
527
|
-
return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${
|
|
527
|
+
return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${d?", undefined, captureScope":""});
|
|
528
528
|
};
|
|
529
529
|
// The composed mutation runs under the SAME wrapper the top-level RPC
|
|
530
530
|
// uses, so "do the transactional work in a mutation and call it from the
|
|
@@ -547,7 +547,7 @@ ${f?` const captureScope = (): (() => void) => {
|
|
|
547
547
|
// refuses network I/O wherever it runs, so its \`fetch\` is overridden here.
|
|
548
548
|
return Object.defineProperties({}, {
|
|
549
549
|
...Object.getOwnPropertyDescriptors(target),
|
|
550
|
-
db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${
|
|
550
|
+
db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${G}
|
|
551
551
|
fetch: { configurable: true, enumerable: true, value: refuseFetch, writable: true },
|
|
552
552
|
random: { configurable: true, enumerable: true, value: mutationRandom, writable: true },
|
|
553
553
|
scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
|
|
@@ -559,7 +559,7 @@ ${f?` const captureScope = (): (() => void) => {
|
|
|
559
559
|
installRun(mutationCtx, kind);
|
|
560
560
|
}
|
|
561
561
|
|
|
562
|
-
return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${
|
|
562
|
+
return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${d?", captureScope":""});
|
|
563
563
|
};
|
|
564
564
|
// \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
|
|
565
565
|
// its OWN query context, built without the subscription's read-footprint
|
|
@@ -584,7 +584,7 @@ ${f?` const captureScope = (): (() => void) => {
|
|
|
584
584
|
runOptions?.untracked === true
|
|
585
585
|
? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope, sensitive: options.sensitive })
|
|
586
586
|
: queryContext(),
|
|
587
|
-
kind,${
|
|
587
|
+
kind,${d?`
|
|
588
588
|
undefined,
|
|
589
589
|
captureScope,`:""}
|
|
590
590
|
);
|
|
@@ -610,7 +610,7 @@ ${f?` const captureScope = (): (() => void) => {
|
|
|
610
610
|
|
|
611
611
|
if (queryView === undefined) {
|
|
612
612
|
const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
|
|
613
|
-
${t.map(
|
|
613
|
+
${t.map(y=>` delete descriptors.${y};
|
|
614
614
|
`).join("")} // Writable and configurable, like the plain fields they replace.
|
|
615
615
|
const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
|
|
616
616
|
|
|
@@ -698,7 +698,7 @@ const dispatchRun = async (
|
|
|
698
698
|
} finally {
|
|
699
699
|
runDepth -= 1;
|
|
700
700
|
}
|
|
701
|
-
};`,
|
|
701
|
+
};`,Mr=r=>r?ge.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
|
|
702
702
|
captureScope?: () => () => void,`).replace(` try {
|
|
703
703
|
// A mutation composed from an action`,` try {
|
|
704
704
|
let loaded = getLoadedFunction(functionPath);
|
|
@@ -719,7 +719,7 @@ const dispatchRun = async (
|
|
|
719
719
|
|
|
720
720
|
const loadedFunction = loaded;
|
|
721
721
|
|
|
722
|
-
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ge
|
|
722
|
+
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ge,qr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
|
|
723
723
|
// A dispatch that did not come through the shard's \`/rpc\` (a scheduled call,
|
|
724
724
|
// a lifecycle hook, an admin run) has no scope of its own, so it opens one here
|
|
725
725
|
// and releases it when the handler settles.
|
|
@@ -932,8 +932,7 @@ __COMMITTED_CATCH__ } finally {
|
|
|
932
932
|
// parked it, and there is nothing to park — an app with no scheduler has no
|
|
933
933
|
// \`ctx.scheduler\` call that reached the buffer in the first place.
|
|
934
934
|
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
935
|
-
|
|
936
|
-
}`,Mr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ identityTracked?: boolean; ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
935
|
+
__OUTBOX_SCHEDULER__ }`,Ur=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ identityTracked?: boolean; ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
937
936
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
938
937
|
|
|
939
938
|
if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
|
|
@@ -981,7 +980,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
981
980
|
return this.windowStreamReads(headroom, (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, headroom, identity }), args, signal));
|
|
982
981
|
},
|
|
983
982
|
};
|
|
984
|
-
}`,
|
|
983
|
+
}`,Fr=` } catch (error) {
|
|
985
984
|
// The write committed before this failed. Mark the error so the caller can tell
|
|
986
985
|
// a durable write from a rollback: the rethrow still reaches the caller unchanged.
|
|
987
986
|
if (typeof error === "object" && error !== null) {
|
|
@@ -989,13 +988,13 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
989
988
|
}
|
|
990
989
|
|
|
991
990
|
throw error;
|
|
992
|
-
`,
|
|
991
|
+
`,Br=(r,t=!1,e=!1)=>{const o=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
|
|
993
992
|
|
|
994
993
|
if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
|
|
995
994
|
throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
|
|
996
995
|
}
|
|
997
996
|
|
|
998
|
-
`:"",
|
|
997
|
+
`:"",n=t?` const requestScope = this.captureRequestScope();
|
|
999
998
|
const preparation = this.prepareFunction(functionPath, "rpc");
|
|
1000
999
|
|
|
1001
1000
|
if (preparation !== undefined) {
|
|
@@ -1006,7 +1005,10 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
1006
1005
|
}
|
|
1007
1006
|
}
|
|
1008
1007
|
|
|
1009
|
-
`:""
|
|
1008
|
+
`:"",a=e?` const configured = config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
1009
|
+
return configured === undefined ? undefined : withAgentScheduleShard(configured, LUNORA_AGENTS, this.currentShardKey());
|
|
1010
|
+
`:` return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
1011
|
+
`;return qr.replace("__COMMITTED_CATCH__",r?Fr:"").replace("__PREPARE_FUNCTION__",`${o}${n}`).replace("__OUTBOX_SCHEDULER__",a)},jr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,a]of Object.entries(e.shape)){const i=F(a);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},Wr=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,a]of Object.entries(e.shape))F(a).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Kr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(a=>a.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},Hr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Vr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Gr=new Set(["bigint","boolean","date","number","timestamp"]),Qr=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=a=>a.kind==="null"||a.kind==="literal"&&a.literalValue==="null",n=F(o(e)?t:e);return o(t)!==o(e)&&Gr.has(n.kind)?n:void 0},zr=(r,t,e)=>{const o=F(t),n=Qr(o),a=n??o,i={name:r,optional:xr(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){i.ref=a.tableName;const h=e.get(r);h!==void 0&&(i.onDelete=h)}a.kind==="storage"&&(i.isStorage=!0,a.bucket!==void 0&&(i.bucket=a.bucket));const u=Vr(a);return u!==void 0&&(i.enumValues=u),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Jr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(a=>a.kind==="one"?[[a.field,a.onDelete]]:[]));for(const[a,i]of Object.entries(e.shape))o.push(zr(a,i,n));t[e.name]=o}return t},Yr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",a=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
|
|
1010
1012
|
const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
|
|
1011
1013
|
|
|
1012
1014
|
try {
|
|
@@ -1081,14 +1083,14 @@ ${a}
|
|
|
1081
1083
|
|
|
1082
1084
|
return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
|
|
1083
1085
|
}
|
|
1084
|
-
`:"",h=e?[...new Set(o.policies.filter(
|
|
1086
|
+
`:"",h=e?[...new Set(o.policies.filter(d=>d.on==="read"&&d.table!=="").map(d=>d.table))].toSorted((d,x)=>d.localeCompare(x)):[],m=h.length>0?`
|
|
1085
1087
|
/** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
|
|
1086
1088
|
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
|
|
1087
1089
|
`:"";return{customMutatorOverride:r?`
|
|
1088
1090
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1089
1091
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1090
1092
|
}
|
|
1091
|
-
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},
|
|
1093
|
+
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},Xr=(r,t)=>r?`
|
|
1092
1094
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1093
1095
|
const env = this.env as Record<string, unknown>;
|
|
1094
1096
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1154,7 +1156,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as
|
|
|
1154
1156
|
|
|
1155
1157
|
return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
|
|
1156
1158
|
}
|
|
1157
|
-
`:"",
|
|
1159
|
+
`:"",Zr=r=>({externalSourceOverride:r?`
|
|
1158
1160
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1159
1161
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1160
1162
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1307,8 +1309,8 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as
|
|
|
1307
1309
|
`:"",sourceClientCacheConst:r?`
|
|
1308
1310
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1309
1311
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1310
|
-
`:""}),
|
|
1311
|
-
`:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",h=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(
|
|
1312
|
+
`:""}),en=(r,t)=>{const e=t.length>0,n=r?U("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",a=e?` const vectorShardKey = this.currentShardKey();
|
|
1313
|
+
`:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",h=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(v=>JSON.stringify(v)).join(", ")}]`]:[]].join(", ")} }`,m=r?`
|
|
1312
1314
|
const vectorSync = this.vectorSync(env);
|
|
1313
1315
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
1314
1316
|
// depends on a similarity search cannot be proven current on reconnect —
|
|
@@ -1351,14 +1353,14 @@ ${a} const vectors = createContextVectors(lunora${h});
|
|
|
1351
1353
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1352
1354
|
});
|
|
1353
1355
|
}
|
|
1354
|
-
`:"",vectorsBuild:m,vectorsStub:n}},
|
|
1356
|
+
`:"",vectorsBuild:m,vectorsStub:n}},bn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:a,flagKeys:i=[],hasFlags:u=!1,hasNotify:h=!1,hasRooms:m=!1,hasSecretValues:S=!1,hasSensitiveArgs:v=!1,hasSockets:R=!1,lazyFunctions:d=!1,hasVectors:x=!0,liveStreamDeclarations:A=[],liveStreams:O=!1,maskMetadata:B,mutators:j=[],queues:k=[],rlsMetadata:W,schema:c,schemaSnapshot:b,shapes:L=[],storageRules:K,studioFeatures:H,hasIpReaders:D=!1,services:P=[],topics:V=[],useUmbrella:G=!1,workflowEvents:N=[],workflows:T=[]})=>{const l=Er(G),y=j.length>0,_=L.length>0,E=L.some(s=>Ar(s.args).length>0),Q=v||E,be=b===void 0?"":tr(b),ye=b===void 0?"":`
|
|
1355
1357
|
/** 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. */
|
|
1356
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1357
|
-
`,we=
|
|
1358
|
-
return { ${
|
|
1358
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(rr(b))}, json: ${JSON.stringify(be)} };
|
|
1359
|
+
`,we=b===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",w=or(o),$=ir(u,l.flags),z=dr(i,u,l.flags),J=Rr(h),Y=cr(a),{build:ve,contextField:ke,importLines:Se,specs:Re}=lr(Ir(k)),{build:xe,contextField:Ae,importLines:Oe,specs:De}=ur(V,k),X=hr(P,l.server),{build:Te,contextField:_e,importLines:Ee,specs:Ie}=pr(n,c.jurisdiction),{build:Ce,contextField:Le,importLines:Pe,specs:Ne}=mr(T),{build:$e,contextField:Me,importLines:qe,schedulerSource:Ue,specs:Fe,stampsOutbox:Be}=fr(e,S&&e.length>0),{build:je,configField:We,contextField:Ke,imports:He,stub:Ve}=gr(o.has("payments")),Ge=r,{advisoryRules:Qe,advisoryRows:ze}=Lr(Ge),Je=t,se=W??{policies:[],roles:[]},Ye=B??{columns:[]},Xe=K??{rules:[]},Ze=H??{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:et,override:tt}=br(T,N),{constant:rt,override:nt}=yr(T,N),{constant:at,override:st}=wr(k),f=x&&c.vectorIndexes.length>0,Z=new Set(c.tables.filter(s=>Cr(s)).map(s=>s.name)),oe=f&&c.vectorIndexes.some(s=>Z.has(s.table)),I=c.tables.some(s=>s.shardMode==="global"),ee=vr(Z),te=c.tables.some(s=>nr(s)),ie=c.tables.some(s=>ar(s)),M=c.tables.some(s=>s.externalSource!==void 0),de=c.tables.some(s=>s.memory===!0),re=c.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ie&&te)throw new me("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const ne=c.tables.length>0,ot=jr(c),it=Kr(c),dt=Jr(c),ct=Wr(c),ce=Hr(c),ae=kr(f,T.length>0,k.length>0,u,re);_&&ae.push("WhereInput"),E&&ae.push("SensitiveScope");const le=Sr(I),{customMutatorOverride:lt,shapeGuardImport:ut,shapeReadPolicyAssertion:ht,shapeReadPolicyImport:pt,shapeResolveOverride:mt}=Yr({hasMutators:y,hasSensitiveShapes:E,hasShapes:_,rlsData:se}),C=O?A:[];for(const s of C)if(Or(s.exportName,"live stream export name"),!Dr.test(s.filePath))throw new me("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ft=d?[]:C.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),gt=` protected override liveStreams() {
|
|
1360
|
+
return { ${C.map(s=>`${Tr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
|
|
1359
1361
|
}
|
|
1360
|
-
`,
|
|
1361
|
-
${
|
|
1362
|
+
`,bt=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
|
|
1363
|
+
${C.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
|
|
1362
1364
|
`)}
|
|
1363
1365
|
]);
|
|
1364
1366
|
|
|
@@ -1379,11 +1381,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1379
1381
|
protected override liveStreams() {
|
|
1380
1382
|
return Object.fromEntries(this.loadedLiveStreams);
|
|
1381
1383
|
}
|
|
1382
|
-
`;let ue="";
|
|
1383
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1384
|
-
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",
|
|
1385
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",
|
|
1386
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1384
|
+
`;let ue="";C.length>0&&(ue=d?bt:gt);const q=[`import type { ${ae.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${re?"backfillSearchIndexes, ":""}${f?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${de?"clearMemoryTables, ":""}${ut}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${M?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${oe?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${le.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...M?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],_?`import { asBucketStorage, ${pt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];ne&&q.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),f&&q.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),q.push(...w.importLines,...$.importLines,...J.importLines,...Y.importLines,...Ee,...Pe,...Se,...Oe,...X.importLines,...qe,...He,...Q?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ft,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...d?["getLoadedFunction","loadFunction"]:[],...y?["LUNORA_MUTATOR_PATHS"]:[],...D?["LUNORA_IP_READER_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...R?["LUNORA_SOCKETS"]:[],..._?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const yt=f?`
|
|
1385
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",wt=ie?`
|
|
1386
|
+
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",vt=te?`
|
|
1387
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",kt=M?`
|
|
1388
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",St="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",Rt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",xt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",At=I?U("globalDbStub: DatabaseWriterLike",St,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:Ot,vectorsBuild:Dt,vectorsStub:Tt}=en(f,oe?c.vectorIndexes.filter(s=>Z.has(s.table)).map(s=>s.name):[]),_t=`{
|
|
1387
1389
|
...this.ctxDbTuning(),
|
|
1388
1390
|
auth: {
|
|
1389
1391
|
get identity() {
|
|
@@ -1430,7 +1432,7 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1430
1432
|
// fallback rather than reporting into a no-op.
|
|
1431
1433
|
...(options.onReadRange !== undefined
|
|
1432
1434
|
? { onReadRange: options.onReadRange }
|
|
1433
|
-
: options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${
|
|
1435
|
+
: options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${f?`
|
|
1434
1436
|
// Vectorize is outside this shard's SQLite and cannot roll back, so
|
|
1435
1437
|
// the sync is held until the mutation's transaction has COMMITTED
|
|
1436
1438
|
// (\`deferAfterCommit\`) instead of running inline. Inline, a write
|
|
@@ -1442,11 +1444,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1442
1444
|
scheduler,
|
|
1443
1445
|
schema: schema as unknown as SchemaLike,
|
|
1444
1446
|
sql: this.sql as SqlExec,
|
|
1445
|
-
storage,${
|
|
1447
|
+
storage,${I?`
|
|
1446
1448
|
globalDb,`:""}
|
|
1447
|
-
}`,
|
|
1448
|
-
vectors,`:"",
|
|
1449
|
-
orm: bindOrm(facade),`:"",he=
|
|
1449
|
+
}`,Et=f?`
|
|
1450
|
+
vectors,`:"",It=ne?`
|
|
1451
|
+
orm: bindOrm(facade),`:"",he=te?"config.hyperdriveGlobal":"config.d1",Ct=I?` const bookmark = this.getInboundBookmark();
|
|
1450
1452
|
const globalRequest = {
|
|
1451
1453
|
...this.globalCdcOptions(config.cdc ?? false),
|
|
1452
1454
|
...(bookmark === undefined ? {} : { bookmark }),
|
|
@@ -1459,14 +1461,14 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1459
1461
|
},
|
|
1460
1462
|
};
|
|
1461
1463
|
const globalDb: DatabaseWriterLike = ${he}?.(env, globalRequest) ?? globalDbStub;
|
|
1462
|
-
`:"",
|
|
1464
|
+
`:"",Lt=Xr(_&&I,he),Pt=m?` protected override roomHandlerPath(topic: string): string | undefined {
|
|
1463
1465
|
// Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
|
|
1464
1466
|
return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
|
|
1465
1467
|
}
|
|
1466
|
-
`:"",
|
|
1468
|
+
`:"",Nt=R?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
|
|
1467
1469
|
return LUNORA_SOCKETS[path];
|
|
1468
1470
|
}
|
|
1469
|
-
`:"",{externalSourceOverride
|
|
1471
|
+
`:"",{externalSourceOverride:$t,sourceBootstrap:Mt,sourceClientCacheConst:qt}=Zr(M),Ut=`
|
|
1470
1472
|
private shardInitDeferred = false;
|
|
1471
1473
|
private deferredShardInit?: Promise<void>;
|
|
1472
1474
|
|
|
@@ -1512,11 +1514,11 @@ ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1512
1514
|
|
|
1513
1515
|
await this.deferredShardInit;
|
|
1514
1516
|
}
|
|
1515
|
-
`,
|
|
1517
|
+
`,Ft=ce.length>0?`
|
|
1516
1518
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1517
1519
|
void this.scheduleTtlSweep();
|
|
1518
1520
|
}
|
|
1519
|
-
`:"",
|
|
1521
|
+
`:"",Bt=`
|
|
1520
1522
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1521
1523
|
super(state, env, {
|
|
1522
1524
|
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
@@ -1533,10 +1535,10 @@ ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1533
1535
|
// exists — a trigger that fails first still flushes and fuses.
|
|
1534
1536
|
...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
|
|
1535
1537
|
});
|
|
1536
|
-
${
|
|
1538
|
+
${D?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
1537
1539
|
this.ipKeyedFunctionPaths.add(path);
|
|
1538
1540
|
}
|
|
1539
|
-
`:""}${
|
|
1541
|
+
`:""}${Mt}${Ft} }
|
|
1540
1542
|
|
|
1541
1543
|
protected override isCacheableQuery(functionPath: string): boolean {
|
|
1542
1544
|
// NOT \`kind === "query"\` alone. A cache hit answers without running
|
|
@@ -1560,7 +1562,7 @@ ${C?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
|
1560
1562
|
protected override isPaidFunction(functionPath: string): boolean {
|
|
1561
1563
|
return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
|
|
1562
1564
|
}
|
|
1563
|
-
`,pe=
|
|
1565
|
+
`,pe=d?`
|
|
1564
1566
|
protected override prepareFunction(functionPath: string, reason: "rpc" | "subscription" | "stream" | "reactor"): Promise<void> | undefined {
|
|
1565
1567
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
1566
1568
|
const allowsInternal = reason === "reactor" || (reason === "rpc" && this.isSystemDispatch());
|
|
@@ -1575,14 +1577,14 @@ ${C?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
|
1575
1577
|
|
|
1576
1578
|
return this.holdShardWhileLoading(() => loadFunction(functionPath));
|
|
1577
1579
|
}
|
|
1578
|
-
`:"",
|
|
1580
|
+
`:"",jt=pe===""?`
|
|
1579
1581
|
|
|
1580
1582
|
`:`${pe}
|
|
1581
|
-
`,
|
|
1583
|
+
`,Wt=Q?`
|
|
1582
1584
|
protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
|
|
1583
|
-
const registered = LUNORA_FUNCTIONS[functionPath];${
|
|
1585
|
+
const registered = LUNORA_FUNCTIONS[functionPath];${E?`
|
|
1584
1586
|
const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
|
|
1585
|
-
const fromValidators = sensitiveArgumentNames(registered?.args ?? ${
|
|
1587
|
+
const fromValidators = sensitiveArgumentNames(registered?.args ?? ${E?"shape?.args ?? ":""}{});
|
|
1586
1588
|
|
|
1587
1589
|
if (registered?.sensitiveArgs === undefined) {
|
|
1588
1590
|
return fromValidators;
|
|
@@ -1591,22 +1593,22 @@ ${C?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
|
1591
1593
|
return new Set([...registered.sensitiveArgs, ...fromValidators]);
|
|
1592
1594
|
}
|
|
1593
1595
|
|
|
1594
|
-
`:"",
|
|
1596
|
+
`:"",Kt=Mr(d),Ht=d?` const preparation = this.prepareFunction(functionPath, "subscription");
|
|
1595
1597
|
if (preparation !== undefined) await preparation;
|
|
1596
|
-
`:"",
|
|
1598
|
+
`:"",Vt=Ur.replace("__PREPARE_FUNCTION__",Ht),Gt=Br(m,d,Be),Qt=ne?`
|
|
1597
1599
|
const facade = db as unknown as Record<string, FacadeEntry>;
|
|
1598
|
-
${
|
|
1600
|
+
${c.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`).join(`
|
|
1599
1601
|
`)}
|
|
1600
|
-
`:"",
|
|
1602
|
+
`:"",zt=`${w.everyBuild}${$.build}${Y.build}
|
|
1601
1603
|
const secrets = createSecrets(env);
|
|
1602
|
-
`,
|
|
1603
|
-
secrets,`,
|
|
1604
|
+
`,Jt=`${w.everyFields}${$.contextField}${J.contextField}${Y.contextField}
|
|
1605
|
+
secrets,`,Yt=J.build,Xt=O?`
|
|
1604
1606
|
const live = {
|
|
1605
1607
|
publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
|
|
1606
1608
|
await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
|
|
1607
1609
|
},
|
|
1608
1610
|
};
|
|
1609
|
-
`:"",
|
|
1611
|
+
`:"",Zt=[...w.actionFields,...P.length>0?["services"]:[],...O?["live"]:[]],er=`${w.actionBuild}${X.build}${Xt}`;return`${_r}${q.join(`
|
|
1610
1612
|
`)}
|
|
1611
1613
|
|
|
1612
1614
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1616,13 +1618,13 @@ interface FunctionReference {
|
|
|
1616
1618
|
}
|
|
1617
1619
|
|
|
1618
1620
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1619
|
-
const LUNORA_TABLE_REFS = ${p(
|
|
1621
|
+
const LUNORA_TABLE_REFS = ${p(ot,"Record<string, Record<string, string>>")};
|
|
1620
1622
|
|
|
1621
1623
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1622
|
-
const LUNORA_TABLE_INDEXES = ${p(
|
|
1624
|
+
const LUNORA_TABLE_INDEXES = ${p(it,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
|
|
1623
1625
|
|
|
1624
1626
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1625
|
-
const LUNORA_TABLE_COLUMNS = ${p(
|
|
1627
|
+
const LUNORA_TABLE_COLUMNS = ${p(dt,`Record<
|
|
1626
1628
|
string,
|
|
1627
1629
|
Array<{
|
|
1628
1630
|
bucket?: string;
|
|
@@ -1639,16 +1641,16 @@ const LUNORA_TABLE_COLUMNS = ${p(ot,`Record<
|
|
|
1639
1641
|
>`)};
|
|
1640
1642
|
|
|
1641
1643
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1642
|
-
const LUNORA_STORAGE_COLUMNS = ${p(
|
|
1644
|
+
const LUNORA_STORAGE_COLUMNS = ${p(ct,"Record<string, string[]>")};
|
|
1643
1645
|
|
|
1644
1646
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1645
|
-
const LUNORA_TTL_SWEEPS = ${
|
|
1647
|
+
const LUNORA_TTL_SWEEPS = ${sr(ce,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1646
1648
|
|
|
1647
1649
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1648
|
-
const LUNORA_ADVISORY_RULES = ${p(
|
|
1650
|
+
const LUNORA_ADVISORY_RULES = ${p(Qe,"Record<string, Partial<AdvisoryFinding>>")};
|
|
1649
1651
|
|
|
1650
1652
|
/** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
|
|
1651
|
-
const LUNORA_ADVISORY_ROWS = ${p(
|
|
1653
|
+
const LUNORA_ADVISORY_ROWS = ${p(ze,"Array<Partial<AdvisoryFinding> & { name: string }>")};
|
|
1652
1654
|
|
|
1653
1655
|
const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
1654
1656
|
let cached: AdvisoryFinding[] | undefined;
|
|
@@ -1656,23 +1658,23 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
|
1656
1658
|
})();
|
|
1657
1659
|
|
|
1658
1660
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1659
|
-
const LUNORA_ADVISOR_PROCEDURES = ${p(
|
|
1661
|
+
const LUNORA_ADVISOR_PROCEDURES = ${p(Je,"AdvisorProcedure[]")};
|
|
1660
1662
|
|
|
1661
1663
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1662
1664
|
const LUNORA_RLS_METADATA = ${p(se,"RlsPoliciesResult")};
|
|
1663
|
-
${
|
|
1665
|
+
${ht}
|
|
1664
1666
|
/** 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. */
|
|
1665
|
-
const LUNORA_MASK_METADATA = ${p(
|
|
1667
|
+
const LUNORA_MASK_METADATA = ${p(Ye,"MaskPoliciesResult")};
|
|
1666
1668
|
|
|
1667
1669
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1668
|
-
const LUNORA_STORAGE_RULES = ${p(
|
|
1670
|
+
const LUNORA_STORAGE_RULES = ${p(Xe,"StorageRulesResult")};
|
|
1669
1671
|
|
|
1670
1672
|
/** 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. */
|
|
1671
|
-
const LUNORA_STUDIO_FEATURES = ${p(
|
|
1673
|
+
const LUNORA_STUDIO_FEATURES = ${p(Ze,"StudioFeaturesResult")};
|
|
1672
1674
|
|
|
1673
1675
|
/** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
|
|
1674
1676
|
const BLOCKED_MIGRATION_RETRY_MS = 5000;
|
|
1675
|
-
${ye}${
|
|
1677
|
+
${ye}${ee.constant}${z.constant}${et}${rt}${at}${Ie}${Ne}${Re}${De}${X.specs}${Fe}
|
|
1676
1678
|
export interface ShardDOConfig {
|
|
1677
1679
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1678
1680
|
cdc?: boolean;
|
|
@@ -1689,9 +1691,9 @@ export interface ShardDOConfig {
|
|
|
1689
1691
|
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1690
1692
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1691
1693
|
/** \`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. */
|
|
1692
|
-
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${
|
|
1694
|
+
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${yt}${w.configFields}${$.configField}${We}${wt}${vt}${kt}${ee.configField}
|
|
1693
1695
|
}
|
|
1694
|
-
${
|
|
1696
|
+
${U("schedulerStub",Rt,["cancel","runAfter","runAt"])}${U("storageStub",xt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${At}${qt}${Tt}${w.stubs}${Ve}
|
|
1695
1697
|
// \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
|
|
1696
1698
|
// mutation may be replayed, so a network call in either returns a different answer
|
|
1697
1699
|
// on each run. Refused at runtime, not only linted: the advisor sees just the call
|
|
@@ -1703,24 +1705,24 @@ const refuseFetch = (): never => {
|
|
|
1703
1705
|
throw new LunoraError("FORBIDDEN", "ctx.fetch is action-only: network I/O belongs in an action, not a query or mutation");
|
|
1704
1706
|
};
|
|
1705
1707
|
|
|
1706
|
-
${
|
|
1708
|
+
${Kt}
|
|
1707
1709
|
|
|
1708
1710
|
/**
|
|
1709
1711
|
* Build the project's shard Durable Object. Export the result as \`ShardDO\`
|
|
1710
1712
|
* from the worker entry so wrangler binds it by name.
|
|
1711
1713
|
*/
|
|
1712
1714
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1713
|
-
class extends ShardDOBase {${
|
|
1715
|
+
class extends ShardDOBase {${Bt}
|
|
1714
1716
|
private blockedUniqueIndexes: readonly string[] = [];
|
|
1715
1717
|
private migrated = false;
|
|
1716
|
-
private migrationRetryAt = 0;${
|
|
1718
|
+
private migrationRetryAt = 0;${jt}${Wt}${Gt}
|
|
1717
1719
|
${le.override}
|
|
1718
|
-
${
|
|
1719
|
-
${
|
|
1720
|
+
${Vt}
|
|
1721
|
+
${lt}${mt}${Lt}${$t}
|
|
1720
1722
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
1721
1723
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1722
1724
|
}
|
|
1723
|
-
${
|
|
1725
|
+
${Pt}${Nt}${ue}${ee.override}${Ut}
|
|
1724
1726
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1725
1727
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1726
1728
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1741,7 +1743,7 @@ ${Ct}${Lt}${ue}${Z.override}${Mt}
|
|
|
1741
1743
|
// would instead run an app's reactor as whichever user happened to write
|
|
1742
1744
|
// last, which is worse than running it as nobody.
|
|
1743
1745
|
protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
|
|
1744
|
-
${
|
|
1746
|
+
${d?` const requestScope = this.captureRequestScope();
|
|
1745
1747
|
const preparation = this.prepareFunction(functionPath, "reactor");
|
|
1746
1748
|
|
|
1747
1749
|
if (preparation !== undefined) {
|
|
@@ -1819,7 +1821,7 @@ ${c?` const requestScope = this.captureRequestScope();
|
|
|
1819
1821
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1820
1822
|
return LUNORA_STUDIO_FEATURES();
|
|
1821
1823
|
}
|
|
1822
|
-
${
|
|
1824
|
+
${z.evaluateOverride}${z.subscriptionOverride}${tt}${nt}${st}
|
|
1823
1825
|
protected override advisories(): AdvisoryFinding[] {
|
|
1824
1826
|
return LUNORA_ADVISORIES();
|
|
1825
1827
|
}
|
|
@@ -1828,7 +1830,7 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${Ze}${tt}${nt}
|
|
|
1828
1830
|
return LUNORA_ADVISOR_PROCEDURES();
|
|
1829
1831
|
}
|
|
1830
1832
|
|
|
1831
|
-
${
|
|
1833
|
+
${Nr}
|
|
1832
1834
|
|
|
1833
1835
|
/**
|
|
1834
1836
|
* Migrate the base schema. A UNIQUE index that existing duplicate rows block
|
|
@@ -1871,7 +1873,7 @@ ${Lr}
|
|
|
1871
1873
|
throw new LunoraError("UNIQUE_INDEX_DUPLICATES", this.blockedUniqueIndexes.join("; "));
|
|
1872
1874
|
}
|
|
1873
1875
|
}
|
|
1874
|
-
${
|
|
1876
|
+
${re?`
|
|
1875
1877
|
protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
|
|
1876
1878
|
// Migrations create the fts5 companions; without them every backfill
|
|
1877
1879
|
// statement would raise "no such table" on a shard that has never
|
|
@@ -1880,7 +1882,7 @@ ${te?`
|
|
|
1880
1882
|
|
|
1881
1883
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1882
1884
|
}
|
|
1883
|
-
`:""}${
|
|
1884
|
-
${
|
|
1885
|
+
`:""}${Ot}
|
|
1886
|
+
${$r({hasSensitiveArgs:Q,lazyFunctions:d,actionOnlyFields:Zt,agentsBuild:$e,agentsContextField:Me,agentsSchedulerSource:Ue,containersBuild:Te,containersContextField:_e,databaseOptions:_t,everyContextBuild:zt,everyContextField:Jt,facadeBlock:Qt,globalDatabaseLine:Ct,notifyBuild:Yt,ormContextField:It,paymentsBuild:je,paymentsContextField:Ke,queuesBuild:ve,queuesContextField:ke,topicsBuild:xe,topicsContextField:Ae,vectorsBuild:Dt,vectorsContextField:Et,workflowsBuild:Ce,workflowsContextField:Le,actionOnlyBuild:er})}
|
|
1885
1887
|
};
|
|
1886
|
-
`};export{
|
|
1888
|
+
`};export{Wr as b,bn as e};
|