@lunora/codegen 1.0.0-alpha.364 → 1.0.0-alpha.366

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.
@@ -1,4 +1,4 @@
1
- import{LunoraError as he}from"@lunora/errors";import{serializeSchemaSnapshot as Jt,hashSchemaSnapshot as zt}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{isHyperdriveGlobalTable as Yt,isD1GlobalTable as Xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Zt}from"./json-data-Chfs2Cz5.mjs";import{r as $,e as er,a as tr,b as rr,c as nr,d as ar,f as sr,g as or,h as ir,i as dr,j as cr,k as lr,l as ur,m as hr,n as pr,o as mr,p as fr,q as gr}from"./shard-runtime-DXlpfT3P.mjs";import{u as M,h as br,s as yr,a as wr,I as vr,c as kr,G as Sr,d as Rr}from"./shared-Br_OnErI.mjs";import{p as xr}from"./platform-8oj7iXQy.mjs";import{i as Ar}from"./schema-BgM8A3XV.mjs";const p=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,pe=["categories","description","facing","level","remediation","title"],Or=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(pe.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!pe.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Dr=` /**
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
- }`,y=(r="")=>` const writer = this.adminWriter(${r});`,Tr=`${Dr}
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
- ${y()}
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
- ${y("headroom ?? this.transactionHeadroom()")}
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
- ${y()}
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
- ${y()}
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
- ${y()}
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
- ${y()}
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
- ${y()}
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
- ${y()}
232
+ ${b()}
233
233
 
234
234
  await applyCdcChanges(writer, args.changes);
235
235
 
236
236
  return { applied: args.changes.length };
237
- }`,_r=({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:g=!1,notifyBuild:c,ormContextField:w,paymentsBuild:q,paymentsContextField:A,queuesBuild:F,queuesContextField:U,topicsBuild:R,topicsContextField:B,vectorsBuild:d,vectorsContextField:v,workflowsBuild:E,workflowsContextField:j})=>{const I=t.length>0,C=w===""?"{ db }":"{ db, orm: bindOrm(facade) }",W=w===""?"":`
238
- orm: databaseContext.orm,`,K=w===""?"":`
239
- orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,O=I?`
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(f=>` ctx.${f} = ${f};`).join(`
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}${u}${n}${E}${F}${R}${e}
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 ${C};
388
+ ${m} return ${L};
389
389
  };
390
390
  const databaseContext = makeDatabaseContext(scheduler);
391
391
  const db = databaseContext.db;
392
- ${q}
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\`
@@ -458,16 +458,16 @@ ${c}
458
458
  // to the handler so code that signs its own URLs (a copy-in
459
459
  // \`createStorage\`) can fall back to it too. \`undefined\` for a
460
460
  // query and for a deferred dispatch, for the reasons given there.
461
- origin: requestOrigin,${W}
461
+ origin: requestOrigin,${H}
462
462
  scheduler,
463
463
  span,
464
464
  storage: contextStorage,
465
- trace,${v}${h}${A}${a}${j}${U}${B}${o}${S?`
465
+ trace,${w}${h}${A}${a}${K}${j}${W}${o}${S?`
466
466
  [Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
467
467
  };
468
- ${I?` const isAction = contextKind === "action";
469
- `:""}${O}
470
- ${g?` const captureScope = (): (() => void) => {
468
+ ${C?` const isAction = contextKind === "action";
469
+ `:""}${P}
470
+ ${f?` const captureScope = (): (() => void) => {
471
471
  const requestScope = this.captureRequestScope();
472
472
  return () => this.restoreRequestScope(requestScope);
473
473
  };
@@ -477,7 +477,7 @@ ${g?` const captureScope = (): (() => void) => {
477
477
  // The callee runs inside this invocation, so its marked arguments are scrubbed here too.
478
478
  this.admitSensitiveArgs(options.sensitive, reference.__lunoraRef, fnArgs);
479
479
 
480
- return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${g?", undefined, captureScope":""});
480
+ return dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind${f?", undefined, captureScope":""});
481
481
  };
482
482
  // The composed mutation runs under the SAME wrapper the top-level RPC
483
483
  // uses, so "do the transactional work in a mutation and call it from the
@@ -500,7 +500,7 @@ ${g?` const captureScope = (): (() => void) => {
500
500
  // refuses network I/O wherever it runs, so its \`fetch\` is overridden here.
501
501
  return Object.defineProperties({}, {
502
502
  ...Object.getOwnPropertyDescriptors(target),
503
- db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${K}
503
+ db: { configurable: true, enumerable: true, value: mutationDatabase.db, writable: true },${V}
504
504
  fetch: { configurable: true, enumerable: true, value: refuseFetch, writable: true },
505
505
  random: { configurable: true, enumerable: true, value: mutationRandom, writable: true },
506
506
  scheduler: { configurable: true, enumerable: true, value: mutationScheduler, writable: true },
@@ -512,7 +512,7 @@ ${g?` const captureScope = (): (() => void) => {
512
512
  installRun(mutationCtx, kind);
513
513
  }
514
514
 
515
- return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${g?", captureScope":""});
515
+ return dispatchRun("mutation", reference.__lunoraRef, fnArgs, mutationCtx, kind, async (work) => this.runMutationTransaction(mutationCtx, work)${f?", captureScope":""});
516
516
  };
517
517
  // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
518
518
  // its OWN query context, built without the subscription's read-footprint
@@ -537,7 +537,7 @@ ${g?` const captureScope = (): (() => void) => {
537
537
  runOptions?.untracked === true
538
538
  ? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope, sensitive: options.sensitive })
539
539
  : queryContext(),
540
- kind,${g?`
540
+ kind,${f?`
541
541
  undefined,
542
542
  captureScope,`:""}
543
543
  );
@@ -563,7 +563,7 @@ ${g?` const captureScope = (): (() => void) => {
563
563
 
564
564
  if (queryView === undefined) {
565
565
  const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
566
- ${t.map(f=>` delete descriptors.${f};
566
+ ${t.map(v=>` delete descriptors.${v};
567
567
  `).join("")} // Writable and configurable, like the plain fields they replace.
568
568
  const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
569
569
 
@@ -585,7 +585,7 @@ ${t.map(f=>` delete descriptors.${f};
585
585
  installRun(ctx, contextKind);
586
586
 
587
587
  return ctx;
588
- }`},me=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
588
+ }`},fe=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
589
589
  // referencing call fails loudly with a clear error instead of overflowing the
590
590
  // stack. Tracked across the awaited handler chain (one DO invocation is
591
591
  // single-threaded), so the counter reflects true nesting depth.
@@ -651,7 +651,7 @@ const dispatchRun = async (
651
651
  } finally {
652
652
  runDepth -= 1;
653
653
  }
654
- };`,Er=r=>r?me.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
654
+ };`,Pr=r=>r?fe.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
655
655
  captureScope?: () => () => void,`).replace(` try {
656
656
  // A mutation composed from an action`,` try {
657
657
  let loaded = getLoadedFunction(functionPath);
@@ -672,7 +672,7 @@ const dispatchRun = async (
672
672
 
673
673
  const loadedFunction = loaded;
674
674
 
675
- // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):me,Ir=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
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> {
676
676
  // A dispatch that did not come through the shard's \`/rpc\` (a scheduled call,
677
677
  // a lifecycle hook, an admin run) has no scope of its own, so it opens one here
678
678
  // and releases it when the handler settles.
@@ -876,7 +876,7 @@ __COMMITTED_CATCH__ } finally {
876
876
  // \`ctx.scheduler\` call that reached the buffer in the first place.
877
877
  protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
878
878
  return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
879
- }`,Cr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
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> {
880
880
  const registered = LUNORA_FUNCTIONS[functionPath];
881
881
 
882
882
  if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
@@ -917,7 +917,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
917
917
  // \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
918
918
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
919
919
  };
920
- }`,Lr=` } catch (error) {
920
+ }`,Mr=` } catch (error) {
921
921
  // The write committed before this failed. Mark the error so the caller can tell
922
922
  // a durable write from a rollback: the rethrow still reaches the caller unchanged.
923
923
  if (typeof error === "object" && error !== null) {
@@ -925,7 +925,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
925
925
  }
926
926
 
927
927
  throw error;
928
- `,Pr=(r,t=!1)=>{const e=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
928
+ `,qr=(r,t=!1)=>{const e=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
929
929
 
930
930
  if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
931
931
  throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
@@ -942,7 +942,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
942
942
  }
943
943
  }
