@lunora/codegen 1.0.0-alpha.317 → 1.0.0-alpha.319

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 At}from"@lunora/errors";import{serializeSchemaSnapshot as Ot,hashSchemaSnapshot as Dt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Tt,isD1GlobalTable as Et}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Ct}from"./json-data-Chfs2Cz5.mjs";import{r as T,e as Lt,a as _t,b as It,c as Mt,d as Pt,f as Nt,g as $t,h as qt,i as Ft,j as Ut,k as Bt,l as Wt,m as jt,n as Ht,o as Vt,p as Kt,q as Gt}from"./shard-runtime-CkTgY8tL.mjs";import{u as K,i as Qt,G as zt,d as Jt}from"./shared-DnCokNcE.mjs";import{p as Yt}from"./platform-8oj7iXQy.mjs";import{i as Xt}from"./schema-BgM8A3XV.mjs";const h=(a,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(a))}) as ${e}); })()`,te=["categories","description","facing","level","remediation","title"],Zt=a=>{const e={};return{advisoryRows:a.map(n=>{let r=e[n.name];return r||(r=Object.fromEntries(te.filter(s=>s in n).map(s=>[s,n[s]])),e[n.name]=r),Object.fromEntries(Object.entries(n).filter(([s,d])=>!te.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},er=` /**
1
+ import{LunoraError as At}from"@lunora/errors";import{serializeSchemaSnapshot as Ot,hashSchemaSnapshot as Dt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Tt,isD1GlobalTable as Et}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as Ct}from"./json-data-Chfs2Cz5.mjs";import{r as T,e as Lt,a as _t,b as It,c as Mt,d as Pt,f as Nt,g as $t,h as qt,i as Ft,j as Ut,k as Bt,l as Wt,m as jt,n as Ht,o as Vt,p as Kt,q as Gt}from"./shard-runtime-BQ6ZNigW.mjs";import{u as K,i as zt,G as Qt,d as Jt}from"./shared-DnCokNcE.mjs";import{p as Yt}from"./platform-8oj7iXQy.mjs";import{i as Xt}from"./schema-BgM8A3XV.mjs";const h=(n,e)=>`((): (() => ${e}) => { let cached: ${e} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(n))}) as ${e}); })()`,te=["categories","description","facing","level","remediation","title"],Zt=n=>{const e={};return{advisoryRows:n.map(a=>{let r=e[a.name];return r||(r=Object.fromEntries(te.filter(s=>s in a).map(s=>[s,a[s]])),e[a.name]=r),Object.fromEntries(Object.entries(a).filter(([s,d])=>!te.includes(s)||JSON.stringify(d)!==JSON.stringify(r[s])))}),advisoryRules:e}},er=` /**
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
@@ -23,14 +23,14 @@ import{LunoraError as At}from"@lunora/errors";import{serializeSchemaSnapshot as
23
23
  this.recordChangedTable(delta.table, delta.indexKeys);
24
24
  },
25
25
  cdc: config.cdc ?? false,
26
- headroom,
26
+ ...(headroom === undefined ? {} : { headroom }),
27
27
  // Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
28
28
  inTransaction: () => this.isInTransaction(),
29
29
  scheduler,
30
30
  schema: schema as unknown as SchemaLike,
31
31
  sql: this.sql as SqlExec,
32
32
  });
33
- }`,m=(a="")=>` const writer = this.adminWriter(${a});`,tr=`${er}
33
+ }`,m=(n="")=>` const writer = this.adminWriter(${n});`,tr=`${er}
34
34
 
35
35
  protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
36
36
  this.ensureMigrated();
@@ -50,10 +50,10 @@ import{LunoraError as At}from"@lunora/errors";import{serializeSchemaSnapshot as
50
50
  ${m()}
51
51
 
52
52
  return runDataMigration({
53
- batchSize: args.batchSize,
54
- direction: args.direction,
55
- dryRun: args.dryRun,
56
- maxBatches: args.maxBatches,
53
+ ...(args.batchSize === undefined ? {} : { batchSize: args.batchSize }),
54
+ ...(args.direction === undefined ? {} : { direction: args.direction }),
55
+ ...(args.dryRun === undefined ? {} : { dryRun: args.dryRun }),
56
+ ...(args.maxBatches === undefined ? {} : { maxBatches: args.maxBatches }),
57
57
  migration: migration as unknown as DataMigrationLike,
58
58
  // Flush after each batch so live migrationStatus subscribers see
59
59
  // progress mid-run (the base method records the reserved state
@@ -142,7 +142,7 @@ ${m()}
142
142
  // \`exportShardRows\` walks in keyset batches so a large table does not
143
143
  // materialize at once inside the generator; the admin RPC's response
144
144
  // is a single array, so it is collected here rather than streamed.
145
- for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, { batchSize: args.batchSize, tables: args.tables })) {
145
+ for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, args)) {
146
146
  rows.push(row);
147
147
  }
148
148
 
@@ -157,7 +157,7 @@ ${m()}
157
157
  // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
158
158
  // database's \`_id\`s carry across verbatim and every foreign key
159
159
  // referencing them stays valid without a second remapping pass.
160
- return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
160
+ return importShardRows(writer, schema as unknown as SchemaLike, args);
161
161
  }
162
162
 
163
163
  protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
@@ -192,7 +192,7 @@ ${m()}
192
192
 
193
193
  return writer.related(
194
194
  { id: args.id, table: args.table },
195
- { cursor: args.cursor, depth: args.depth, direction: args.direction, edges: args.edges, limit: args.limit },
195
+ args,
196
196
  );
197
197
  }
198
198
 
@@ -210,10 +210,10 @@ ${m()}
210
210
  }
211
211
 
212
212
  return writer.rankPageRows(args.table, args.index, {
213
- after: args.after,
214
- cursor: args.cursor,
215
- partitionKey: args.partitionKey,
216
- take: args.take,
213
+ ...(args.after === undefined ? {} : { after: args.after }),
214
+ ...(args.cursor === undefined ? {} : { cursor: args.cursor }),
215
+ ...(args.partitionKey === undefined ? {} : { partitionKey: args.partitionKey }),
216
+ ...(args.take === undefined ? {} : { take: args.take }),
217
217
  });
218
218
  }
219
219
 
@@ -225,14 +225,14 @@ ${m()}
225
225
  await applyCdcChanges(writer, args.changes);
226
226
 
227
227
  return { applied: args.changes.length };
228
- }`,rr=({actionOnlyBuild:a,actionOnlyFields:e,agentsBuild:t,agentsContextField:n,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:g,everyContextField:w,facadeBlock:c,globalDatabaseLine:y,notifyBuild:S,ormContextField:E,paymentsBuild:v,paymentsContextField:C,queuesBuild:i,queuesContextField:f,topicsBuild:L,topicsContextField:_,vectorsBuild:I,vectorsContextField:x,workflowsBuild:M,workflowsContextField:P})=>{const k=e.length>0,l=k?`
228
+ }`,rr=({actionOnlyBuild:n,actionOnlyFields:e,agentsBuild:t,agentsContextField:a,containersBuild:r,containersContextField:s,databaseOptions:d,everyContextBuild:g,everyContextField:y,facadeBlock:c,globalDatabaseLine:w,notifyBuild:S,ormContextField:E,paymentsBuild:v,paymentsContextField:C,queuesBuild:i,queuesContextField:f,topicsBuild:L,topicsContextField:_,vectorsBuild:I,vectorsContextField:x,workflowsBuild:M,workflowsContextField:P})=>{const k=e.length>0,l=k?`
229
229
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
230
230
  // and attached only for an \`action\` so query/mutation ctx never carry them.
231
231
  if (isAction) {
232
- ${a.replaceAll(/^(?=.)/gmu," ")}${e.map(u=>` ctx.${u} = ${u};`).join(`
232
+ ${n.replaceAll(/^(?=.)/gmu," ")}${e.map(u=>` ctx.${u} = ${u};`).join(`
233
233
  `)}
234
234
  }
235
- `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
235
+ `:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark | undefined; functionPath?: string | undefined; headroom?: TransactionHeadroomTracker | undefined; identity?: SubscriptionIdentity | undefined; kind?: "query" | undefined; onRead?: ((table: string, idOrScan?: string) => void) | undefined; onReadRange?: ((range: KeyRange) => void) | undefined; scope?: QueryReadScope | undefined; trusted?: boolean | undefined } = {}): unknown {
236
236
  const env = (this.env ?? {}) as Record<string, unknown>;
237
237
  // The caller context this ctx runs under, resolved ONCE on one
238
238
  // discriminant. When the caller threads an explicit identity
@@ -247,11 +247,17 @@ ${a.replaceAll(/^(?=.)/gmu," ")}${e.map(u=>` ctx.${u} = ${u};`
247
247
  // One expression, not one per field: three parallel ternaries on the
248
248
  // same discriminant is how \`ip\` came to be the only one still reading
249
249
  // the shared field.
250
- const caller: SubscriptionIdentity = options.identity ?? {
251
- identity: this.getCurrentIdentity(),
252
- ip: this.getCurrentIp(),
253
- userId: this.getCurrentUserId(),
254
- };
250
+ const caller: SubscriptionIdentity = options.identity ?? (() => {
251
+ const identity = this.getCurrentIdentity();
252
+ const ip = this.getCurrentIp();
253
+ const userId = this.getCurrentUserId();
254
+
255
+ return {
256
+ ...(identity === undefined ? {} : { identity }),
257
+ ...(ip === undefined ? {} : { ip }),
258
+ ...(userId === undefined ? {} : { userId }),
259
+ };
260
+ })();
255
261
  const { identity, ip, userId } = caller;
256
262
  ${I}${g}${r}${M}${i}${L}${t}
257
263
  // Which dispatch this ctx belongs to. Drives the two deferral facades
@@ -362,7 +368,7 @@ ${I}${g}${r}${M}${i}${L}${t}
362
368
  // so both write to the same trace.
363
369
  const span = this.makeDispatchSpan(traceAnchor, observability);
364
370
 
365
- ${y} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
371
+ ${w} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
366
372
  // adds aggregate counters (call count, total time, per-operation
367
373
  // breakdown) to the wide event rather than a span per call, so a
368
374
  // handler making hundreds of queries stays readable. See
@@ -431,7 +437,7 @@ ${S}
431
437
  scheduler,
432
438
  span,
433
439
  storage: contextStorage,
434
- trace,${x}${w}${C}${s}${P}${f}${_}${n}
440
+ trace,${x}${y}${C}${s}${P}${f}${_}${a}
435
441
  };
436
442
  ${k?` const isAction = contextKind === "action";
437
443
  `:""}${l}
@@ -504,7 +510,7 @@ ${e.map(u=>` delete descriptors.${u};
504
510
  installRun(ctx, contextKind);
505
511
 
506
512
  return ctx;
507
- }`},ar=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
513
+ }`},nr=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
508
514
  // referencing call fails loudly with a clear error instead of overflowing the
509
515
  // stack. Tracked across the awaited handler chain (one DO invocation is
510
516
  // single-threaded), so the counter reflects true nesting depth.
@@ -570,7 +576,7 @@ const dispatchRun = async (
570
576
  } finally {
571
577
  runDepth -= 1;
572
578
  }
573
- };`,nr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
579
+ };`,ar=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
574
580
  const registered = LUNORA_FUNCTIONS[functionPath];
575
581
 
576
582
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -765,7 +771,9 @@ __COMMITTED_CATCH__ } finally {
765
771
 
766
772
  // Ranges come from THIS run's reads, never a shared field on the DO:
767
773
  // a deferred re-run interleaves with unrelated dispatches.
768
- return { ranges: footprint.ranges(), result, tables: footprint.tables };
774
+ const ranges = footprint.ranges();
775
+
776
+ return { ...(ranges === undefined ? {} : { ranges }), result, tables: footprint.tables };
769
777
  }
770
778
 
771
779
  protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
@@ -794,7 +802,7 @@ __COMMITTED_CATCH__ } finally {
794
802
  }
795
803
 
796
804
  throw error;
797
- `,ir=a=>nr.replace("__COMMITTED_CATCH__",a?or:""),dr=a=>{const e={};for(const t of a.tables){const n={};for(const[r,s]of Object.entries(t.shape)){const d=K(s);d.kind==="id"&&d.tableName!==void 0&&(n[r]=d.tableName)}Object.keys(n).length>0&&(e[t.name]=n)}return e},cr=a=>{const e={};for(const t of a.tables){const n=[];for(const[r,s]of Object.entries(t.shape))K(s).kind==="storage"&&n.push(r);n.length>0&&(e[t.name]=n)}return e},lr=a=>{const e={};for(const t of a.tables){const n=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];n.length>0&&(e[t.name]=n)}return e},hr=a=>{const e=[];for(const t of a.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},ur=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const e=[];for(const t of a.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const n=JSON.parse(t.literalValue);if(typeof n!="string")return;e.push(n)}catch{return}}return e},pr=(a,e,t)=>{const n=K(e),r={name:a,optional:Qt(e),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){r.ref=n.tableName;const d=t.get(a);d!==void 0&&(r.onDelete=d)}n.kind==="storage"&&(r.isStorage=!0,n.bucket!==void 0&&(r.bucket=n.bucket));const s=ur(n);return s!==void 0&&(r.enumValues=s),n.column?.notNull===!1&&(r.nullable=!0),r},mr=a=>{const e={};for(const t of a.tables){const n=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))n.push(pr(s,d,r));e[t.name]=n}return e},gr=({hasMutators:a,hasShapes:e,rlsData:t})=>{const n=e?`
805
+ `,ir=n=>ar.replace("__COMMITTED_CATCH__",n?or:""),dr=n=>{const e={};for(const t of n.tables){const a={};for(const[r,s]of Object.entries(t.shape)){const d=K(s);d.kind==="id"&&d.tableName!==void 0&&(a[r]=d.tableName)}Object.keys(a).length>0&&(e[t.name]=a)}return e},cr=n=>{const e={};for(const t of n.tables){const a=[];for(const[r,s]of Object.entries(t.shape))K(s).kind==="storage"&&a.push(r);a.length>0&&(e[t.name]=a)}return e},lr=n=>{const e={};for(const t of n.tables){const a=[...t.indexes.map(r=>({fields:[...r.fields],name:r.name,type:"index",...r.unique===!0?{unique:!0}:{}})),...t.searchIndexes.map(r=>({fields:[r.field,...r.filterFields??[]],name:r.name,type:"search"})),...(t.geoIndexes??[]).map(r=>({fields:[r.field],name:r.name,type:"geo"})),...t.rankIndexes.map(r=>({fields:r.sortBy.map(s=>s.field),name:r.name,type:"rank"})),...t.vectorIndexes.map(r=>({fields:r.field===void 0?[]:[r.field],name:r.name,type:"vector"}))];a.length>0&&(e[t.name]=a)}return e},hr=n=>{const e=[];for(const t of n.tables)!t.ttl||t.shardMode==="global"||e.push({...t.ttl.after===void 0?{}:{after:t.ttl.after},field:t.ttl.field,...t.softDelete?{softDeleteField:t.softDelete.field}:{},table:t.name});return e},ur=n=>{if(n.kind!=="union"||n.members===void 0||n.members.length===0)return;const e=[];for(const t of n.members){if(t.kind!=="literal"||t.literalValue===void 0)return;try{const a=JSON.parse(t.literalValue);if(typeof a!="string")return;e.push(a)}catch{return}}return e},pr=(n,e,t)=>{const a=K(e),r={name:n,optional:zt(e),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){r.ref=a.tableName;const d=t.get(n);d!==void 0&&(r.onDelete=d)}a.kind==="storage"&&(r.isStorage=!0,a.bucket!==void 0&&(r.bucket=a.bucket));const s=ur(a);return s!==void 0&&(r.enumValues=s),a.column?.notNull===!1&&(r.nullable=!0),r},mr=n=>{const e={};for(const t of n.tables){const a=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...t.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],r=new Map(t.relations.flatMap(s=>s.kind==="one"?[[s.field,s.onDelete]]:[]));for(const[s,d]of Object.entries(t.shape))a.push(pr(s,d,r));e[t.name]=a}return e},gr=({hasMutators:n,hasShapes:e,rlsData:t})=>{const a=e?`
798
806
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
799
807
  const shape = LUNORA_SHAPES[name];
800
808
 
@@ -812,9 +820,8 @@ __COMMITTED_CATCH__ } finally {
812
820
  // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
813
821
  // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
814
822
  // rather than every shape restating the ownership check in its \`where\`.
815
- const shapeWhere = shape.compileWhere(ctx, args, {
816
- ownerField: (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField,
817
- }) as unknown as WhereInput;
823
+ const ownerField = (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField;
824
+ const shapeWhere = shape.compileWhere(ctx, args, ownerField === undefined ? {} : { ownerField }) as unknown as WhereInput;
818
825
 
819
826
  // AND-compose with the read policies this SHAPE declares
820
827
  // (\`defineShape({ use: [guard] })\`, pre-indexed into
@@ -856,16 +863,16 @@ __COMMITTED_CATCH__ } finally {
856
863
  // instead of the CDC poke path.
857
864
  const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
858
865
 
859
- return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
866
+ return { ...(shape.columns === undefined ? {} : { columns: shape.columns }), effectiveWhere, global: isGlobal, table: shape.table };
860
867
  }
861
- `:"",r=e?[...new Set(t.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,y)=>c.localeCompare(y)):[],s=r.length>0?`
868
+ `:"",r=e?[...new Set(t.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],s=r.length>0?`
862
869
  /** 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). */
