@lunora/codegen 1.0.0-alpha.363 → 1.0.0-alpha.365
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 +14 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CVAC4R90.mjs +31 -0
- package/dist/packem_shared/emitAgents-BIvfaobb.mjs +1 -0
- package/dist/packem_shared/{emitApp-CT7iAjam.mjs → emitApp-CFkLyCIO.mjs} +119 -53
- package/dist/packem_shared/{emitShard-DdB1N32N.mjs → emitShard-tyWbUrjj.mjs} +1 -1
- package/dist/packem_shared/{shard-wyX4XRYk.mjs → shard-DOqocTdL.mjs} +130 -126
- package/dist/packem_shared/{shard-runtime-DXlpfT3P.mjs → shard-runtime-Dad_kcaX.mjs} +54 -44
- package/package.json +8 -8
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bmny8aw5.mjs +0 -31
- package/dist/packem_shared/emitAgents-CwwzVPZe.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Xt,hashSchemaSnapshot as Zt}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{isHyperdriveGlobalTable as er,isD1GlobalTable as tr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as rr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as nr,a as ar,b as sr,c as or,d as ir,f as dr,g as cr,h as lr,i as ur,j as hr,k as pr,l as mr,m as fr,n as gr,o as br,p as yr,q as wr,s as vr}from"./shard-runtime-Dad_kcaX.mjs";import{u as F,h as kr,s as Sr,a as Rr,I as xr,c as Ar,G as Or,d as Dr}from"./shared-Br_OnErI.mjs";import{p as Tr}from"./platform-8oj7iXQy.mjs";import{i as _r}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Er=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!me.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Ir=` /**
|
|
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 he}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
|
+
}`,b=(r="")=>` const writer = this.adminWriter(${r});`,Cr=`${Ir}
|
|
34
34
|
|
|
35
35
|
protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
|
|
36
36
|
this.ensureMigrated();
|
|
@@ -47,7 +47,7 @@ import{LunoraError as he}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
|
+
${b()}
|
|
51
51
|
|
|
52
52
|
try {
|
|
53
53
|
return await runDataMigration({
|
|
@@ -86,7 +86,7 @@ ${y()}
|
|
|
86
86
|
|
|
87
87
|
this.ensureMigrated();
|
|
88
88
|
|
|
89
|
-
${
|
|
89
|
+
${b("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 @@ ${y("headroom ?? this.transactionHeadroom()")}
|
|
|
141
141
|
protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
|
|
142
142
|
this.ensureMigrated();
|
|
143
143
|
|
|
144
|
-
${
|
|
144
|
+
${b()}
|
|
145
145
|
|
|
146
146
|
const rows: ExportRow[] = [];
|
|
147
147
|
|
|
@@ -161,7 +161,7 @@ ${y()}
|
|
|
161
161
|
this.ensureMigrated();
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
${
|
|
164
|
+
${b()}
|
|
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 @@ ${y()}
|
|
|
172
172
|
protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
|
|
173
173
|
this.ensureMigrated();
|
|
174
174
|
|
|
175
|
-
${
|
|
175
|
+
${b()}
|
|
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 @@ ${y()}
|
|
|
190
190
|
protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
|
|
191
191
|
this.ensureMigrated();
|
|
192
192
|
|
|
193
|
-
${
|
|
193
|
+
${b()}
|
|
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 @@ ${y()}
|
|
|
208
208
|
protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
|
|
209
209
|
this.ensureMigrated();
|
|
210
210
|
|
|
211
|
-
${
|
|
211
|
+
${b()}
|
|
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 @@ ${y()}
|
|
|
229
229
|
protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
|
|
230
230
|
this.ensureMigrated();
|
|
231
231
|
|
|
232
|
-
${
|
|
232
|
+
${b()}
|
|
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
|
+
}`,Lr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,containersBuild:n,containersContextField:a,databaseOptions:i,everyContextBuild:u,everyContextField:h,facadeBlock:m,globalDatabaseLine:x,hasSensitiveArgs:S=!1,lazyFunctions:f=!1,notifyBuild:c,ormContextField:y,paymentsBuild:U,paymentsContextField:A,queuesBuild:B,queuesContextField:j,topicsBuild:R,topicsContextField:W,vectorsBuild:d,vectorsContextField:w,workflowsBuild:I,workflowsContextField:K})=>{const C=t.length>0,L=y===""?"{ db }":"{ db, orm: bindOrm(facade) }",H=y===""?"":`
|
|
238
|
+
orm: databaseContext.orm,`,V=y===""?"":`
|
|
239
|
+
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,P=C?`
|
|
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(v=>` ctx.${v} = ${v};`).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 {
|
|
@@ -270,7 +270,7 @@ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(f=>` ctx.${f} = ${f};`
|
|
|
270
270
|
};
|
|
271
271
|
})();
|
|
272
272
|
const { identity, ip, userId } = caller;
|
|
273
|
-
${d}${
|
|
273
|
+
${d}${u}${n}${I}${B}${R}${e}
|
|
274
274
|
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
275
275
|
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
276
276
|
// admin/lifecycle path has no registered function, and so no kind. An
|
|
@@ -385,11 +385,11 @@ ${x} // \`ctx.db\`, wrapped in automatic instrumentation: by default
|
|
|
385
385
|
// mutation must rebuild its DB and table/ORM views with its own queue.
|
|
386
386
|
const makeDatabaseContext = (scheduler: SchedulerLike) => {
|
|
387
387
|
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${i}), logFunctionPath, traceAnchor, observability, options.sensitive);
|
|
388
|
-
${m} return ${
|
|
388
|
+
${m} return ${L};
|
|
389
389
|
};
|
|
390
390
|
const databaseContext = makeDatabaseContext(scheduler);
|
|
391
391
|
const db = databaseContext.db;
|
|
392
|
-
${
|
|
392
|
+
${U}
|
|
393
393
|
|
|
394
394
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
395
395
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -409,22 +409,14 @@ ${c}
|
|
|
409
409
|
// advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
|
|
410
410
|
const now = Date.now();
|
|
411
411
|
|
|
412
|
-
// \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
|
|
413
|
-
// mutation may be replayed, so a network call in either returns a different answer
|
|
414
|
-
// on each run. Refused at runtime, not only linted: the advisor sees just the call
|
|
415
|
-
// sites it can read, and a call inside a dependency is invisible to it.
|
|
416
|
-
// Synchronous on purpose: an async refusal only rejects a promise the handler may
|
|
417
|
-
// discard, and the handler would then return normally. A sync throw surfaces at the call.
|
|
418
|
-
const refuseFetch = (): never => {
|
|
419
|
-
throw new LunoraError("FORBIDDEN", "ctx.fetch is action-only: network I/O belongs in an action, not a query or mutation");
|
|
420
|
-
};
|
|
421
|
-
|
|
422
412
|
// A reactor run is driven by the writer's inline refresh, not replayed by the writer, so it must not
|
|
423
413
|
// inherit the writer's key: every run would restart the same id and random sequence.
|
|
424
414
|
const stableKey = options.replayKey !== false && options.identity === undefined && this.idempotencyNamespace() !== undefined ? this.getCurrentMutationId() : undefined;
|
|
425
|
-
|
|
415
|
+
// Both factories ignore the scope without a replay key, and most dispatches have none.
|
|
416
|
+
const stableScope = stableKey === undefined ? "" : JSON.stringify([this.currentShardKey(), options.functionPath ?? "", this.idempotencyNamespace() ?? "", userId ?? ""]);
|
|
426
417
|
// One sequence for every mutation this run composes: their ids share one counter (the copied \`newId\`), so their draws must too.
|
|
427
|
-
|
|
418
|
+
// Created on the first composed mutation that gets a ctx of its own; most dispatches compose none.
|
|
419
|
+
let composedRandom: (() => number) | undefined;
|
|
428
420
|
|
|
429
421
|
const ctx: Record<string, unknown> = {
|
|
430
422
|
auth: {
|
|
@@ -466,16 +458,16 @@ ${c}
|
|
|
466
458
|
// to the handler so code that signs its own URLs (a copy-in
|
|
467
459
|
// \`createStorage\`) can fall back to it too. \`undefined\` for a
|
|
468
460
|
// query and for a deferred dispatch, for the reasons given there.
|
|
469
|
-
origin: requestOrigin,${
|
|
461
|
+
origin: requestOrigin,${H}
|
|
470
462
|
scheduler,
|
|
471
463
|
span,
|
|
472
464
|
storage: contextStorage,
|
|
473
|
-
trace,${
|
|
465
|
+
trace,${w}${h}${A}${a}${K}${j}${W}${o}${S?`
|
|
474
466
|
[Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
|
|
475
467
|
};
|
|
476
|
-
${
|
|
477
|
-
`:""}${
|
|
478
|
-
${
|
|
468
|
+
${C?` const isAction = contextKind === "action";
|
|
469
|
+
`:""}${P}
|
|
470
|
+
${f?` const captureScope = (): (() => void) => {
|
|
479
471
|
const requestScope = this.captureRequestScope();
|
|
480
472
|
return () => this.restoreRequestScope(requestScope);
|
|
481
473
|
};
|
|
@@ -485,7 +477,7 @@ ${g?` const captureScope = (): (() => void) => {
|
|
|
485
477
|
// The callee runs inside this invocation, so its marked arguments are scrubbed here too.
|
|
486
478
|
this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
|
|
487
479
|
|
|
488
|
-
return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${
|
|
480
|
+
return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${f?", undefined, captureScope":""});
|
|
489
481
|
};
|
|
490
482
|
// The composed mutation runs under the SAME wrapper the top-level RPC
|
|
491
483
|
// uses, so "do the transactional work in a mutation and call it from the
|
|
@@ -500,16 +492,17 @@ ${g?` const captureScope = (): (() => void) => {
|
|
|
500
492
|
: (() => {
|
|
501
493
|
const mutationScheduler = withDeferredSchedules(schedulerBase, this.scheduleOutbox());
|
|
502
494
|
const mutationDatabase = makeDatabaseContext(mutationScheduler);
|
|
495
|
+
// The composed mutation's ids come from the action's replay key and counter, so its draws do too; a
|
|
496
|
+
// fresh factory per call would repeat the same draws across sibling mutations.
|
|
497
|
+
const mutationRandom = (composedRandom ??= createStableRandomFactory(stableKey, stableScope));
|
|
503
498
|
|
|
504
499
|
// Copied from an action's ctx, which carries the real \`fetch\`; a mutation
|
|
505
500
|
// refuses network I/O wherever it runs, so its \`fetch\` is overridden here.
|
|
506
501
|
return Object.defineProperties({}, {
|
|
507
502
|
...Object.getOwnPropertyDescriptors(target),
|
|
508
|
-
db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${
|
|
503
|
+
db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${V}
|
|
509
504
|
fetch: { configurable: true, enumerable: true, value: refuseFetch, writable: true },
|
|
510
|
-
|
|
511
|
-
// fresh factory per call would repeat the same draws across sibling mutations.
|
|
512
|
-
random: { configurable: true, enumerable: true, value: composedRandom, writable: true },
|
|
505
|
+
random: { configurable: true, enumerable: true, value: mutationRandom, writable: true },
|
|
513
506
|
scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
|
|
514
507
|
storage: { configurable: true, enumerable: true, value: withDeferredDeletes(storage), writable: true },
|
|
515
508
|
});
|
|
@@ -519,7 +512,7 @@ ${g?` const captureScope = (): (() => void) => {
|
|
|
519
512
|
installRun(mutationCtx, kind);
|
|
520
513
|
}
|
|
521
514
|
|
|
522
|
-
return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${
|
|
515
|
+
return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${f?", captureScope":""});
|
|
523
516
|
};
|
|
524
517
|
// \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
|
|
525
518
|
// its OWN query context, built without the subscription's read-footprint
|
|
@@ -544,7 +537,7 @@ ${g?` const captureScope = (): (() => void) => {
|
|
|
544
537
|
runOptions?.untracked === true
|
|
545
538
|
? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope, sensitive: options.sensitive })
|
|
546
539
|
: queryContext(),
|
|
547
|
-
kind,${
|
|
540
|
+
kind,${f?`
|
|
548
541
|
undefined,
|
|
549
542
|
captureScope,`:""}
|
|
550
543
|
);
|
|
@@ -570,7 +563,7 @@ ${g?` const captureScope = (): (() => void) => {
|
|
|
570
563
|
|
|
571
564
|
if (queryView === undefined) {
|
|
572
565
|
const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
|
|
573
|
-
${t.map(
|
|
566
|
+
${t.map(v=>` delete descriptors.${v};
|
|
574
567
|
`).join("")} // Writable and configurable, like the plain fields they replace.
|
|
575
568
|
const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
|
|
576
569
|
|
|
@@ -592,7 +585,7 @@ ${t.map(f=>` delete descriptors.${f};
|
|
|
592
585
|
installRun(ctx, contextKind);
|
|
593
586
|
|
|
594
587
|
return ctx;
|
|
595
|
-
}`},
|
|
588
|
+
}`},fe=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
596
589
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
597
590
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
598
591
|
// single-threaded), so the counter reflects true nesting depth.
|
|
@@ -658,7 +651,7 @@ const dispatchRun = async (
|
|
|
658
651
|
} finally {
|
|
659
652
|
runDepth -= 1;
|
|
660
653
|
}
|
|
661
|
-
};`,
|
|
654
|
+
};`,Pr=r=>r?fe.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
|
|
662
655
|
captureScope?: () => () => void,`).replace(` try {
|
|
663
656
|
// A mutation composed from an action`,` try {
|
|
664
657
|
let loaded = getLoadedFunction(functionPath);
|
|
@@ -679,7 +672,7 @@ const dispatchRun = async (
|
|
|
679
672
|
|
|
680
673
|
const loadedFunction = loaded;
|
|
681
674
|
|
|
682
|
-
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):
|
|
675
|
+
// A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):fe,Nr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
|
|
683
676
|
// A dispatch that did not come through the shard's \`/rpc\` (a scheduled call,
|
|
684
677
|
// a lifecycle hook, an admin run) has no scope of its own, so it opens one here
|
|
685
678
|
// and releases it when the handler settles.
|
|
@@ -883,7 +876,7 @@ __COMMITTED_CATCH__ } finally {
|
|
|
883
876
|
// \`ctx.scheduler\` call that reached the buffer in the first place.
|
|
884
877
|
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
885
878
|
return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
886
|
-
}
|
|
879
|
+
}`,$r=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
887
880
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
888
881
|
|
|
889
882
|
if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
|
|
@@ -924,7 +917,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
924
917
|
// \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
|
|
925
918
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
|
|
926
919
|
};
|
|
927
|
-
}`,
|
|
920
|
+
}`,Mr=` } catch (error) {
|
|
928
921
|
// The write committed before this failed. Mark the error so the caller can tell
|
|
929
922
|
// a durable write from a rollback: the rethrow still reaches the caller unchanged.
|
|
930
923
|
if (typeof error === "object" && error !== null) {
|
|
@@ -932,7 +925,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
932
925
|
}
|
|
933
926
|
|
|
934
927
|
throw error;
|
|
935
|
-
`,
|
|
928
|
+
`,qr=(r,t=!1)=>{const e=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
|
|
936
929
|
|
|
937
930
|
if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
|
|
938
931
|
throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
|
|
@@ -949,7 +942,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
949
942
|
}
|
|
950
943
|
}
|
|
951
944
|
|
|
952
|
-
`:"";return
|
|
945
|
+
`:"";return Nr.replace("__COMMITTED_CATCH__",r?Mr:"").replace("__PREPARE_FUNCTION__",`${e}${o}`)},Fr=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},Ur=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},Br=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},jr=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},Wr=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},Kr=new Set(["bigint","boolean","date","number","timestamp"]),Hr=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)&&Kr.has(n.kind)?n:void 0},Vr=(r,t,e)=>{const o=F(t),n=Hr(o),a=n??o,i={name:r,optional:kr(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=Wr(a);return u!==void 0&&(i.enumValues=u),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Gr=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(Vr(a,i,n));t[e.name]=o}return t},Qr=({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} {
|
|
953
946
|
const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
|
|
954
947
|
|
|
955
948
|
try {
|
|
@@ -961,8 +954,8 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
961
954
|
}
|
|
962
955
|
}
|
|
963
956
|
|
|
964
|
-
private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${n} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {`,
|
|
965
|
-
${
|
|
957
|
+
private resolveShapeWithScope(name: string, args: Record<string, unknown>, identity: SubscriptionIdentity | undefined, sensitive: SensitiveScope): ${n} {`:` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {`,u=e?`
|
|
958
|
+
${a}
|
|
966
959
|
const shape = LUNORA_SHAPES[name];
|
|
967
960
|
|
|
968
961
|
if (!shape) {
|
|
@@ -1024,14 +1017,14 @@ ${s}
|
|
|
1024
1017
|
|
|
1025
1018
|
return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
|
|
1026
1019
|
}
|
|
1027
|
-
`:"",
|
|
1020
|
+
`:"",h=e?[...new Set(o.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,y)=>c.localeCompare(y)):[],m=h.length>0?`
|
|
1028
1021
|
/** 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). */
|
|
1029
|
-
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(
|
|
1022
|
+
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
|
|
1030
1023
|
`:"";return{customMutatorOverride:r?`
|
|
1031
1024
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1032
1025
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1033
1026
|
}
|
|
1034
|
-
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:
|
|
1027
|
+
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},Jr=(r,t)=>r?`
|
|
1035
1028
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1036
1029
|
const env = this.env as Record<string, unknown>;
|
|
1037
1030
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1097,7 +1090,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(u)}, (schema as
|
|
|
1097
1090
|
|
|
1098
1091
|
return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
|
|
1099
1092
|
}
|
|
1100
|
-
`:"",
|
|
1093
|
+
`:"",zr=r=>({externalSourceOverride:r?`
|
|
1101
1094
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1102
1095
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1103
1096
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1250,8 +1243,8 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(u)}, (schema as
|
|
|
1250
1243
|
`:"",sourceClientCacheConst:r?`
|
|
1251
1244
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1252
1245
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1253
|
-
`:""}),
|
|
1254
|
-
`:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",
|
|
1246
|
+
`:""}),Yr=(r,t)=>{const e=t.length>0,n=r?q("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",a=e?` const vectorShardKey = this.currentShardKey();
|
|
1247
|
+
`:"",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(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,m=r?`
|
|
1255
1248
|
const vectorSync = this.vectorSync(env);
|
|
1256
1249
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
1257
1250
|
// depends on a similarity search cannot be proven current on reconnect —
|
|
@@ -1268,7 +1261,7 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1268
1261
|
}
|
|
1269
1262
|
|
|
1270
1263
|
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1271
|
-
${
|
|
1264
|
+
${a} const vectors = createContextVectors(lunora${h});
|
|
1272
1265
|
|
|
1273
1266
|
return {
|
|
1274
1267
|
backfill: createVectorBackfillSync({ ${i}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
|
|
@@ -1294,14 +1287,14 @@ ${s} const vectors = createContextVectors(lunora${u});
|
|
|
1294
1287
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1295
1288
|
});
|
|
1296
1289
|
}
|
|
1297
|
-
`:"",vectorsBuild:m,vectorsStub:n}},
|
|
1290
|
+
`:"",vectorsBuild:m,vectorsStub:n}},pn=({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:x=!1,hasSensitiveArgs:S=!1,hasSockets:f=!1,lazyFunctions:c=!1,hasVectors:y=!0,liveStreamDeclarations:U=[],liveStreams:A=!1,maskMetadata:B,mutators:j=[],queues:R=[],rlsMetadata:W,schema:d,schemaSnapshot:w,shapes:I=[],storageRules:K,studioFeatures:C,services:L=[],topics:H=[],useUmbrella:V=!1,workflowEvents:P=[],workflows:O=[]})=>{const l=Dr(V),v=j.length>0,D=I.length>0,T=I.some(s=>Sr(s.args).length>0),G=S||T,ge=w===void 0?"":Xt(w),be=w===void 0?"":`
|
|
1298
1291
|
/** 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. */
|
|
1299
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1300
|
-
`,
|
|
1301
|
-
return { ${
|
|
1292
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Zt(w))}, json: ${JSON.stringify(ge)} };
|
|
1293
|
+
`,ye=w===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=nr(o),N=ar(u,l.flags),Q=sr(i,u,l.flags),J=vr(h),z=or(a),{build:we,contextField:ve,importLines:ke,specs:Se}=ir(Tr(R)),{build:Re,contextField:xe,importLines:Ae,specs:Oe}=dr(H,R),Y=cr(L,l.server),{build:De,contextField:Te,importLines:_e,specs:Ee}=lr(n,d.jurisdiction),{build:Ie,contextField:Ce,importLines:Le,specs:Pe}=ur(O),{build:Ne,contextField:$e,importLines:Me,specs:qe}=hr(e,x&&e.length>0),{build:Fe,configField:Ue,contextField:Be,imports:je,stub:We}=pr(o.has("payments")),Ke=r,{advisoryRules:He,advisoryRows:Ve}=Er(Ke),Ge=t,ae=W??{policies:[],roles:[]},Qe=B??{columns:[]},Je=K??{rules:[]},ze=C??{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:Ye,override:Xe}=mr(O,P),{constant:Ze,override:et}=fr(O,P),{constant:tt,override:rt}=gr(R),g=y&&d.vectorIndexes.length>0,X=new Set(d.tables.filter(s=>_r(s)).map(s=>s.name)),se=g&&d.vectorIndexes.some(s=>X.has(s.table)),_=d.tables.some(s=>s.shardMode==="global"),Z=br(X),ee=d.tables.some(s=>er(s)),oe=d.tables.some(s=>tr(s)),$=d.tables.some(s=>s.externalSource!==void 0),ie=d.tables.some(s=>s.memory===!0),te=d.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(oe&&ee)throw new pe("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const re=d.tables.length>0,nt=Fr(d),at=Br(d),st=Gr(d),ot=Ur(d),de=jr(d),ne=yr(g,O.length>0,R.length>0,u,te);D&&ne.push("WhereInput"),T&&ne.push("SensitiveScope");const ce=wr(_),{customMutatorOverride:it,shapeGuardImport:dt,shapeReadPolicyAssertion:ct,shapeReadPolicyImport:lt,shapeResolveOverride:ut}=Qr({hasMutators:v,hasSensitiveShapes:T,hasShapes:D,rlsData:ae}),E=A?U:[];for(const s of E)if(Rr(s.exportName,"live stream export name"),!xr.test(s.filePath))throw new pe("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ht=c?[]:E.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),pt=` protected override liveStreams() {
|
|
1294
|
+
return { ${E.map(s=>`${Ar(s.id)}: liveStream_${s.exportName}`).join(", ")} };
|
|
1302
1295
|
}
|
|
1303
|
-
`,
|
|
1304
|
-
${
|
|
1296
|
+
`,mt=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
|
|
1297
|
+
${E.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
|
|
1305
1298
|
`)}
|
|
1306
1299
|
]);
|
|
1307
1300
|
|
|
@@ -1322,11 +1315,11 @@ ${_.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}
|
|
|
1322
1315
|
protected override liveStreams() {
|
|
1323
1316
|
return Object.fromEntries(this.loadedLiveStreams);
|
|
1324
1317
|
}
|
|
1325
|
-
`;let
|
|
1326
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1327
|
-
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;`:"",
|
|
1328
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1329
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1318
|
+
`;let le="";E.length>0&&(le=c?mt:pt);const M=[`import type { ${ne.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${te?"backfillSearchIndexes, ":""}${g?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ie?"clearMemoryTables, ":""}${dt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${$?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ce.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...$?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],D?`import { asBucketStorage, ${lt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];re&&M.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),g&&M.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),M.push(...k.importLines,...N.importLines,...J.importLines,...z.importLines,..._e,...Le,...ke,...Ae,...Y.importLines,...Me,...je,...G?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ht,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...v?["LUNORA_MUTATOR_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...f?["LUNORA_SOCKETS"]:[],...D?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ft=g?`
|
|
1319
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",gt=oe?`
|
|
1320
|
+
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;`:"",bt=ee?`
|
|
1321
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",yt=$?`
|
|
1322
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",wt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",vt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",kt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",St=_?q("globalDbStub: DatabaseWriterLike",wt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:Rt,vectorsBuild:xt,vectorsStub:At}=Yr(g,se?d.vectorIndexes.filter(s=>X.has(s.table)).map(s=>s.name):[]),Ot=`{
|
|
1330
1323
|
...this.ctxDbTuning(),
|
|
1331
1324
|
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1332
1325
|
broadcast: (delta) => {
|
|
@@ -1366,7 +1359,7 @@ ${_.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}
|
|
|
1366
1359
|
// fallback rather than reporting into a no-op.
|
|
1367
1360
|
...(options.onReadRange !== undefined
|
|
1368
1361
|
? { onReadRange: options.onReadRange }
|
|
1369
|
-
: options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${
|
|
1362
|
+
: options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${g?`
|
|
1370
1363
|
// Vectorize is outside this shard's SQLite and cannot roll back, so
|
|
1371
1364
|
// the sync is held until the mutation's transaction has COMMITTED
|
|
1372
1365
|
// (\`deferAfterCommit\`) instead of running inline. Inline, a write
|
|
@@ -1378,11 +1371,11 @@ ${_.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}
|
|
|
1378
1371
|
scheduler,
|
|
1379
1372
|
schema: schema as unknown as SchemaLike,
|
|
1380
1373
|
sql: this.sql as SqlExec,
|
|
1381
|
-
storage,${
|
|
1374
|
+
storage,${_?`
|
|
1382
1375
|
globalDb,`:""}
|
|
1383
|
-
}`,
|
|
1384
|
-
vectors,`:"",
|
|
1385
|
-
orm: bindOrm(facade),`:"",
|
|
1376
|
+
}`,Dt=g?`
|
|
1377
|
+
vectors,`:"",Tt=re?`
|
|
1378
|
+
orm: bindOrm(facade),`:"",ue=ee?"config.hyperdriveGlobal":"config.d1",_t=_?` const bookmark = this.getInboundBookmark();
|
|
1386
1379
|
const globalRequest = {
|
|
1387
1380
|
...this.globalCdcOptions(config.cdc ?? false),
|
|
1388
1381
|
...(bookmark === undefined ? {} : { bookmark }),
|
|
@@ -1390,21 +1383,21 @@ ${_.map(a=>` [${JSON.stringify(a.id)}, () => import("../${a.filePath}
|
|
|
1390
1383
|
onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
|
|
1391
1384
|
...(userId === undefined ? {} : { userId }),
|
|
1392
1385
|
};
|
|
1393
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1394
|
-
`:"",
|
|
1386
|
+
const globalDb: DatabaseWriterLike = ${ue}?.(env, globalRequest) ?? globalDbStub;
|
|
1387
|
+
`:"",Et=Jr(D&&_,ue),It=m?` protected override roomHandlerPath(topic: string): string | undefined {
|
|
1395
1388
|
// Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
|
|
1396
1389
|
return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
|
|
1397
1390
|
}
|
|
1398
|
-
`:"",
|
|
1391
|
+
`:"",Ct=f?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
|
|
1399
1392
|
return LUNORA_SOCKETS[path];
|
|
1400
1393
|
}
|
|
1401
|
-
`:"",{externalSourceOverride:
|
|
1394
|
+
`:"",{externalSourceOverride:Lt,sourceBootstrap:Pt,sourceClientCacheConst:Nt}=zr($),$t=`
|
|
1402
1395
|
private shardInitDeferred = false;
|
|
1403
1396
|
private deferredShardInit?: Promise<void>;
|
|
1404
1397
|
|
|
1405
1398
|
protected override async runShardInit(): Promise<void> {
|
|
1406
1399
|
this.ensureMigrated();
|
|
1407
|
-
${
|
|
1400
|
+
${ie?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1408
1401
|
`:""}
|
|
1409
1402
|
if (this.blockedUniqueIndexes.length > 0) {
|
|
1410
1403
|
this.shardInitDeferred = true;
|
|
@@ -1444,11 +1437,11 @@ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1444
1437
|
|
|
1445
1438
|
await this.deferredShardInit;
|
|
1446
1439
|
}
|
|
1447
|
-
`,
|
|
1440
|
+
`,Mt=de.length>0?`
|
|
1448
1441
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1449
1442
|
void this.scheduleTtlSweep();
|
|
1450
1443
|
}
|
|
1451
|
-
`:"",
|
|
1444
|
+
`:"",qt=`
|
|
1452
1445
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1453
1446
|
super(state, env, {
|
|
1454
1447
|
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
@@ -1465,7 +1458,7 @@ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1465
1458
|
// exists — a trigger that fails first still flushes and fuses.
|
|
1466
1459
|
...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
|
|
1467
1460
|
});
|
|
1468
|
-
${
|
|
1461
|
+
${Pt}${Mt} }
|
|
1469
1462
|
|
|
1470
1463
|
protected override isCacheableQuery(functionPath: string): boolean {
|
|
1471
1464
|
// NOT \`kind === "query"\` alone. A cache hit answers without running
|
|
@@ -1489,7 +1482,7 @@ ${It}${Pt} }
|
|
|
1489
1482
|
protected override isPaidFunction(functionPath: string): boolean {
|
|
1490
1483
|
return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
|
|
1491
1484
|
}
|
|
1492
|
-
`,
|
|
1485
|
+
`,he=c?`
|
|
1493
1486
|
protected override prepareFunction(functionPath: string, reason: "rpc" | "subscription" | "stream" | "reactor"): Promise<void> | undefined {
|
|
1494
1487
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
1495
1488
|
const allowsInternal = reason === "reactor" || (reason === "rpc" && this.isSystemDispatch());
|
|
@@ -1504,14 +1497,14 @@ ${It}${Pt} }
|
|
|
1504
1497
|
|
|
1505
1498
|
return loadFunction(functionPath).then(() => undefined);
|
|
1506
1499
|
}
|
|
1507
|
-
`:""
|
|
1500
|
+
`:"",Ft=he===""?`
|
|
1508
1501
|
|
|
1509
|
-
`:`${
|
|
1510
|
-
`,
|
|
1502
|
+
`:`${he}
|
|
1503
|
+
`,Ut=G?`
|
|
1511
1504
|
protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
|
|
1512
|
-
const registered = LUNORA_FUNCTIONS[functionPath];${
|
|
1505
|
+
const registered = LUNORA_FUNCTIONS[functionPath];${T?`
|
|
1513
1506
|
const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
|
|
1514
|
-
const fromValidators = sensitiveArgumentNames(registered?.args ?? ${
|
|
1507
|
+
const fromValidators = sensitiveArgumentNames(registered?.args ?? ${T?"shape?.args ?? ":""}{});
|
|
1515
1508
|
|
|
1516
1509
|
if (registered?.sensitiveArgs === undefined) {
|
|
1517
1510
|
return fromValidators;
|
|
@@ -1520,22 +1513,22 @@ ${It}${Pt} }
|
|
|
1520
1513
|
return new Set([...registered.sensitiveArgs, ...fromValidators]);
|
|
1521
1514
|
}
|
|
1522
1515
|
|
|
1523
|
-
`:"",
|
|
1516
|
+
`:"",Bt=Pr(c),jt=c?` const preparation = this.prepareFunction(functionPath, "subscription");
|
|
1524
1517
|
if (preparation !== undefined) await preparation;
|
|
1525
|
-
`:"",
|
|
1526
|
-
const facade = db as unknown as Record<string,
|
|
1527
|
-
${d.tables.map(
|
|
1518
|
+
`:"",Wt=$r.replace("__PREPARE_FUNCTION__",jt),Kt=qr(m,c),Ht=re?`
|
|
1519
|
+
const facade = db as unknown as Record<string, FacadeEntry>;
|
|
1520
|
+
${d.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`).join(`
|
|
1528
1521
|
`)}
|
|
1529
|
-
`:"",
|
|
1522
|
+
`:"",Vt=`${k.everyBuild}${N.build}${z.build}
|
|
1530
1523
|
const secrets = createSecrets(env);
|
|
1531
|
-
`,
|
|
1532
|
-
secrets,`,
|
|
1524
|
+
`,Gt=`${k.everyFields}${N.contextField}${J.contextField}${z.contextField}
|
|
1525
|
+
secrets,`,Qt=J.build,Jt=A?`
|
|
1533
1526
|
const live = {
|
|
1534
1527
|
publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
|
|
1535
1528
|
await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
|
|
1536
1529
|
},
|
|
1537
1530
|
};
|
|
1538
|
-
`:"",
|
|
1531
|
+
`:"",zt=[...k.actionFields,...L.length>0?["services"]:[],...A?["live"]:[]],Yt=`${k.actionBuild}${Y.build}${Jt}`;return`${Or}${M.join(`
|
|
1539
1532
|
`)}
|
|
1540
1533
|
|
|
1541
1534
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1545,13 +1538,13 @@ interface FunctionReference {
|
|
|
1545
1538
|
}
|
|
1546
1539
|
|
|
1547
1540
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1548
|
-
const LUNORA_TABLE_REFS = ${p(
|
|
1541
|
+
const LUNORA_TABLE_REFS = ${p(nt,"Record<string, Record<string, string>>")};
|
|
1549
1542
|
|
|
1550
1543
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1551
|
-
const LUNORA_TABLE_INDEXES = ${p(
|
|
1544
|
+
const LUNORA_TABLE_INDEXES = ${p(at,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
|
|
1552
1545
|
|
|
1553
1546
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1554
|
-
const LUNORA_TABLE_COLUMNS = ${p(
|
|
1547
|
+
const LUNORA_TABLE_COLUMNS = ${p(st,`Record<
|
|
1555
1548
|
string,
|
|
1556
1549
|
Array<{
|
|
1557
1550
|
bucket?: string;
|
|
@@ -1568,16 +1561,16 @@ const LUNORA_TABLE_COLUMNS = ${p(rt,`Record<
|
|
|
1568
1561
|
>`)};
|
|
1569
1562
|
|
|
1570
1563
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1571
|
-
const LUNORA_STORAGE_COLUMNS = ${p(
|
|
1564
|
+
const LUNORA_STORAGE_COLUMNS = ${p(ot,"Record<string, string[]>")};
|
|
1572
1565
|
|
|
1573
1566
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1574
|
-
const LUNORA_TTL_SWEEPS = ${
|
|
1567
|
+
const LUNORA_TTL_SWEEPS = ${rr(de,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1575
1568
|
|
|
1576
1569
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1577
|
-
const LUNORA_ADVISORY_RULES = ${p(
|
|
1570
|
+
const LUNORA_ADVISORY_RULES = ${p(He,"Record<string, Partial<AdvisoryFinding>>")};
|
|
1578
1571
|
|
|
1579
1572
|
/** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
|
|
1580
|
-
const LUNORA_ADVISORY_ROWS = ${p(
|
|
1573
|
+
const LUNORA_ADVISORY_ROWS = ${p(Ve,"Array<Partial<AdvisoryFinding> & { name: string }>")};
|
|
1581
1574
|
|
|
1582
1575
|
const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
1583
1576
|
let cached: AdvisoryFinding[] | undefined;
|
|
@@ -1585,23 +1578,23 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
|
|
|
1585
1578
|
})();
|
|
1586
1579
|
|
|
1587
1580
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1588
|
-
const LUNORA_ADVISOR_PROCEDURES = ${p(
|
|
1581
|
+
const LUNORA_ADVISOR_PROCEDURES = ${p(Ge,"AdvisorProcedure[]")};
|
|
1589
1582
|
|
|
1590
1583
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1591
|
-
const LUNORA_RLS_METADATA = ${p(
|
|
1592
|
-
${
|
|
1584
|
+
const LUNORA_RLS_METADATA = ${p(ae,"RlsPoliciesResult")};
|
|
1585
|
+
${ct}
|
|
1593
1586
|
/** 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. */
|
|
1594
|
-
const LUNORA_MASK_METADATA = ${p(
|
|
1587
|
+
const LUNORA_MASK_METADATA = ${p(Qe,"MaskPoliciesResult")};
|
|
1595
1588
|
|
|
1596
1589
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1597
|
-
const LUNORA_STORAGE_RULES = ${p(
|
|
1590
|
+
const LUNORA_STORAGE_RULES = ${p(Je,"StorageRulesResult")};
|
|
1598
1591
|
|
|
1599
1592
|
/** 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. */
|
|
1600
|
-
const LUNORA_STUDIO_FEATURES = ${p(
|
|
1593
|
+
const LUNORA_STUDIO_FEATURES = ${p(ze,"StudioFeaturesResult")};
|
|
1601
1594
|
|
|
1602
1595
|
/** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
|
|
1603
1596
|
const BLOCKED_MIGRATION_RETRY_MS = 5000;
|
|
1604
|
-
${
|
|
1597
|
+
${be}${Z.constant}${Q.constant}${Ye}${Ze}${tt}${Ee}${Pe}${Se}${Oe}${Y.specs}${qe}
|
|
1605
1598
|
export interface ShardDOConfig {
|
|
1606
1599
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1607
1600
|
cdc?: boolean;
|
|
@@ -1618,27 +1611,38 @@ export interface ShardDOConfig {
|
|
|
1618
1611
|
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1619
1612
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1620
1613
|
/** \`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. */
|
|
1621
|
-
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${
|
|
1614
|
+
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ft}${k.configFields}${N.configField}${Ue}${gt}${bt}${yt}${Z.configField}
|
|
1622
1615
|
}
|
|
1623
|
-
${
|
|
1624
|
-
|
|
1616
|
+
${q("schedulerStub",vt,["cancel","runAfter","runAt"])}${q("storageStub",kt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${St}${Nt}${At}${k.stubs}${We}
|
|
1617
|
+
// \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
|
|
1618
|
+
// mutation may be replayed, so a network call in either returns a different answer
|
|
1619
|
+
// on each run. Refused at runtime, not only linted: the advisor sees just the call
|
|
1620
|
+
// sites it can read, and a call inside a dependency is invisible to it.
|
|
1621
|
+
// Synchronous on purpose: an async refusal only rejects a promise the handler may
|
|
1622
|
+
// discard, and the handler would then return normally. A sync throw surfaces at the call.
|
|
1623
|
+
// Module scope: it captures nothing, so one instance serves every dispatch.
|
|
1624
|
+
const refuseFetch = (): never => {
|
|
1625
|
+
throw new LunoraError("FORBIDDEN", "ctx.fetch is action-only: network I/O belongs in an action, not a query or mutation");
|
|
1626
|
+
};
|
|
1627
|
+
|
|
1628
|
+
${Bt}
|
|
1625
1629
|
|
|
1626
1630
|
/**
|
|
1627
1631
|
* Build the project's shard Durable Object. Export the result as \`ShardDO\`
|
|
1628
1632
|
* from the worker entry so wrangler binds it by name.
|
|
1629
1633
|
*/
|
|
1630
1634
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1631
|
-
class extends ShardDOBase {${
|
|
1635
|
+
class extends ShardDOBase {${qt}
|
|
1632
1636
|
private blockedUniqueIndexes: readonly string[] = [];
|
|
1633
1637
|
private migrated = false;
|
|
1634
|
-
private migrationRetryAt = 0;${
|
|
1635
|
-
${
|
|
1636
|
-
${
|
|
1637
|
-
${
|
|
1638
|
+
private migrationRetryAt = 0;${Ft}${Ut}${Kt}
|
|
1639
|
+
${ce.override}
|
|
1640
|
+
${Wt}
|
|
1641
|
+
${it}${ut}${Et}${Lt}
|
|
1638
1642
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
1639
1643
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1640
1644
|
}
|
|
1641
|
-
${
|
|
1645
|
+
${It}${Ct}${le}${Z.override}${$t}
|
|
1642
1646
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1643
1647
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1644
1648
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1737,7 +1741,7 @@ ${c?` const requestScope = this.captureRequestScope();
|
|
|
1737
1741
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1738
1742
|
return LUNORA_STUDIO_FEATURES();
|
|
1739
1743
|
}
|
|
1740
|
-
${
|
|
1744
|
+
${Q.evaluateOverride}${Q.subscriptionOverride}${Xe}${et}${rt}
|
|
1741
1745
|
protected override advisories(): AdvisoryFinding[] {
|
|
1742
1746
|
return LUNORA_ADVISORIES();
|
|
1743
1747
|
}
|
|
@@ -1746,7 +1750,7 @@ ${G.evaluateOverride}${G.subscriptionOverride}${ze}${Ze}
|
|
|
1746
1750
|
return LUNORA_ADVISOR_PROCEDURES();
|
|
1747
1751
|
}
|
|
1748
1752
|
|
|
1749
|
-
${
|
|
1753
|
+
${Cr}
|
|
1750
1754
|
|
|
1751
1755
|
/**
|
|
1752
1756
|
* Migrate the base schema. A UNIQUE index that existing duplicate rows block
|
|
@@ -1771,7 +1775,7 @@ ${Tr}
|
|
|
1771
1775
|
return;
|
|
1772
1776
|
}
|
|
1773
1777
|
|
|
1774
|
-
this.blockedUniqueIndexes = runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false, deferBlockedUniqueIndexes: true${
|
|
1778
|
+
this.blockedUniqueIndexes = runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false, deferBlockedUniqueIndexes: true${ye} });
|
|
1775
1779
|
this.invalidateCompanionMemo();
|
|
1776
1780
|
this.migrated = this.blockedUniqueIndexes.length === 0;
|
|
1777
1781
|
this.migrationRetryAt = now + BLOCKED_MIGRATION_RETRY_MS;
|
|
@@ -1784,7 +1788,7 @@ ${Tr}
|
|
|
1784
1788
|
throw new LunoraError("INTERNAL", this.blockedUniqueIndexes.join("; "));
|
|
1785
1789
|
}
|
|
1786
1790
|
}
|
|
1787
|
-
${
|
|
1791
|
+
${te?`
|
|
1788
1792
|
protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
|
|
1789
1793
|
// Migrations create the fts5 companions; without them every backfill
|
|
1790
1794
|
// statement would raise "no such table" on a shard that has never
|
|
@@ -1793,7 +1797,7 @@ ${ee?`
|
|
|
1793
1797
|
|
|
1794
1798
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1795
1799
|
}
|
|
1796
|
-
`:""}${
|
|
1797
|
-
${
|
|
1800
|
+
`:""}${Rt}
|
|
1801
|
+
${Lr({hasSensitiveArgs:G,lazyFunctions:c,actionOnlyFields:zt,agentsBuild:Ne,agentsContextField:$e,containersBuild:De,containersContextField:Te,databaseOptions:Ot,everyContextBuild:Vt,everyContextField:Gt,facadeBlock:Ht,globalDatabaseLine:_t,notifyBuild:Qt,ormContextField:Tt,paymentsBuild:Fe,paymentsContextField:Be,queuesBuild:we,queuesContextField:ve,topicsBuild:Re,topicsContextField:xe,vectorsBuild:xt,vectorsContextField:Dt,workflowsBuild:Ie,workflowsContextField:Ce,actionOnlyBuild:Yt})}
|
|
1798
1802
|
};
|
|
1799
|
-
`};export{
|
|
1803
|
+
`};export{Ur as b,pn as e};
|