944
944
 
945
- `:"";return Ir.replace("__COMMITTED_CATCH__",r?Lr:"").replace("__PREPARE_FUNCTION__",`${e}${o}`)},Nr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,a]of Object.entries(e.shape)){const i=M(a);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},$r=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,a]of Object.entries(e.shape))M(a).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Mr=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},qr=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},Fr=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},Ur=new Set(["bigint","boolean","date","number","timestamp"]),Br=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=M(o(e)?t:e);return o(t)!==o(e)&&Ur.has(n.kind)?n:void 0},jr=(r,t,e)=>{const o=M(t),n=Br(o),a=n??o,i={name:r,optional:br(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=Fr(a);return u!==void 0&&(i.enumValues=u),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Wr=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(jr(a,i,n));t[e.name]=o}return t},Kr=({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} {
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} {
946
946
  const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
947
947
 
948
948
  try {
@@ -1017,14 +1017,14 @@ ${a}
1017
1017
 
1018
1018
  return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
1019
1019
  }
1020
- `:"",h=e?[...new Set(o.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],m=h.length>0?`
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?`
1021
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). */
1022
1022
  assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
1023
1023
  `:"";return{customMutatorOverride:r?`
1024
1024
  protected override isCustomMutator(functionPath: string): boolean {
1025
1025
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1026
1026
  }