863
870
  assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
864
- `:"";return{customMutatorOverride:a?`
871
+ `:"";return{customMutatorOverride:n?`
865
872
  protected override isCustomMutator(functionPath: string): boolean {
866
873
  return LUNORA_MUTATOR_PATHS.has(functionPath);
867
874
  }
868
- `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},fr=(a,e)=>a?`
875
+ `:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:s,shapeReadPolicyImport:s===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:a}},fr=(n,e)=>n?`
869
876
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
870
877
  const env = this.env as Record<string, unknown>;
871
878
  // A shape read performs no writes, so the widened request only needs
@@ -878,7 +885,13 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
878
885
  // cache in front of this read — keys on identity + userId only. Equal
879
886
  // keys must mean equal rows, so a field the writer can scope by has to
880
887
  // be either in the key or out of the request; it is out.
881
- const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity: identity?.identity, userId: identity?.userId };
888
+ const bookmark = this.getInboundBookmark();
889
+ const globalRequest = {
890
+ ...this.globalCdcOptions(config.cdc ?? false),
891
+ ...(bookmark === undefined ? {} : { bookmark }),
892
+ ...(identity?.identity === undefined ? {} : { identity: identity.identity }),
893
+ ...(identity?.userId === undefined ? {} : { userId: identity.userId }),
894
+ };
882
895
  const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