1027
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},Hr=(r,t)=>r?`
1027
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:m,shapeReadPolicyImport:m===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:u}},Jr=(r,t)=>r?`
1028
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 }>> {
1029
1029
  const env = this.env as Record<string, unknown>;
1030
1030
  // A shape read performs no writes, so the widened request only needs
@@ -1090,7 +1090,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as
1090
1090
 
1091
1091
  return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
1092
1092
  }
1093
- `:"",Vr=r=>({externalSourceOverride:r?`
1093
+ `:"",zr=r=>({externalSourceOverride:r?`
1094
1094
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1095
1095
  const env = (this.env ?? {}) as Record<string, unknown>;
1096
1096
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1243,7 +1243,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as
1243
1243
  `:"",sourceClientCacheConst:r?`
1244
1244
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1245
1245
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1246
- `:""}),Gr=(r,t)=>{const e=t.length>0,n=r?$("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",a=e?` const vectorShardKey = this.currentShardKey();
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
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?`
1248
1248
  const vectorSync = this.vectorSync(env);
1249
1249
  // Vectorize lives outside this shard's SQLite, so a query whose result
@@ -1287,14 +1287,14 @@ ${a} const vectors = createContextVectors(lunora${h});
1287
1287
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1288
1288
  });
1289
1289
  }
1290
- `:"",vectorsBuild:m,vectorsStub:n}},cn=({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:g=!1,lazyFunctions:c=!1,hasVectors:w=!0,liveStreamDeclarations:q=[],liveStreams:A=!1,maskMetadata:F,mutators:U=[],queues:R=[],rlsMetadata:B,schema:d,schemaSnapshot:v,shapes:E=[],storageRules:j,studioFeatures:I,services:C=[],topics:W=[],useUmbrella:K=!1,workflows:O=[]})=>{const l=Rr(K),H=U.length>0,f=E.length>0,D=E.some(s=>yr(s.args).length>0),V=S||D,fe=v===void 0?"":Jt(v),ge=v===void 0?"":`
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?"":`
1291
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. */
1292
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(zt(v))}, json: ${JSON.stringify(fe)} };
1293
- `,be=v===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",k=er(o),L=tr(u,l.flags),G=rr(i,u,l.flags),Q=gr(h),J=nr(a),{build:ye,contextField:we,importLines:ve,specs:ke}=ar(xr(R)),{build:Se,contextField:Re,importLines:xe,specs:Ae}=sr(W,R),z=or(C,l.server),{build:Oe,contextField:De,importLines:Te,specs:_e}=ir(n,d.jurisdiction),{build:Ee,contextField:Ie,importLines:Ce,specs:Le}=dr(O),{build:Pe,contextField:Ne,importLines:$e,specs:Me}=cr(e,x&&e.length>0),{build:qe,configField:Fe,contextField:Ue,imports:Be,stub:je}=lr(o.has("payments")),We=r,{advisoryRules:Ke,advisoryRows:He}=Or(We),Ve=t,ne=B??{policies:[],roles:[]},Ge=F??{columns:[]},Qe=j??{rules:[]},Je=I??{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:ze,override:Ye}=ur(O),{constant:Xe,override:Ze}=hr(R),b=w&&d.vectorIndexes.length>0,Y=new Set(d.tables.filter(s=>Ar(s)).map(s=>s.name)),ae=b&&d.vectorIndexes.some(s=>Y.has(s.table)),T=d.tables.some(s=>s.shardMode==="global"),X=pr(Y),Z=d.tables.some(s=>Yt(s)),se=d.tables.some(s=>Xt(s)),P=d.tables.some(s=>s.externalSource!==void 0),oe=d.tables.some(s=>s.memory===!0),ee=d.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&Z)throw new he("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const te=d.tables.length>0,et=Nr(d),tt=Mr(d),rt=Wr(d),nt=$r(d),ie=qr(d),re=mr(b,O.length>0,R.length>0,u,ee);f&&re.push("WhereInput"),D&&re.push("SensitiveScope");const de=fr(T),{customMutatorOverride:at,shapeGuardImport:st,shapeReadPolicyAssertion:ot,shapeReadPolicyImport:it,shapeResolveOverride:dt}=Kr({hasMutators:H,hasSensitiveShapes:D,hasShapes:f,rlsData:ne}),_=A?q:[];for(const s of _)if(wr(s.exportName,"live stream export name"),!vr.test(s.filePath))throw new he("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ct=c?[]:_.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),lt=` protected override liveStreams() {
1294
- return { ${_.map(s=>`${kr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
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(", ")} };
1295
1295
  }
1296
- `,ut=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1297
- ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
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(`
1298
1298
  `)}
1299
1299
  ]);
1300
1300
 
@@ -1315,11 +1315,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1315
1315
  protected override liveStreams() {
1316
1316
  return Object.fromEntries(this.loadedLiveStreams);
1317
1317
  }
1318
- `;let ce="";_.length>0&&(ce=c?ut:lt);const N=[`import type { ${re.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${ee?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${st}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${P?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${de.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...P?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],f?`import { asBucketStorage, ${it}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];te&&N.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),b&&N.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),N.push(...k.importLines,...L.importLines,...Q.importLines,...J.importLines,...Te,...Ce,...ve,...xe,...z.importLines,...$e,...Be,...V?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ct,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...c?["getLoadedFunction","loadFunction"]:[],...H?["LUNORA_MUTATOR_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...g?["LUNORA_SOCKETS"]:[],...f?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const ht=b?`
1319
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",pt=se?`
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;`:"",mt=Z?`
1321
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ft=P?`
1322
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",gt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",bt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",yt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",wt=T?$("globalDbStub: DatabaseWriterLike",gt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:vt,vectorsBuild:kt,vectorsStub:St}=Gr(b,ae?d.vectorIndexes.filter(s=>Y.has(s.table)).map(s=>s.name):[]),Rt=`{
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=`{
1323
1323
  ...this.ctxDbTuning(),
1324
1324
  auth: { identity: identity ?? null, userId: userId ?? null },
1325
1325
  broadcast: (delta) => {
@@ -1359,7 +1359,7 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1359
1359
  // fallback rather than reporting into a no-op.
1360
1360
  ...(options.onReadRange !== undefined
1361
1361
  ? { onReadRange: options.onReadRange }
1362
- : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${b?`
1362
+ : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${g?`
1363
1363
  // Vectorize is outside this shard's SQLite and cannot roll back, so
1364
1364
  // the sync is held until the mutation's transaction has COMMITTED
1365
1365
  // (\`deferAfterCommit\`) instead of running inline. Inline, a write
@@ -1371,11 +1371,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1371
1371
  scheduler,
1372
1372
  schema: schema as unknown as SchemaLike,
1373
1373
  sql: this.sql as SqlExec,
1374
- storage,${T?`
1374
+ storage,${_?`
1375
1375
  globalDb,`:""}
1376
- }`,xt=b?`
1377
- vectors,`:"",At=te?`
1378
- orm: bindOrm(facade),`:"",le=Z?"config.hyperdriveGlobal":"config.d1",Ot=T?` const bookmark = this.getInboundBookmark();
1376
+ }`,Dt=g?`
1377
+ vectors,`:"",Tt=re?`
1378
+ orm: bindOrm(facade),`:"",ue=ee?"config.hyperdriveGlobal":"config.d1",_t=_?` const bookmark = this.getInboundBookmark();
1379
1379
  const globalRequest = {
1380
1380
  ...this.globalCdcOptions(config.cdc ?? false),
1381
1381
  ...(bookmark === undefined ? {} : { bookmark }),
@@ -1383,21 +1383,21 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1383
1383
  onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
1384
1384
  ...(userId === undefined ? {} : { userId }),
1385
1385
  };
1386
- const globalDb: DatabaseWriterLike = ${le}?.(env, globalRequest) ?? globalDbStub;
1387
- `:"",Dt=Hr(f&&T,le),Tt=m?` protected override roomHandlerPath(topic: string): string | undefined {
1386
+ const globalDb: DatabaseWriterLike = ${ue}?.(env, globalRequest) ?? globalDbStub;
1387
+ `:"",Et=Jr(D&&_,ue),It=m?` protected override roomHandlerPath(topic: string): string | undefined {
1388
1388
  // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1389
1389
  return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1390
1390
  }
1391
- `:"",_t=g?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1391
+ `:"",Ct=f?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1392
1392
  return LUNORA_SOCKETS[path];
1393
1393
  }
1394
- `:"",{externalSourceOverride:Et,sourceBootstrap:It,sourceClientCacheConst:Ct}=Vr(P),Lt=`
1394
+ `:"",{externalSourceOverride:Lt,sourceBootstrap:Pt,sourceClientCacheConst:Nt}=zr($),$t=`
1395
1395
  private shardInitDeferred = false;
1396
1396
  private deferredShardInit?: Promise<void>;
1397
1397
 
1398
1398
  protected override async runShardInit(): Promise<void> {
1399
1399
  this.ensureMigrated();
1400
- ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1400
+ ${ie?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1401
1401
  `:""}
1402
1402
  if (this.blockedUniqueIndexes.length > 0) {
1403
1403
  this.shardInitDeferred = true;
@@ -1437,11 +1437,11 @@ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1437
1437
 
1438
1438
  await this.deferredShardInit;
1439
1439
  }
1440
- `,Pt=ie.length>0?`
1440
+ `,Mt=de.length>0?`
1441
1441
  if (LUNORA_TTL_SWEEPS.length > 0) {
1442
1442
  void this.scheduleTtlSweep();
1443
1443
  }
1444
- `:"",Nt=`
1444
+ `:"",qt=`
1445
1445
  public constructor(state: ShardDOState, env: unknown) {
1446
1446
  super(state, env, {
1447
1447
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1458,7 +1458,7 @@ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1458
1458
  // exists — a trigger that fails first still flushes and fuses.
1459
1459
  ...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
1460
1460
  });
1461
- ${It}${Pt} }
1461
+ ${Pt}${Mt} }
1462
1462
 
1463
1463
  protected override isCacheableQuery(functionPath: string): boolean {
1464
1464
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1482,7 +1482,7 @@ ${It}${Pt} }
1482
1482
  protected override isPaidFunction(functionPath: string): boolean {
1483
1483
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1484
1484
  }
1485
- `,ue=c?`
1485
+ `,he=c?`
1486
1486
  protected override prepareFunction(functionPath: string, reason: "rpc" | "subscription" | "stream" | "reactor"): Promise<void> | undefined {
1487
1487
  const registered = LUNORA_FUNCTIONS[functionPath];
1488
1488
  const allowsInternal = reason === "reactor" || (reason === "rpc" && this.isSystemDispatch());
@@ -1497,14 +1497,14 @@ ${It}${Pt} }
1497
1497
 
1498
1498
  return loadFunction(functionPath).then(() => undefined);
1499
1499
  }
1500
- `:"",$t=ue===""?`
1500
+ `:"",Ft=he===""?`
1501
1501
 
1502
- `:`${ue}
1503
- `,Mt=V?`
1502
+ `:`${he}
1503
+ `,Ut=G?`
1504
1504
  protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
1505
- const registered = LUNORA_FUNCTIONS[functionPath];${D?`
1505
+ const registered = LUNORA_FUNCTIONS[functionPath];${T?`
1506
1506
  const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
1507
- const fromValidators = sensitiveArgumentNames(registered?.args ?? ${D?"shape?.args ?? ":""}{});
1507
+ const fromValidators = sensitiveArgumentNames(registered?.args ?? ${T?"shape?.args ?? ":""}{});
1508
1508
 
1509
1509
  if (registered?.sensitiveArgs === undefined) {
1510
1510
  return fromValidators;
@@ -1513,22 +1513,22 @@ ${It}${Pt} }
1513
1513
  return new Set([...registered.sensitiveArgs, ...fromValidators]);
1514
1514
  }
1515
1515
 
1516
- `:"",qt=Er(c),Ft=c?` const preparation = this.prepareFunction(functionPath, "subscription");
1516
+ `:"",Bt=Pr(c),jt=c?` const preparation = this.prepareFunction(functionPath, "subscription");
1517
1517
  if (preparation !== undefined) await preparation;
1518
- `:"",Ut=Cr.replace("__PREPARE_FUNCTION__",Ft),Bt=Pr(m,c),jt=te?`
1518
+ `:"",Wt=$r.replace("__PREPARE_FUNCTION__",jt),Kt=qr(m,c),Ht=re?`
1519
1519
  const facade = db as unknown as Record<string, FacadeEntry>;
1520
1520
  ${d.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`).join(`
1521
1521
  `)}
1522
- `:"",Wt=`${k.everyBuild}${L.build}${J.build}
1522
+ `:"",Vt=`${k.everyBuild}${N.build}${z.build}
1523
1523
  const secrets = createSecrets(env);
1524
- `,Kt=`${k.everyFields}${L.contextField}${Q.contextField}${J.contextField}
1525
- secrets,`,Ht=Q.build,Vt=A?`
1524
+ `,Gt=`${k.everyFields}${N.contextField}${J.contextField}${z.contextField}
1525
+ secrets,`,Qt=J.build,Jt=A?`
1526
1526
  const live = {
1527
1527
  publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
1528
1528
  await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1529
1529
  },
1530
1530
  };
1531
- `:"",Gt=[...k.actionFields,...C.length>0?["services"]:[],...A?["live"]:[]],Qt=`${k.actionBuild}${z.build}${Vt}`;return`${Sr}${N.join(`
1531
+ `:"",zt=[...k.actionFields,...L.length>0?["services"]:[],...A?["live"]:[]],Yt=`${k.actionBuild}${Y.build}${Jt}`;return`${Or}${M.join(`
1532
1532
  `)}
1533
1533
 
1534
1534
  type FunctionKind = "action" | "mutation" | "query";
@@ -1538,13 +1538,13 @@ interface FunctionReference {
1538
1538
  }
1539
1539
 
1540
1540
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1541
- const LUNORA_TABLE_REFS = ${p(et,"Record<string, Record<string, string>>")};
1541
+ const LUNORA_TABLE_REFS = ${p(nt,"Record<string, Record<string, string>>")};
1542
1542
 
1543
1543
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1544
- const LUNORA_TABLE_INDEXES = ${p(tt,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1544
+ const LUNORA_TABLE_INDEXES = ${p(at,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
1545
1545
 
1546
1546
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1547
- const LUNORA_TABLE_COLUMNS = ${p(rt,`Record<
1547
+ const LUNORA_TABLE_COLUMNS = ${p(st,`Record<
1548
1548
  string,
1549
1549
  Array<{
1550
1550
  bucket?: string;
@@ -1561,16 +1561,16 @@ const LUNORA_TABLE_COLUMNS = ${p(rt,`Record<
1561
1561
  >`)};
1562
1562
 
1563
1563
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1564
- const LUNORA_STORAGE_COLUMNS = ${p(nt,"Record<string, string[]>")};
1564
+ const LUNORA_STORAGE_COLUMNS = ${p(ot,"Record<string, string[]>")};
1565
1565
 
1566
1566
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1567
- const LUNORA_TTL_SWEEPS = ${Zt(ie,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1567
+ const LUNORA_TTL_SWEEPS = ${rr(de,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1568
1568
 
1569
1569
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1570
- const LUNORA_ADVISORY_RULES = ${p(Ke,"Record<string, Partial<AdvisoryFinding>>")};
1570
+ const LUNORA_ADVISORY_RULES = ${p(He,"Record<string, Partial<AdvisoryFinding>>")};
1571
1571
 
1572
1572
  /** Per-finding rows; rule-level text lives once in \`LUNORA_ADVISORY_RULES\` and is merged back on first read. */
1573
- const LUNORA_ADVISORY_ROWS = ${p(He,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1573
+ const LUNORA_ADVISORY_ROWS = ${p(Ve,"Array<Partial<AdvisoryFinding> & { name: string }>")};
1574
1574
 
1575
1575
  const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1576
1576
  let cached: AdvisoryFinding[] | undefined;
@@ -1578,23 +1578,23 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1578
1578
  })();
1579
1579
 
1580
1580
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1581
- const LUNORA_ADVISOR_PROCEDURES = ${p(Ve,"AdvisorProcedure[]")};
1581
+ const LUNORA_ADVISOR_PROCEDURES = ${p(Ge,"AdvisorProcedure[]")};
1582
1582
 
1583
1583
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1584
- const LUNORA_RLS_METADATA = ${p(ne,"RlsPoliciesResult")};
1585
- ${ot}
1584
+ const LUNORA_RLS_METADATA = ${p(ae,"RlsPoliciesResult")};
1585
+ ${ct}
1586
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. */
1587
- const LUNORA_MASK_METADATA = ${p(Ge,"MaskPoliciesResult")};
1587
+ const LUNORA_MASK_METADATA = ${p(Qe,"MaskPoliciesResult")};
1588
1588
 
1589
1589
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1590
- const LUNORA_STORAGE_RULES = ${p(Qe,"StorageRulesResult")};
1590
+ const LUNORA_STORAGE_RULES = ${p(Je,"StorageRulesResult")};
1591
1591
 
1592
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. */
1593
- const LUNORA_STUDIO_FEATURES = ${p(Je,"StudioFeaturesResult")};
1593
+ const LUNORA_STUDIO_FEATURES = ${p(ze,"StudioFeaturesResult")};
1594
1594
 
1595
1595
  /** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
1596
1596
  const BLOCKED_MIGRATION_RETRY_MS = 5000;
1597
- ${ge}${X.constant}${G.constant}${ze}${Xe}${_e}${Le}${ke}${Ae}${z.specs}${Me}
1597
+ ${be}${Z.constant}${Q.constant}${Ye}${Ze}${tt}${Ee}${Pe}${Se}${Oe}${Y.specs}${qe}
1598
1598
  export interface ShardDOConfig {
1599
1599
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1600
1600
  cdc?: boolean;
@@ -1611,9 +1611,9 @@ export interface ShardDOConfig {
1611
1611
  /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1612
1612
  scheduler?: (env: Record<string, unknown>) => unknown;
1613
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. */
1614
- storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ht}${k.configFields}${L.configField}${Fe}${pt}${mt}${ft}${X.configField}
1614
+ storage?: (env: Record<string, unknown>, origin?: string) => unknown;${ft}${k.configFields}${N.configField}${Ue}${gt}${bt}${yt}${Z.configField}
1615
1615
  }
1616
- ${$("schedulerStub",bt,["cancel","runAfter","runAt"])}${$("storageStub",yt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${wt}${Ct}${St}${k.stubs}${je}
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
1617
  // \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
1618
1618
  // mutation may be replayed, so a network call in either returns a different answer
1619
1619
  // on each run. Refused at runtime, not only linted: the advisor sees just the call
@@ -1625,24 +1625,24 @@ const refuseFetch = (): never => {
1625
1625
  throw new LunoraError("FORBIDDEN", "ctx.fetch is action-only: network I/O belongs in an action, not a query or mutation");
1626
1626
  };
1627
1627
 
1628
- ${qt}
1628
+ ${Bt}
1629
1629
 
1630
1630
  /**
1631
1631
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1632
1632
  * from the worker entry so wrangler binds it by name.
1633
1633
  */
1634
1634
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1635
- class extends ShardDOBase {${Nt}
1635
+ class extends ShardDOBase {${qt}
1636
1636
  private blockedUniqueIndexes: readonly string[] = [];
1637
1637
  private migrated = false;
1638
- private migrationRetryAt = 0;${$t}${Mt}${Bt}
1639
- ${de.override}
1640
- ${Ut}
1641
- ${at}${dt}${Dt}${Et}
1638
+ private migrationRetryAt = 0;${Ft}${Ut}${Kt}
1639
+ ${ce.override}
1640
+ ${Wt}
1641
+ ${it}${ut}${Et}${Lt}
1642
1642
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1643
1643
  return LUNORA_LIFECYCLE_HOOKS[event];
1644
1644
  }
1645
- ${Tt}${_t}${ce}${X.override}${Lt}
1645
+ ${It}${Ct}${le}${Z.override}${$t}
1646
1646
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1647
1647
  // socket-terminated half of the same reactivity — and differs only in who
1648
1648
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1741,7 +1741,7 @@ ${c?` const requestScope = this.captureRequestScope();
1741
1741
  protected override studioFeatures(): StudioFeaturesResult {
1742
1742
  return LUNORA_STUDIO_FEATURES();
1743
1743
  }
1744
- ${G.evaluateOverride}${G.subscriptionOverride}${Ye}${Ze}
1744
+ ${Q.evaluateOverride}${Q.subscriptionOverride}${Xe}${et}${rt}
1745
1745
  protected override advisories(): AdvisoryFinding[] {
1746
1746
  return LUNORA_ADVISORIES();
1747
1747
  }
@@ -1750,7 +1750,7 @@ ${G.evaluateOverride}${G.subscriptionOverride}${Ye}${Ze}
1750
1750
  return LUNORA_ADVISOR_PROCEDURES();
1751
1751
  }
1752
1752
 
1753
- ${Tr}
1753
+ ${Cr}
1754
1754
 
1755
1755
  /**
1756
1756
  * Migrate the base schema. A UNIQUE index that existing duplicate rows block
@@ -1775,7 +1775,7 @@ ${Tr}
1775
1775
  return;
1776
1776
  }
1777
1777
 
1778
- this.blockedUniqueIndexes = runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false, deferBlockedUniqueIndexes: true${be} });
1778
+ this.blockedUniqueIndexes = runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false, deferBlockedUniqueIndexes: true${ye} });
1779
1779
  this.invalidateCompanionMemo();
1780
1780
  this.migrated = this.blockedUniqueIndexes.length === 0;
1781
1781
  this.migrationRetryAt = now + BLOCKED_MIGRATION_RETRY_MS;
@@ -1788,7 +1788,7 @@ ${Tr}
1788
1788
  throw new LunoraError("INTERNAL", this.blockedUniqueIndexes.join("; "));
1789
1789
  }
1790
1790
  }
1791
- ${ee?`
1791
+ ${te?`
1792
1792
  protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
1793
1793
  // Migrations create the fts5 companions; without them every backfill
1794
1794
  // statement would raise "no such table" on a shard that has never
@@ -1797,7 +1797,7 @@ ${ee?`
1797
1797
 
1798
1798
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1799
1799
  }
1800
- `:""}${vt}
1801
- ${_r({hasSensitiveArgs:V,lazyFunctions:c,actionOnlyFields:Gt,agentsBuild:Pe,agentsContextField:Ne,containersBuild:Oe,containersContextField:De,databaseOptions:Rt,everyContextBuild:Wt,everyContextField:Kt,facadeBlock:jt,globalDatabaseLine:Ot,notifyBuild:Ht,ormContextField:At,paymentsBuild:qe,paymentsContextField:Ue,queuesBuild:ye,queuesContextField:we,topicsBuild:Se,topicsContextField:Re,vectorsBuild:kt,vectorsContextField:xt,workflowsBuild:Ee,workflowsContextField:Ie,actionOnlyBuild:Qt})}
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})}
1802
1802
  };
1803
- `};export{$r as b,cn as e};
1803
+ `};export{Ur as b,pn as e};