883
896
  const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
884
897
 
@@ -891,7 +904,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
891
904
  // so bail early and let the caller fail it closed.
892
905
  do {
893
906
  // eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
894
- const page = await globalDb.findMany(resolved.table, { cursor, where: resolved.effectiveWhere });
907
+ const page = await globalDb.findMany(resolved.table, { cursor, ...(resolved.effectiveWhere === undefined ? {} : { where: resolved.effectiveWhere }) });
895
908
 
896
909
  for (const doc of page.page) {
897
910
  rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
@@ -919,12 +932,13 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
919
932
  // literal trips an excess-property error (TS2353) that makes the
920
933
  // emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
921
934
  // a \`defineShape\`. The Hyperdrive factory simply never reads it.
922
- const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
935
+ const bookmark = this.getInboundBookmark();
936
+ const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), ...(bookmark === undefined ? {} : { bookmark }) };
923
937
  const globalDb: DatabaseWriterLike = ${e}?.(env, globalRequest) ?? globalDbStub;
924
938
 
925
- return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
939
+ return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
926
940
  }
927
- `:"",br=a=>({externalSourceOverride:a?`
941
+ `:"",br=n=>({externalSourceOverride:n?`
928
942
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
929
943
  const env = (this.env ?? {}) as Record<string, unknown>;
930
944
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1064,7 +1078,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1064
1078
 
1065
1079
  return nextDueAt;
1066
1080
  }
1067
- `:"",sourceBootstrap:a?`
1081
+ `:"",sourceBootstrap:n?`
1068
1082
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1069
1083
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1070
1084
 
@@ -1074,11 +1088,11 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(r)}, (schema as
1074
1088
  if (autoSourced) {
1075
1089
  void this.scheduleSourcePoll();
1076
1090
  }
1077
- `:"",sourceClientCacheConst:a?`
1091
+ `:"",sourceClientCacheConst:n?`
1078
1092
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1079
1093
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1080
- `:""}),wr=(a,e)=>{const t=e.length>0,r=a?T("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1081
- `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",w=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=a?`
1094
+ `:""}),yr=(n,e)=>{const t=e.length>0,r=n?T("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",s=t?` const vectorShardKey = this.currentShardKey();
1095
+ `:"",d=t?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",y=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...t?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${e.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=n?`
1082
1096
  const vectorSync = this.vectorSync(env);
1083
1097
  // Vectorize lives outside this shard's SQLite, so a query whose result
1084
1098
  // depends on a similarity search cannot be proven current on reconnect —
@@ -1088,14 +1102,14 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1088
1102
  const bareVectors = vectorSync?.vectors ?? vectorsStub;
1089
1103
  const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
1090
1104
  const onWrite = vectorSync?.onWrite;
1091
- `:"";return{vectorSyncMethod:a?`
1105
+ `:"";return{vectorSyncMethod:n?`
1092
1106
  private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
1093
1107
  if (!config.vectors) {
1094
1108
  return undefined;
1095
1109
  }
1096
1110
 
1097
1111
  const lunora = createVectors({ indexes: config.vectors(env) });
1098
- ${s} const vectors = createContextVectors(lunora${w});
1112
+ ${s} const vectors = createContextVectors(lunora${y});
1099
1113
 
1100
1114
  return {
1101
1115
  backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
@@ -1121,14 +1135,14 @@ ${s} const vectors = createContextVectors(lunora${w});
1121
1135
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1122
1136
  });
1123
1137
  }
1124
- `:"",vectorsBuild:c,vectorsStub:r}},Lr=({advisories:a=[],advisorProcedures:e=[],agents:t=[],capabilities:n=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:g=!1,hasNotify:w=!1,hasRooms:c=!1,hasVectors:y=!0,maskMetadata:S,mutators:E=[],queues:v=[],rlsMetadata:C,schema:i,schemaSnapshot:f,shapes:L=[],storageRules:_,studioFeatures:I,services:x=[],topics:M=[],useUmbrella:P=!1,workflows:k=[]})=>{const l=Jt(P),N=E.length>0,u=L.length>0,re=f===void 0?"":Ot(f),ae=f===void 0?"":`
1138
+ `:"",vectorsBuild:c,vectorsStub:r}},Lr=({advisories:n=[],advisorProcedures:e=[],agents:t=[],capabilities:a=new Set,containers:r=[],env:s,flagKeys:d=[],hasFlags:g=!1,hasNotify:y=!1,hasRooms:c=!1,hasVectors:w=!0,maskMetadata:S,mutators:E=[],queues:v=[],rlsMetadata:C,schema:i,schemaSnapshot:f,shapes:L=[],storageRules:_,studioFeatures:I,services:x=[],topics:M=[],useUmbrella:P=!1,workflows:k=[]})=>{const l=Jt(P),N=E.length>0,u=L.length>0,re=f===void 0?"":Ot(f),ne=f===void 0?"":`
1125
1139
  /** 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. */
1126
1140
  const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Dt(f))}, json: ${JSON.stringify(re)} };
1127
- `,ne=f===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Lt(n),A=_t(g,l.flags),$=It(d,g,l.flags),q=Gt(w),F=Mt(s),{build:se,contextField:oe,importLines:ie,specs:de}=Pt(Yt(v)),{build:ce,contextField:le,importLines:he,specs:ue}=Nt(M,v),U=$t(x,l.server),{build:pe,contextField:me,importLines:ge,specs:fe}=qt(r,i.jurisdiction),{build:be,contextField:we,importLines:ye,specs:ve}=Ft(k),{build:ke,contextField:Se,importLines:Re,specs:xe}=Ut(t),{build:Ae,configField:Oe,contextField:De,imports:Te,stub:Ee}=Bt(n.has("payments")),Ce=a,{advisoryRules:Le,advisoryRows:_e}=Zt(Ce),Ie=e,G=C??{policies:[],roles:[]},Me=S??{columns:[]},Pe=_??{rules:[]},Ne=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:$e,override:qe}=Wt(k),{constant:Fe,override:Ue}=jt(v),p=y&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(o=>Xt(o)).map(o=>o.name)),Q=p&&i.vectorIndexes.some(o=>B.has(o.table)),R=i.tables.some(o=>o.shardMode==="global"),W=Ht(B),j=i.tables.some(o=>Tt(o)),z=i.tables.some(o=>Et(o)),O=i.tables.some(o=>o.externalSource!==void 0),J=i.tables.some(o=>o.memory===!0),H=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(z&&j)throw new At("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Be=dr(i),We=lr(i),je=mr(i),He=cr(i),Y=hr(i),X=Vt(p,k.length>0,v.length>0,g,H);u&&X.push("WhereInput");const Z=Kt(R),{customMutatorOverride:Ve,shapeGuardImport:Ke,shapeReadPolicyAssertion:Ge,shapeReadPolicyImport:Qe,shapeResolveOverride:ze}=gr({hasMutators:N,hasShapes:u,rlsData:G}),D=[`import type { ${X.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${H?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${J?"clearMemoryTables, ":""}${Ke}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${O?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...O?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],u?`import { asBucketStorage, ${Qe}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&D.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),p&&D.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),D.push(...b.importLines,...A.importLines,...q.importLines,...F.importLines,...ge,...ye,...ie,...he,...U.importLines,...Re,...Te,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...N?["LUNORA_MUTATOR_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...u?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Je=p?`
1128
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Ye=z?`
1141
+ `,ae=f===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Lt(a),A=_t(g,l.flags),$=It(d,g,l.flags),q=Gt(y),F=Mt(s),{build:se,contextField:oe,importLines:ie,specs:de}=Pt(Yt(v)),{build:ce,contextField:le,importLines:he,specs:ue}=Nt(M,v),U=$t(x,l.server),{build:pe,contextField:me,importLines:ge,specs:fe}=qt(r,i.jurisdiction),{build:be,contextField:ye,importLines:we,specs:ve}=Ft(k),{build:ke,contextField:Se,importLines:Re,specs:xe}=Ut(t),{build:Ae,configField:Oe,contextField:De,imports:Te,stub:Ee}=Bt(a.has("payments")),Ce=n,{advisoryRules:Le,advisoryRows:_e}=Zt(Ce),Ie=e,G=C??{policies:[],roles:[]},Me=S??{columns:[]},Pe=_??{rules:[]},Ne=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:$e,override:qe}=Wt(k),{constant:Fe,override:Ue}=jt(v),p=w&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(o=>Xt(o)).map(o=>o.name)),z=p&&i.vectorIndexes.some(o=>B.has(o.table)),R=i.tables.some(o=>o.shardMode==="global"),W=Ht(B),j=i.tables.some(o=>Tt(o)),Q=i.tables.some(o=>Et(o)),O=i.tables.some(o=>o.externalSource!==void 0),J=i.tables.some(o=>o.memory===!0),H=i.tables.some(o=>o.shardMode!=="global"&&o.searchIndexes.length>0);if(Q&&j)throw new At("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Be=dr(i),We=lr(i),je=mr(i),He=cr(i),Y=hr(i),X=Vt(p,k.length>0,v.length>0,g,H);u&&X.push("WhereInput");const Z=Kt(R),{customMutatorOverride:Ve,shapeGuardImport:Ke,shapeReadPolicyAssertion:Ge,shapeReadPolicyImport:ze,shapeResolveOverride:Qe}=gr({hasMutators:N,hasShapes:u,rlsData:G}),D=[`import type { ${X.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, ${H?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${J?"clearMemoryTables, ":""}${Ke}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${O?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${z?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...O?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],u?`import { asBucketStorage, ${ze}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&D.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),p&&D.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),D.push(...b.importLines,...A.importLines,...q.importLines,...F.importLines,...ge,...we,...ie,...he,...U.importLines,...Re,...Te,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...N?["LUNORA_MUTATOR_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...u?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Je=p?`
1142
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Ye=Q?`
1129
1143
  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;`:"",Xe=j?`
1130
1144
  hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ze=O?`
1131
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",et="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",tt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",rt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",at=R?T("globalDbStub: DatabaseWriterLike",et,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:nt,vectorsBuild:st,vectorsStub:ot}=wr(p,Q?i.vectorIndexes.filter(o=>B.has(o.table)).map(o=>o.name):[]),it=`{
1145
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",et="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",tt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",rt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",nt=R?T("globalDbStub: DatabaseWriterLike",et,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:at,vectorsBuild:st,vectorsStub:ot}=yr(p,z?i.vectorIndexes.filter(o=>B.has(o.table)).map(o=>o.name):[]),it=`{
1132
1146
  ...this.ctxDbTuning(),
1133
1147
  auth: { identity: identity ?? null, userId: userId ?? null },
1134
1148
  broadcast: (delta) => {
@@ -1163,10 +1177,12 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1163
1177
  // own \`ReadFootprint\` pair instead, and a dispatch with neither
1164
1178
  // gets an unbound hook that stamps no deps.
1165
1179
  onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
1166
- // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1180
+ // Omitted when there is no scope so \`createShardCtxDb\`
1167
1181
  // keeps its own "degrade a provable slice to a whole-table dep"
1168
1182
  // fallback rather than reporting into a no-op.
1169
- onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${p?`
1183
+ ...(options.onReadRange !== undefined
1184
+ ? { onReadRange: options.onReadRange }
1185
+ : options.scope === undefined ? {} : { onReadRange: this.getCtxDbReadRangeHook(options.scope) }),${p?`
1170
1186
  // Vectorize is outside this shard's SQLite and cannot roll back, so
1171
1187
  // the sync is held until the mutation's transaction has COMMITTED
1172
1188
  // (\`deferAfterCommit\`) instead of running inline. Inline, a write
@@ -1174,7 +1190,7 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1174
1190
  // exist — which a search then surfaces — and a rolled-back delete
1175
1191
  // left the row with its vector already purged. Outside a
1176
1192
  // transaction (an action) nothing is open and it runs at once.
1177
- onWrite: onWrite === undefined ? undefined : (event) => this.deferAfterCommit(() => onWrite(event)),`:""}
1193
+ ...(onWrite === undefined ? {} : { onWrite: (event) => this.deferAfterCommit(() => onWrite(event)) }),`:""}
1178
1194
  scheduler,
1179
1195
  schema: schema as unknown as SchemaLike,
1180
1196
  sql: this.sql as SqlExec,
@@ -1182,7 +1198,14 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1182
1198
  globalDb,`:""}
1183
1199
  }`,dt=p?`
1184
1200
  vectors,`:"",ct=V?`
1185
- orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",lt=R?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
1201
+ orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",lt=R?` const bookmark = this.getInboundBookmark();
1202
+ const globalRequest = {
1203
+ ...this.globalCdcOptions(config.cdc ?? false),
1204
+ ...(bookmark === undefined ? {} : { bookmark }),
1205
+ ...(identity === undefined ? {} : { identity }),
1206
+ onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } },
1207
+ ...(userId === undefined ? {} : { userId }),
1208
+ };
1186
1209
  const globalDb: DatabaseWriterLike = ${ee}?.(env, globalRequest) ?? globalDbStub;
1187
1210
  `:"",ht=fr(u&&R,ee),ut=c?` protected override roomHandlerPath(topic: string): string | undefined {
1188
1211
  // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
@@ -1199,7 +1222,7 @@ ${J?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sch
1199
1222
  if (LUNORA_TTL_SWEEPS.length > 0) {
1200
1223
  void this.scheduleTtlSweep();
1201
1224
  }
1202
- `:"",wt=`
1225
+ `:"",yt=`
1203
1226
  public constructor(state: ShardDOState, env: unknown) {
1204
1227
  super(state, env, {
1205
1228
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1208,6 +1231,7 @@ ${J?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sch
1208
1231
  // emitter can know that; a hand-written subclass leaves this unset
1209
1232
  // and keeps the backstop.
1210
1233
  ctxDbCacheWired: true,
1234
+ ...(config.deliveryAuthorization === undefined ? {} : { deliveryAuthorization: config.deliveryAuthorization((env ?? {}) as Record<string, unknown>) }),
1211
1235
  ...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
1212
1236
  ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1213
1237
  ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
@@ -1239,14 +1263,14 @@ ${mt}${bt} }
1239
1263
  protected override isPaidFunction(functionPath: string): boolean {
1240
1264
  return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
1241
1265
  }
1242
- `,yt=V?`
1266
+ `,wt=V?`
1243
1267
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1244
1268
  ${i.tables.map(o=>` facade[${JSON.stringify(o.name)}] = bindTableFacade(db, ${JSON.stringify(o.name)});`).join(`
1245
1269
  `)}
1246
1270
  `:"",vt=`${b.everyBuild}${A.build}${F.build}
1247
1271
  const secrets = createSecrets(env);
1248
1272
  `,kt=`${b.everyFields}${A.contextField}${q.contextField}${F.contextField}
1249
- secrets,`,St=q.build,Rt=[...b.actionFields,...x.length>0?["services"]:[]],xt=`${b.actionBuild}${U.build}`;return`${zt}${D.join(`
1273
+ secrets,`,St=q.build,Rt=[...b.actionFields,...x.length>0?["services"]:[]],xt=`${b.actionBuild}${U.build}`;return`${Qt}${D.join(`
1250
1274
  `)}
1251
1275
 
1252
1276
  type FunctionKind = "action" | "mutation" | "query";
@@ -1309,8 +1333,10 @@ const LUNORA_STORAGE_RULES = ${h(Pe,"StorageRulesResult")};
1309
1333
 
1310
1334
  /** 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. */
1311
1335
  const LUNORA_STUDIO_FEATURES = ${h(Ne,"StudioFeaturesResult")};
1312
- ${ae}${W.constant}${$.constant}${$e}${Fe}${fe}${ve}${de}${ue}${U.specs}${xe}
1336
+ ${ne}${W.constant}${$.constant}${$e}${Fe}${fe}${ve}${de}${ue}${U.specs}${xe}
1313
1337
  export interface ShardDOConfig {
1338
+ /** Current authority for RPC and ordinary subscription deliveries; other live delivery modes are refused. */
1339
+ deliveryAuthorization?: (env: Record<string, unknown>) => DeliveryAuthorization;
1314
1340
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1315
1341
  cdc?: boolean;
1316
1342
  /** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
@@ -1326,21 +1352,21 @@ export interface ShardDOConfig {
1326
1352
  /** \`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. */
1327
1353
  storage?: (env: Record<string, unknown>, origin?: string) => unknown;${Je}${b.configFields}${A.configField}${Oe}${Ye}${Xe}${Ze}${W.configField}
1328
1354
  }
1329
- ${T("schedulerStub",tt,["cancel","runAfter","runAt"])}${T("storageStub",rt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${at}${gt}${ot}${b.stubs}${Ee}
1330
- ${ar}
1355
+ ${T("schedulerStub",tt,["cancel","runAfter","runAt"])}${T("storageStub",rt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${nt}${gt}${ot}${b.stubs}${Ee}
1356
+ ${nr}
1331
1357
 
1332
1358
  /**
1333
1359
  * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1334
1360
  * from the worker entry so wrangler binds it by name.
1335
1361
  */
1336
1362
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1337
- class extends ShardDOBase {${wt}
1363
+ class extends ShardDOBase {${yt}
1338
1364
  private migrated = false;
1339
1365
 
1340
1366
  ${ir(c)}
1341
1367
  ${Z.override}
1342
1368
  ${sr}
1343
- ${Ve}${ze}${ht}${pt}
1369
+ ${Ve}${Qe}${ht}${pt}
1344
1370
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
1345
1371
  return LUNORA_LIFECYCLE_HOOKS[event];
1346
1372
  }
@@ -1448,7 +1474,7 @@ ${tr}
1448
1474
  return;
1449
1475
  }
1450
1476
 
1451
- runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ne} });
1477
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${ae} });
1452
1478
  this.migrated = true;
1453
1479
  }
1454
1480
  ${H?`
@@ -1460,7 +1486,7 @@ ${H?`
1460
1486
 
1461
1487
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1462
1488
  }
1463
- `:""}${nt}
1464
- ${rr({actionOnlyFields:Rt,agentsBuild:ke,agentsContextField:Se,containersBuild:pe,containersContextField:me,databaseOptions:it,everyContextBuild:vt,everyContextField:kt,facadeBlock:yt,globalDatabaseLine:lt,notifyBuild:St,ormContextField:ct,paymentsBuild:Ae,paymentsContextField:De,queuesBuild:se,queuesContextField:oe,topicsBuild:ce,topicsContextField:le,vectorsBuild:st,vectorsContextField:dt,workflowsBuild:be,workflowsContextField:we,actionOnlyBuild:xt})}
1489
+ `:""}${at}
1490
+ ${rr({actionOnlyFields:Rt,agentsBuild:ke,agentsContextField:Se,containersBuild:pe,containersContextField:me,databaseOptions:it,everyContextBuild:vt,everyContextField:kt,facadeBlock:wt,globalDatabaseLine:lt,notifyBuild:St,ormContextField:ct,paymentsBuild:Ae,paymentsContextField:De,queuesBuild:se,queuesContextField:oe,topicsBuild:ce,topicsContextField:le,vectorsBuild:st,vectorsContextField:dt,workflowsBuild:be,workflowsContextField:ye,actionOnlyBuild:xt})}
1465
1491
  };
1466
1492
  `};export{cr as b,Lr as e};
@@ -323,4 +323,4 @@ const ${e} = ${b(n,r)};
323
323
  : paymentStub;
324
324
 
325
325
  return payments;
326
- },`,stub:f("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",P,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},ae=(e,r,t,n,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{j as a,M as b,Q as c,Z as d,K as e,ee as f,te as g,H as h,z as i,ne as j,se as k,re as l,oe as m,D as n,ae as o,I as p,U as q,f as r,V as s,G as t,J as u,Y as v,X as w};
326
+ },`,stub:f("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",P,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},ae=(e,r,t,n,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","DeliveryAuthorization","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{j as a,M as b,Q as c,Z as d,K as e,ee as f,te as g,H as h,z as i,ne as j,se as k,re as l,oe as m,D as n,ae as o,I as p,U as q,f as r,V as s,G as t,J as u,Y as v,X as w};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.317",
3
+ "version": "1.0.0-alpha.319",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,15 +50,15 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/advisor": "1.0.0-alpha.227",
54
- "@lunora/agent": "1.0.0-alpha.219",
55
- "@lunora/container": "1.0.0-alpha.78",
53
+ "@lunora/advisor": "1.0.0-alpha.228",
54
+ "@lunora/agent": "1.0.0-alpha.220",
55
+ "@lunora/container": "1.0.0-alpha.79",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
57
  "@lunora/platform": "1.0.0-alpha.66",
58
- "@lunora/queue": "1.0.0-alpha.110",
59
- "@lunora/scheduler": "1.0.0-alpha.132",
60
- "@lunora/values": "1.0.0-alpha.68",
61
- "@lunora/workflow": "1.0.0-alpha.80",
58
+ "@lunora/queue": "1.0.0-alpha.111",
59
+ "@lunora/scheduler": "1.0.0-alpha.133",
60
+ "@lunora/values": "1.0.0-alpha.69",
61
+ "@lunora/workflow": "1.0.0-alpha.81",
62
62
  "@visulima/fs": "6.0.29",
63
63
  "jiti": "^2.7.0",
64
64
  "quicktype-core": "^26.0.0",