@lunora/shard-engine 1.0.0-alpha.16 → 1.0.0-alpha.161

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.
Files changed (158) hide show
  1. package/README.md +1 -1
  2. package/dist/conformance/index.mjs +1 -1
  3. package/dist/index.d.mts +884 -176
  4. package/dist/index.d.ts +884 -176
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/ADMIN_FUNCTIONS-zJra0V3L.mjs +1 -0
  7. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
  8. package/dist/packem_shared/AGG_COUNT-Ctb5Pnyl.mjs +1 -0
  9. package/dist/packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs +8 -0
  10. package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
  11. package/dist/packem_shared/CDC_LOG_TABLE-CwEMKX-0.mjs +18 -0
  12. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs +7 -0
  13. package/dist/packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs +4 -0
  14. package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +1 -0
  15. package/dist/packem_shared/CompanionMemo-BXU5vfak.mjs +1 -0
  16. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  17. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-DTOKJcGY.mjs +31 -0
  18. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs +1 -0
  19. package/dist/packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs +8 -0
  20. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs +1 -0
  21. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs +1 -0
  22. package/dist/packem_shared/DurableStreamRunner-MMlV5qKQ.mjs +1 -0
  23. package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
  24. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs +7 -0
  25. package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
  26. package/dist/packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs +7 -0
  27. package/dist/packem_shared/MAIL_RETENTION-DMolrLYt.mjs +18 -0
  28. package/dist/packem_shared/MAX_SQL_ROWS-eRignWyO.mjs +4 -0
  29. package/dist/packem_shared/MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs +1 -0
  30. package/dist/packem_shared/NotUniqueError-DU8p6_p8.mjs +1 -0
  31. package/dist/packem_shared/QUEUE_TABLE-C-goXtGd.mjs +17 -0
  32. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
  33. package/dist/packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs +28 -0
  34. package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs +1 -0
  35. package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
  36. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs +1 -0
  37. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
  38. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BjV34hfH.mjs +1 -0
  39. package/dist/packem_shared/ReactiveCache-DHhhLJtN.mjs +1 -0
  40. package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
  41. package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs +11 -0
  42. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs +6 -0
  43. package/dist/packem_shared/SEARCH_STATE_TABLE-nYN2eKs_.mjs +1 -0
  44. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs +8 -0
  45. package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
  46. package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
  47. package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
  48. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-loOUGfzw.mjs +1 -0
  49. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +1 -0
  50. package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
  51. package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
  52. package/dist/packem_shared/appendStreamChunk-BZYgGE9Y.mjs +17 -0
  53. package/dist/packem_shared/applyInsertDefaults-B0NXPs2x.mjs +1 -0
  54. package/dist/packem_shared/archiveCdcSegment-Cr8oGLfB.mjs +4 -0
  55. package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
  56. package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
  57. package/dist/packem_shared/awaitWsDrain-e88vUNdj.mjs +1 -0
  58. package/dist/packem_shared/backfillAggregateIndexes-BN0NwXQk.mjs +1 -0
  59. package/dist/packem_shared/buildIndexRange-DQ3eWAGd.mjs +1 -0
  60. package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
  61. package/dist/packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs +1 -0
  62. package/dist/packem_shared/buildSettings-BRkZd6_E.mjs +1 -0
  63. package/dist/packem_shared/buildShapeDiff-oiv4ZHqB.mjs +1 -0
  64. package/dist/packem_shared/clearMemoryTables-aMRERF0w.mjs +1 -0
  65. package/dist/packem_shared/compileWhereSql-TgKZIvWM.mjs +1 -0
  66. package/dist/packem_shared/computeRankPage-BZIpATcs.mjs +1 -0
  67. package/dist/packem_shared/createCompanionSync-zIF_F4oD.mjs +1 -0
  68. package/dist/packem_shared/createReplicaLink-CtUDWLK5.mjs +7 -0
  69. package/dist/packem_shared/createSystemReader-DcDLFfC-.mjs +1 -0
  70. package/dist/packem_shared/ctx-db-relay-shapes-DV0VO4HG.mjs +17 -0
  71. package/dist/packem_shared/ctx-db-search-state-FjgzTFok.mjs +1 -0
  72. package/dist/packem_shared/defineEngineContractSuite-BNY5-Bz-.mjs +1 -0
  73. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
  74. package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
  75. package/dist/packem_shared/do-sql-BWrJQAOh.mjs +1 -0
  76. package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
  77. package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
  78. package/dist/packem_shared/estimate-bytes-_k74s6LZ.mjs +1 -0
  79. package/dist/packem_shared/exportShardRows-6NxY9jMV.mjs +1 -0
  80. package/dist/packem_shared/fts-companion-CA8mLJWq.mjs +1 -0
  81. package/dist/packem_shared/ftsCompanionDdl-0y8d4YvE.mjs +1 -0
  82. package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
  83. package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
  84. package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
  85. package/dist/packem_shared/isSoftDeleted-Dfk5F4Kc.mjs +9 -0
  86. package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
  87. package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
  88. package/dist/packem_shared/materializeExternalRows-DE8zhD1x.mjs +1 -0
  89. package/dist/packem_shared/mergeChangedKeys-BHUURyp6.mjs +1 -0
  90. package/dist/packem_shared/nextTtlExpiry-DhKO_OpO.mjs +1 -0
  91. package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
  92. package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +1 -0
  93. package/dist/packem_shared/runShardMigrations-C-0ec-sY.mjs +5 -0
  94. package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
  95. package/dist/packem_shared/selectShapeMembers-BCfKypfN.mjs +1 -0
  96. package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
  97. package/dist/packem_shared/where-sql-BjY4rnqb.mjs +1 -0
  98. package/package.json +5 -4
  99. package/dist/packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs +0 -1
  100. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
  101. package/dist/packem_shared/AGG_COUNT-B0Pb1nQZ.mjs +0 -1
  102. package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
  103. package/dist/packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs +0 -8
  104. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
  105. package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
  106. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
  107. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DOox9BFi.mjs +0 -1
  108. package/dist/packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs +0 -1
  109. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs +0 -1
  110. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs +0 -1
  111. package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
  112. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
  113. package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
  114. package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
  115. package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
  116. package/dist/packem_shared/NotUniqueError-C32BFrv1.mjs +0 -1
  117. package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
  118. package/dist/packem_shared/RANK_TIEBREAK-D541BOFR.mjs +0 -1
  119. package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
  120. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
  121. package/dist/packem_shared/ReactiveCache-iWA9VRqk.mjs +0 -1
  122. package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
  123. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
  124. package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
  125. package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
  126. package/dist/packem_shared/aggregateTableName-DKo6dwBP.mjs +0 -1
  127. package/dist/packem_shared/applyOnDelete-fMu_5DR5.mjs +0 -1
  128. package/dist/packem_shared/applySelect-BjgwvZmI.mjs +0 -1
  129. package/dist/packem_shared/awaitWsDrain-DKycCSBS.mjs +0 -1
  130. package/dist/packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs +0 -1
  131. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
  132. package/dist/packem_shared/buildPokeFrames-CCxYXd2V.mjs +0 -1
  133. package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
  134. package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
  135. package/dist/packem_shared/computeRankPage-B7U6t1fW.mjs +0 -1
  136. package/dist/packem_shared/createCompanionSync-Dym8huD9.mjs +0 -1
  137. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
  138. package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
  139. package/dist/packem_shared/ctx-db-companions-7fIu-E2H.mjs +0 -1
  140. package/dist/packem_shared/defineEngineContractSuite-LKRHlQwE.mjs +0 -1
  141. package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
  142. package/dist/packem_shared/estimate-bytes-DwQON1Ky.mjs +0 -1
  143. package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
  144. package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
  145. package/dist/packem_shared/isSoftDeleted-doD_8AwX.mjs +0 -9
  146. package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
  147. package/dist/packem_shared/materializeExternalRows-BR8MvZTz.mjs +0 -1
  148. package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
  149. package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
  150. package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
  151. package/dist/packem_shared/runShardMigrations-DhZLG0bn.mjs +0 -5
  152. package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
  153. package/dist/packem_shared/selectExpiredIds-DxFEwNlT.mjs +0 -1
  154. package/dist/packem_shared/selectShapeMemberIds-BD3JiZn-.mjs +0 -1
  155. package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
  156. package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
  157. package/dist/packem_shared/stableWireKey-C4JfdJ_e.mjs +0 -1
  158. package/dist/packem_shared/wire-codec-D_fiax9d.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
+ import { R2BucketLike, ShardHost, SocketHost, SocketHandle } from '@lunora/platform';
2
3
  import { SQL, Name } from 'drizzle-orm';
3
- import { ShardHost, SocketHost, SocketHandle } from '@lunora/platform';
4
+ export { stableStringify, stableWireKey } from '@lunora/wire';
4
5
  interface KeyRange {
5
6
  hi: string;
6
7
  index: string;
@@ -22,15 +23,43 @@ declare const indexKeysForRow: (indexes: ReadonlyArray<{
22
23
  name: string;
23
24
  }>, row: Record<string, unknown>, serialize: (value: unknown) => unknown) => IndexKeyEntry[];
24
25
  declare const keysTouchRanges: (ranges: ReadonlyArray<KeyRange> | undefined, keys: ReadonlyArray<IndexKeyEntry> | undefined) => boolean;
26
+ interface RelationWriteBase {
27
+ readonly colocated: boolean;
28
+ readonly refusal?: string;
29
+ readonly table: string;
30
+ }
31
+ interface KeyedRelationWriteInfo extends RelationWriteBase {
32
+ readonly field: string;
33
+ readonly kind: "many" | "one";
34
+ readonly nullable: boolean;
35
+ readonly references: string;
36
+ readonly refusalNow?: never;
37
+ readonly through?: never;
38
+ }
39
+ interface ThroughRelationWriteInfo extends RelationWriteBase {
40
+ readonly kind: "many";
41
+ readonly pairIsOnlyUnique: boolean;
42
+ readonly refusalNow: () => string | undefined;
43
+ readonly through: {
44
+ readonly from: string;
45
+ readonly table: string;
46
+ readonly to: string;
47
+ };
48
+ }
49
+ type RelationWriteInfo = KeyedRelationWriteInfo | ThroughRelationWriteInfo;
50
+ type RelationWriteMap = Readonly<Record<string, Readonly<Record<string, RelationWriteInfo>>>>;
51
+ declare const describeRelationWrites: (schema: SchemaLike, inTransaction?: () => boolean) => RelationWriteMap;
25
52
  type SystemTableName = "_scheduled_functions" | "_storage";
26
53
  interface ScheduledFunctionDoc {
27
54
  args: Record<string, unknown>;
28
55
  attempts?: number;
29
56
  enqueuedAt: number;
30
- functionPath: string;
57
+ functionPath?: string;
31
58
  id: string;
59
+ pool?: string;
32
60
  scheduledFor: number;
33
61
  shardKey?: string;
62
+ workflow?: string;
34
63
  }
35
64
  interface StorageMetadata {
36
65
  contentType?: string;
@@ -86,6 +115,85 @@ interface WhereInput {
86
115
  OR?: WhereInput[];
87
116
  }
88
117
  declare const RELATION_EXISTS_KEY = "__relationExists";
118
+ interface SubscriptionQuery {
119
+ args?: Record<string, unknown>;
120
+ functionPath?: string;
121
+ sinceEpoch?: string;
122
+ sinceSeq?: number;
123
+ table?: string;
124
+ }
125
+ interface ShapeSubscriptionQuery {
126
+ args?: Record<string, unknown>;
127
+ name: string;
128
+ sinceEpoch?: string;
129
+ sinceSeq?: number;
130
+ }
131
+ interface SubscriptionEnvelope {
132
+ caps?: string[];
133
+ clientId?: string;
134
+ context?: Record<string, unknown>;
135
+ data?: unknown;
136
+ generation?: number;
137
+ id: string;
138
+ query?: SubscriptionQuery;
139
+ shape?: {
140
+ args?: Record<string, unknown>;
141
+ name: string;
142
+ };
143
+ sinceCheckpoint?: number;
144
+ sinceChunk?: number;
145
+ sinceEpoch?: string;
146
+ token?: string;
147
+ topic?: string;
148
+ type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
149
+ }
150
+ interface RpcRequest {
151
+ args?: Record<string, unknown>;
152
+ functionPath: string;
153
+ }
154
+ interface SocketAttachment {
155
+ admin?: boolean;
156
+ adminBinding?: string;
157
+ authenticated?: boolean;
158
+ clientId?: string;
159
+ connected?: boolean;
160
+ connectionId?: string;
161
+ context?: Record<string, unknown>;
162
+ deliveryPermits?: Record<string, {
163
+ epoch: number;
164
+ scope: string;
165
+ }>;
166
+ expiresAt?: number;
167
+ identity?: Record<string, unknown>;
168
+ ip?: string;
169
+ liveGrants?: Record<string, string>;
170
+ pageDeltas?: boolean;
171
+ pendingSince?: number;
172
+ shapes?: Record<string, ShapeSubscriptionQuery>;
173
+ socketFunction?: string;
174
+ socketPath?: string;
175
+ subs: Record<string, SubscriptionQuery>;
176
+ userId?: string;
177
+ whispers?: string[];
178
+ }
179
+ interface ResolvedShape {
180
+ columns?: ReadonlyArray<string>;
181
+ effectiveWhere?: WhereInput;
182
+ global?: boolean;
183
+ table: string;
184
+ }
185
+ interface SubscriptionIdentity {
186
+ identity?: Record<string, unknown>;
187
+ ip?: string;
188
+ userId?: string;
189
+ }
190
+ interface ShardSocketLike {
191
+ readonly bufferedAmount?: number;
192
+ close?: (code?: number, reason?: string) => void;
193
+ deserializeAttachment?: () => unknown;
194
+ send: (data: string) => void;
195
+ serializeAttachment?: (value: unknown) => void;
196
+ }
89
197
  type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
90
198
  interface AggregateIndexDefinitionLike {
91
199
  readonly by?: ReadonlyArray<string>;
@@ -137,6 +245,11 @@ interface ColumnMetaLike {
137
245
  interface ValidatorLike {
138
246
  readonly _meta?: {
139
247
  readonly column?: ColumnMetaLike;
248
+ readonly inner?: ValidatorLike;
249
+ readonly members?: ReadonlyArray<ValidatorLike>;
250
+ readonly shape?: Readonly<Record<string, ValidatorLike>>;
251
+ readonly tableName?: string;
252
+ readonly value?: unknown;
140
253
  };
141
254
  readonly kind?: string;
142
255
  readonly parse?: (value: unknown) => unknown;
@@ -144,7 +257,7 @@ interface ValidatorLike {
144
257
  type TriggerTimingLike = "after" | "before";
145
258
  type TriggerOpLike = "delete" | "insert" | "update";
146
259
  interface SchedulableWorkflowReferenceLike {
147
- readonly binding?: string;
260
+ readonly className?: string;
148
261
  readonly isLunoraWorkflow: true;
149
262
  readonly name?: string;
150
263
  }
@@ -178,11 +291,18 @@ interface SchemaLike {
178
291
  readonly rlsMode?: "required";
179
292
  readonly tables: Record<string, TableDefinitionLike>;
180
293
  }
294
+ type PatchVerifier = (previous: Record<string, unknown>, next: Record<string, unknown>) => boolean;
295
+ interface PatchWriteOptions {
296
+ verify?: PatchVerifier;
297
+ }
181
298
  interface TableDefinitionLike {
182
299
  readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
300
+ readonly commitOrderedMode?: boolean;
301
+ readonly dropStalePatchesMode?: boolean;
183
302
  readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
184
303
  readonly indexes: ReadonlyArray<IndexDefinitionLike>;
185
304
  readonly isPublic?: boolean;
305
+ readonly memoryMode?: boolean;
186
306
  readonly rankIndexes?: ReadonlyArray<RankIndexDefinitionLike>;
187
307
  readonly relationMap?: Record<string, RelationDefinitionLike>;
188
308
  readonly searchIndexes?: ReadonlyArray<SearchIndexDefinitionLike>;
@@ -200,13 +320,25 @@ interface TableDefinitionLike {
200
320
  field: string;
201
321
  };
202
322
  }
203
- interface RelationDefinitionLike {
323
+ interface KeyedRelationDefinitionLike {
204
324
  readonly field: string;
205
325
  readonly kind: "many" | "one";
206
326
  readonly onDelete?: OnDeleteActionLike;
207
327
  readonly references: string;
208
328
  readonly table: string;
329
+ readonly through?: never;
330
+ }
331
+ interface RelationThroughLike {
332
+ readonly from: string;
333
+ readonly table: string;
334
+ readonly to: string;
209
335
  }
336
+ interface ThroughRelationDefinitionLike {
337
+ readonly kind: "many";
338
+ readonly table: string;
339
+ readonly through: RelationThroughLike;
340
+ }
341
+ type RelationDefinitionLike = KeyedRelationDefinitionLike | ThroughRelationDefinitionLike;
210
342
  type OnDeleteActionLike = "cascade" | "restrict" | "set null";
211
343
  interface NestedWith {
212
344
  limit?: number;
@@ -219,13 +351,11 @@ interface WithInput {
219
351
  [relationName: string]: NestedWith | Record<string, true> | boolean | undefined;
220
352
  _count?: Record<string, true>;
221
353
  }
222
- interface ApplyOnDeleteOptions$1 {
223
- database: DatabaseWriterLike;
224
- relation: RelationDefinitionLike;
225
- row: Record<string, unknown>;
226
- tableName: string;
354
+ interface FanOutBudget {
355
+ remaining: number;
227
356
  }
228
357
  interface ResolveWithOptions {
358
+ fanOutBudget?: FanOutBudget;
229
359
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
230
360
  groupedCounter: (tableName: string, whereField: string, values: unknown[], policyWhere?: WhereInput) => Promise<Map<unknown, number>>;
231
361
  parents: Record<string, unknown>[];
@@ -243,12 +373,17 @@ interface ResolveWithResult {
243
373
  rows: Record<string, unknown>[];
244
374
  }
245
375
  type SortDirection = "asc" | "desc";
246
- type OrderByInput = Record<string, SortDirection>;
376
+ type NullPlacement = "first" | "last";
377
+ type OrderByInput = Record<string, SortDirection | {
378
+ nulls: NullPlacement;
379
+ sort: SortDirection;
380
+ }>;
247
381
  interface QueryArgs {
248
382
  baseWhere?: WhereInput;
249
383
  cursor?: null | string;
250
384
  includeDeleted?: boolean;
251
385
  limit?: number;
386
+ omitContinueCursor?: boolean;
252
387
  orderBy?: OrderByInput[];
253
388
  relationBaseWhere?: (table: string) => undefined | WhereInput;
254
389
  relationMask?: RelationMask;
@@ -264,15 +399,59 @@ interface CrossShardReadArgs {
264
399
  with?: WithInput;
265
400
  }
266
401
  type RelationMask = (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
402
+ interface QueryPlan {
403
+ params: unknown[];
404
+ plan: string[];
405
+ sql: string;
406
+ }
267
407
  interface QueryPage {
268
408
  continueCursor: null | string;
269
409
  isDone: boolean;
270
410
  page: Record<string, unknown>[];
271
411
  splitCursor?: null | string;
272
412
  }
413
+ interface RelationEdge {
414
+ readonly array: boolean;
415
+ readonly column: string;
416
+ readonly name: string;
417
+ readonly sourceTable: string;
418
+ readonly targetTable: string;
419
+ }
420
+ interface RelatedStartReference {
421
+ id: string;
422
+ table: string;
423
+ }
424
+ type RelatedStart = (Record<string, unknown> & {
425
+ _id: string;
426
+ }) | RelatedStartReference;
427
+ type RelatedDirection = "both" | "in" | "out";
428
+ interface RelatedOptions {
429
+ cursor?: null | string;
430
+ depth?: number;
431
+ direction?: RelatedDirection;
432
+ edges?: ReadonlyArray<string>;
433
+ limit?: number;
434
+ relationBaseWhere?: (table: string) => undefined | WhereInput;
435
+ relationMask?: RelationMask;
436
+ }
437
+ interface RelatedNode {
438
+ depth: number;
439
+ document: Record<string, unknown>;
440
+ path: ReadonlyArray<string>;
441
+ pathIds: ReadonlyArray<string>;
442
+ score: number;
443
+ table: string;
444
+ }
445
+ interface RelatedPage {
446
+ continueCursor: null | string;
447
+ isDone: boolean;
448
+ nodes: RelatedNode[];
449
+ }
273
450
  interface OrderKey {
274
451
  direction: SortDirection;
275
452
  field: string;
453
+ nullable: boolean;
454
+ nulls?: NullPlacement;
276
455
  }
277
456
  interface RestrictableQueryOptions {
278
457
  baseWhere?: WhereInput;
@@ -408,10 +587,8 @@ interface LifecycleEvent {
408
587
  shardKey: string;
409
588
  userId: string | null;
410
589
  }
411
- interface LifecycleDispatchInfo {
590
+ interface LifecycleDispatchInfo extends SubscriptionIdentity {
412
591
  event: LifecycleEvent;
413
- identity: Record<string, unknown> | undefined;
414
- userId: string | undefined;
415
592
  }
416
593
  interface MutationDelta {
417
594
  indexKeys?: ReadonlyArray<IndexKeyEntry>;
@@ -423,6 +600,14 @@ interface MutationDelta {
423
600
  interface DatabaseWriterLike {
424
601
  aggregate: (tableName: string, options: AggregateOptions) => Promise<AggregateResult>;
425
602
  asId?: (tableName: string, id: string) => string;
603
+ assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
604
+ cdcChangedTables?: (sinceSeq: number, options?: {
605
+ cursorOnly?: boolean;
606
+ }) => Promise<{
607
+ cursor: number;
608
+ floor?: number;
609
+ tables: string[];
610
+ } | undefined>;
426
611
  count: (tableName: string, where?: RestrictableQueryOptions | WhereInput) => Promise<number>;
427
612
  delete: (id: string, expectedTable?: string, options?: {
428
613
  hard?: boolean;
@@ -438,15 +623,17 @@ interface DatabaseWriterLike {
438
623
  }, expectedTable?: string) => Promise<{
439
624
  deleted: number;
440
625
  }>;
626
+ deleteRereadTables?: ReadonlySet<string>;
441
627
  deleteWhere?: (tableName: string, where: WhereInput, options?: {
442
628
  limit?: number;
443
629
  }) => Promise<{
444
630
  deleted: number;
445
631
  }>;
632
+ explain: (tableName: string, args?: QueryArgs) => Promise<QueryPlan>;
446
633
  findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
447
634
  findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
448
635
  findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
449
- get: (id: string, expectedTable?: string) => Promise<Record<string, unknown> | null>;
636
+ get: (table: string, id: string) => Promise<Record<string, unknown> | null>;
450
637
  groupBy: (tableName: string, options: GroupByOptions) => Promise<ReadonlyArray<GroupByEntry>>;
451
638
  insert: (tableName: string, document: Record<string, unknown>, options?: {
452
639
  allowExplicitId?: boolean;
@@ -460,12 +647,21 @@ interface DatabaseWriterLike {
460
647
  allowExplicitId?: boolean;
461
648
  limit?: number;
462
649
  }) => Promise<string[]>;
650
+ inTransaction?: () => boolean;
463
651
  lookupById?: (id: string, expectedTable?: string) => Promise<null | {
464
652
  row: Record<string, unknown>;
465
653
  tableName: string;
466
654
  }>;
467
655
  normalizeId: (tableName: string, id: string) => null | string;
468
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
656
+ patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
657
+ patchIf?: (tableName: string, id: string, args: {
658
+ patch: Record<string, unknown>;
659
+ verify?: PatchVerifier;
660
+ where: WhereInput;
661
+ }) => Promise<{
662
+ applied: boolean;
663
+ doc: Record<string, unknown> | null;
664
+ }>;
469
665
  patchMany?: (patches: ReadonlyArray<{
470
666
  id: string;
471
667
  patch: Record<string, unknown>;
@@ -487,10 +683,14 @@ interface DatabaseWriterLike {
487
683
  rankBefore?: (tableName: string, indexName: string, options: RankBeforeOptions) => Promise<RankBeforeResult>;
488
684
  rankPage: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<RankPage>;
489
685
  rankPageRows?: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<ShardRankPageResult>;
686
+ related?: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
687
+ relationEdges?: ReadonlyArray<RelationEdge>;
688
+ relationWrites?: RelationWriteMap;
490
689
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string, options?: {
491
690
  allowExplicitId?: boolean;
492
691
  }) => Promise<void>;
493
692
  restore?: (id: string, expectedTable?: string) => Promise<void>;
693
+ softDeleteFields?: ReadonlyMap<string, string>;
494
694
  system?: SystemDatabaseReader;
495
695
  wipeShard?: (options?: {
496
696
  chunkSize?: number;
@@ -516,6 +716,7 @@ interface ExportShardArgs {
516
716
  tables?: ReadonlyArray<string>;
517
717
  }
518
718
  interface ImportShardArgs {
719
+ dryRun?: boolean;
519
720
  rows: ReadonlyArray<ExportRow>;
520
721
  startLine?: number;
521
722
  }
@@ -525,7 +726,6 @@ interface ImportShardResult {
525
726
  inserted: Record<string, number>;
526
727
  }
527
728
  declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
528
- declare const exportShardTable: (writer: DatabaseWriterLike, table: string, batchSize?: number) => AsyncGenerator<ExportRow, void, undefined>;
529
729
  declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
530
730
  declare const validateImportRow: (schema: SchemaLike, table: string, record: Record<string, unknown>) => string | undefined;
531
731
  declare const importShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportShardArgs) => Promise<ImportShardResult>;
@@ -534,6 +734,7 @@ interface ExportShardAdminArgs {
534
734
  tables?: ReadonlyArray<string>;
535
735
  }
536
736
  interface ImportShardAdminArgs {
737
+ dryRun: boolean;
537
738
  rows: ReadonlyArray<ExportRow>;
538
739
  startLine?: number;
539
740
  }
@@ -573,8 +774,11 @@ declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefin
573
774
  index: AggregateIndexDefinitionLike;
574
775
  partial: Record<string, unknown>;
575
776
  };
576
- declare const stableStringify: (value: unknown) => string;
577
- declare const stableWireKey: (value: unknown) => string;
777
+ declare const clearCompanionSignatures: (sql: SqlExec) => void;
778
+ declare class CompanionMemo {
779
+ readonly verified: Set<string>;
780
+ invalidate(): void;
781
+ }
578
782
  interface CacheEntry {
579
783
  bytes: number;
580
784
  deps: Set<string>;
@@ -600,6 +804,7 @@ declare class ReactiveCache {
600
804
  private readonly maxBytes;
601
805
  private readonly now;
602
806
  private monotonic;
807
+ private generation;
603
808
  constructor(options?: ReactiveCacheOptions);
604
809
  run<R>(key: string, deps: Set<string>, run: () => Promise<R>, ranges?: () => ReadonlyArray<KeyRange>): Promise<R>;
605
810
  invalidate(table: string, id: string, indexKeys?: ReadonlyArray<IndexKeyEntry>): string[];
@@ -660,12 +865,18 @@ interface RunTriggersOptions {
660
865
  }
661
866
  declare const runTriggers: (options: RunTriggersOptions) => Promise<void>;
662
867
  declare const hasTrigger: (schema: SchemaLike, tableName: string, op: TriggerOpLike) => boolean;
868
+ interface SearchBackfillProgress {
869
+ done: boolean;
870
+ pages: number;
871
+ }
663
872
  declare const backfillAggregateIndexes: (sql: SqlExec, schema: SchemaLike) => void;
664
873
  declare const backfillRankIndexes: (sql: SqlExec, schema: SchemaLike) => void;
665
874
  declare const backfillSearchIndexesForTable: (sql: SqlExec, tableName: string, definition: {
666
875
  searchIndexes?: ReadonlyArray<SearchIndexDefinitionLike>;
667
876
  }) => void;
668
- declare const backfillSearchIndexes: (sql: SqlExec, schema: SchemaLike) => void;
877
+ declare const backfillSearchIndexes: (sql: SqlExec, schema: SchemaLike, options?: {
878
+ maxPages?: number;
879
+ }) => SearchBackfillProgress;
669
880
  declare const CDC_LOG_TABLE = "__cdc_log";
670
881
  interface CdcChange {
671
882
  doc?: Record<string, unknown>;
@@ -675,19 +886,35 @@ interface CdcChange {
675
886
  table: string;
676
887
  ts: number;
677
888
  }
678
- declare const migrateCdcLog: (sql: SqlExec) => void;
889
+ declare const CDC_LOG_TABLE_SEQ_INDEX = "__cdc_log_table_seq";
890
+ declare const migrateCdcLog: (sql: SqlExec, options?: {
891
+ rowHistoryIndex?: boolean;
892
+ }) => void;
679
893
  declare const appendCdcChange: (sql: SqlExec, ts: number, table: string, id: string, op: CdcChange["op"], doc: Record<string, unknown> | undefined) => void;
680
894
  declare const readCdcChanges: (sql: SqlExec, options?: {
681
895
  limit?: number;
682
896
  sinceSeq?: number;
683
- tables?: ReadonlySet<string>;
684
897
  }) => {
685
898
  changes: CdcChange[];
686
899
  cursor: number;
687
900
  };
688
- declare const trimCdcChanges: (sql: SqlExec, throughSeq: number) => void;
901
+ declare const cdcTouchesTables: (sql: SqlExec, sinceSeq: number, tables: ReadonlySet<string>) => boolean;
902
+ declare const cdcCanVouchFor: (sql: SqlExec, deps: ReadonlySet<string>) => boolean;
903
+ interface CdcChangeKey {
904
+ id: string;
905
+ op: CdcChange["op"];
906
+ seq: number;
907
+ }
908
+ declare const readCdcChangeKeys: (sql: SqlExec, table: string, sinceSeq: number, upTo: number) => CdcChangeKey[];
909
+ declare const trimCdcChanges: (sql: SqlExec, throughSeq: number, maxRows: number) => void;
910
+ declare const compactCdcDocs: (sql: SqlExec, throughSeq: number, maxRows: number) => void;
911
+ declare const cdcSeqLeavingRows: (sql: SqlExec, keep: number) => number | undefined;
689
912
  declare const readCdcCursor: (sql: SqlExec) => number;
913
+ declare const cursorBelowRetainedFloor: (floor: number | undefined, sinceSeq: number) => boolean;
914
+ declare const cdcTrimmedError: (floor: number, sinceSeq: number, scope: "global" | "shard") => LunoraError;
915
+ declare const cdcForkedError: (cursor: number, sinceSeq: number, scope: "global" | "shard", epoch?: string) => LunoraError;
690
916
  declare const minCdcSeq: (sql: SqlExec) => number | undefined;
917
+ declare const minCdcReplayableSeq: (sql: SqlExec) => number | undefined;
691
918
  declare const CDC_META_TABLE = "__cdc_meta";
692
919
  declare const migrateCdcMeta: (sql: SqlExec) => void;
693
920
  declare const readCdcEpoch: (sql: SqlExec) => string;
@@ -697,12 +924,6 @@ declare const CLIENT_WATERMARK_TABLE = "__client_watermark";
697
924
  declare const migrateClientWatermark: (sql: SqlExec) => void;
698
925
  declare const readClientWatermark: (sql: SqlExec, identity: string, clientId: string) => number;
699
926
  declare const advanceClientWatermark: (sql: SqlExec, identity: string, clientId: string, mutationId: number) => void;
700
- declare const GLOBAL_SHAPE_SNAPSHOT_TABLE = "__global_shape_snapshot";
701
- declare const migrateGlobalShapeSnapshot: (sql: SqlExec) => void;
702
- declare const readGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => Map<string, string>;
703
- declare const writeGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string, snapshot: Map<string, string>) => void;
704
- declare const deleteGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => void;
705
- declare const deleteGlobalShapeSnapshotsForConnection: (sql: SqlExec, connectionId: string) => void;
706
927
  declare const IDEMPOTENCY_TABLE = "__idempotency";
707
928
  interface IdempotentRecord {
708
929
  resultJson: string;
@@ -714,61 +935,32 @@ declare const writeIdempotent: (sql: SqlExec, identity: string, mutationId: stri
714
935
  declare const trimIdempotent: (sql: SqlExec, olderThanTs: number) => void;
715
936
  declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
716
937
  cdc?: boolean;
938
+ deferBlockedUniqueIndexes?: boolean;
717
939
  schemaSnapshot?: {
718
940
  hash: string;
719
941
  json: string;
720
942
  };
721
- }) => void;
722
- /**
723
- * How far a search companion's backfill has progressed, and what the next pass
724
- * should do about it.
725
- *
726
- * Neither stored analysis nor query policy, which is why it is its own module
727
- * rather than a third responsibility bolted onto one of them: it is *progress*,
728
- * the one piece of search state that is written as the index is built rather
729
- * than decided when it is read.
730
- *
731
- * The policy below is shared because when each engine owned a copy they
732
- * immediately disagreed about exactly the two cases that matter — whether a row
733
- * with no recorded profile may be resumed (it may not; nothing says what
734
- * analyzed it) and whether a never-started index is worth wiping (it is not;
735
- * there is nothing in it).
736
- */
737
- /**
738
- * How far a companion's backfill has progressed, and under which analysis.
739
- * Declared here rather than beside either engine's state table: both record the
740
- * same three facts, and the decisions made from them are the shared policy
741
- * below.
742
- */
743
- interface SearchBackfillState {
744
- /** Last `id` indexed, or `undefined` when no page has run yet. */
745
- cursor: string | undefined;
746
- /** True once a page came back short — the table is fully indexed. */
747
- done: boolean;
748
- /** Analyzer profile the stored rows were built with; `undefined` predates profile tracking. */
749
- profile: string | undefined;
750
- }
751
- declare const SEARCH_STATE_TABLE = "__lunora_search_state";
752
- declare const migrateSearchState: (sql: SqlExec) => void;
753
- declare const readSearchBackfillState: (sql: SqlExec, companion: string) => SearchBackfillState;
754
- declare const writeSearchBackfillState: (sql: SqlExec, companion: string, cursor: string | undefined, done: boolean, profile: string) => void;
943
+ }) => ReadonlyArray<string>;
755
944
  interface ShapeRow {
756
945
  doc: Record<string, unknown>;
757
946
  id: string;
758
947
  }
759
948
  declare const selectShapeRows: (sql: SqlExec, table: string, effectiveWhere: WhereInput | undefined) => ShapeRow[];
760
- declare const selectShapeMemberIds: (sql: SqlExec, table: string, effectiveWhere: WhereInput | undefined, ids: ReadonlyArray<string>) => Set<string>;
949
+ declare const selectShapeMembers: (sql: SqlExec, table: string, effectiveWhere: WhereInput | undefined, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
761
950
  interface SqlExec {
762
951
  exec: <Row = Record<string, unknown>>(sql: string, ...params: unknown[]) => SqlCursor<Row>;
763
952
  }
764
953
  interface SqlCursor<Row> extends Iterable<Row> {
954
+ readonly columnNames?: string[];
765
955
  one: () => Row;
956
+ raw?: () => IterableIterator<unknown[]>;
766
957
  toArray: () => Row[];
767
958
  }
768
959
  type IndexUseHook = (table: string, indexName: string, kind: "geo" | "index" | "rank" | "search") => void;
769
960
  type Clock = () => number;
770
961
  type IdGenerator = () => string;
771
962
  declare const assertValidClientId: (clientId: string) => void;
963
+ declare const assertStorableRowId: (id: string) => void;
772
964
  interface WriteEvent {
773
965
  doc?: Record<string, unknown>;
774
966
  id: string;
@@ -778,18 +970,26 @@ interface WriteEvent {
778
970
  type WriteHook = (event: WriteEvent) => Promise<void> | void;
779
971
  interface CtxDbOptions {
780
972
  auth?: ServerDefaultContextLike["auth"];
973
+ baselineSeq?: () => number | undefined;
781
974
  broadcast?: BroadcastDelta;
782
975
  cache?: ReactiveCache;
783
976
  cdc?: boolean;
784
977
  clock?: Clock;
978
+ companionMemo?: CompanionMemo;
785
979
  enforceRls?: boolean;
786
980
  globalDb?: DatabaseWriterLike;
787
981
  headroom?: TransactionHeadroomTracker;
788
982
  idGenerator?: IdGenerator;
983
+ inTransaction?: () => boolean;
789
984
  maxRelationKeys?: number;
790
985
  onIndexUse?: IndexUseHook;
791
986
  onRead?: ReadHook;
792
987
  onReadRange?: (range: KeyRange) => void;
988
+ onStalePatchDropped?: (event: {
989
+ fields: string[];
990
+ id: string;
991
+ table: string;
992
+ }) => void;
793
993
  onWrite?: WriteHook;
794
994
  relationExistsPushDown?: "always" | "auto" | "never";
795
995
  scheduler?: SchedulerLike;
@@ -802,6 +1002,8 @@ declare class NotUniqueError extends LunoraError {
802
1002
  constructor(message?: string);
803
1003
  }
804
1004
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
1005
+ declare const assertNoExplicitUndefined: (op: "patch" | "patchIf" | "replace", document: Record<string, unknown>) => void;
1006
+ declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
805
1007
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
806
1008
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
807
1009
  interface AuditEntry {
@@ -825,68 +1027,23 @@ declare const readAuditLog: (sql: SqlExec, options?: {
825
1027
  limit?: number;
826
1028
  sinceSeq?: number;
827
1029
  }) => AuditEntry[];
828
- interface SubscriptionQuery {
829
- args?: Record<string, unknown>;
830
- functionPath?: string;
831
- sinceEpoch?: string;
832
- sinceSeq?: number;
833
- table?: string;
834
- }
835
- interface ShapeSubscriptionQuery {
836
- args?: Record<string, unknown>;
837
- name: string;
838
- sinceEpoch?: string;
839
- sinceSeq?: number;
840
- }
841
- interface SubscriptionEnvelope {
842
- clientId?: string;
843
- context?: Record<string, unknown>;
844
- data?: unknown;
845
- id: string;
846
- query?: SubscriptionQuery;
847
- shape?: {
848
- args?: Record<string, unknown>;
849
- name: string;
850
- };
851
- sinceCheckpoint?: number;
852
- sinceEpoch?: string;
853
- topic?: string;
854
- type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
855
- }
856
- interface RpcRequest {
857
- args?: Record<string, unknown>;
858
- functionPath: string;
859
- }
860
- interface SocketAttachment {
861
- admin?: boolean;
862
- clientId?: string;
863
- connected?: boolean;
864
- connectionId?: string;
865
- context?: Record<string, unknown>;
866
- expiresAt?: number;
867
- identity?: Record<string, unknown>;
868
- shapes?: Record<string, ShapeSubscriptionQuery>;
869
- subs: Record<string, SubscriptionQuery>;
870
- userId?: string;
871
- whispers?: string[];
872
- }
873
- interface ResolvedShape {
874
- columns?: ReadonlyArray<string>;
875
- effectiveWhere?: WhereInput;
876
- global?: boolean;
877
- table: string;
878
- }
879
- interface SubscriptionIdentity {
880
- identity?: Record<string, unknown>;
881
- userId?: string;
882
- }
883
- interface ShardSocketLike {
884
- readonly bufferedAmount?: number;
885
- close?: (code?: number, reason?: string) => void;
886
- deserializeAttachment?: () => unknown;
887
- send: (data: string) => void;
888
- serializeAttachment?: (value: unknown) => void;
889
- }
1030
+ interface CdcArchiveScope {
1031
+ epoch: string;
1032
+ shard: string;
1033
+ }
1034
+ declare const readCdcArchivedThrough: (sql: SqlExec) => number;
1035
+ declare const writeCdcArchivedThrough: (sql: SqlExec, seq: number) => void;
1036
+ declare const archiveCdcSegment: (bucket: R2BucketLike, scope: CdcArchiveScope, changes: CdcChange[]) => Promise<void>;
1037
+ declare const cdcArchiveRewound: (bucket: R2BucketLike, scope: CdcArchiveScope, archivedThrough: number) => Promise<boolean>;
1038
+ declare const readArchivedCdcChanges: (bucket: R2BucketLike, scope: CdcArchiveScope, sinceSeq: number, limit: number | undefined) => Promise<{
1039
+ changes: CdcChange[];
1040
+ cursor: number;
1041
+ } | undefined>;
1042
+ declare const COMMIT_SEQ_TABLE = "__commit_seq";
1043
+ declare const COMMIT_SEQ_FIELD = "_commitSeq";
1044
+ declare const migrateCommitSeq: (sql: SqlExec) => void;
1045
+ declare const readCommitSeq: (sql: SqlExec) => number;
1046
+ declare const allocateCommitSeq: (sql: SqlExec) => number;
890
1047
  interface CompanionSyncDeps {
891
1048
  broadcast: (delta: MutationDelta) => void;
892
1049
  indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
@@ -897,6 +1054,7 @@ interface CompanionSyncDeps {
897
1054
  recordCdc: (table: string, id: string, op: "delete" | "insert" | "update", doc?: Record<string, unknown>) => void;
898
1055
  schema: SchemaLike;
899
1056
  sql: SqlExec;
1057
+ verified?: Set<string>;
900
1058
  }
901
1059
  interface CompanionSync {
902
1060
  ensureBackfilledForTable: (tableName: string) => void;
@@ -910,6 +1068,19 @@ interface CompanionSync {
910
1068
  syncSearch: (tableName: string, id: string, document: Record<string, unknown> | undefined, previous?: Record<string, unknown>) => void;
911
1069
  }
912
1070
  declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
1071
+ declare const GLOBAL_SHAPE_SNAPSHOT_TABLE = "__global_shape_snapshot";
1072
+ declare const migrateGlobalShapeSnapshot: (sql: SqlExec) => void;
1073
+ declare const readGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => Map<string, string> | undefined;
1074
+ declare const writeGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string, snapshot: Map<string, string>) => void;
1075
+ declare const deleteGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => void;
1076
+ declare const deleteGlobalShapeSnapshotsForConnection: (sql: SqlExec, connectionId: string) => void;
1077
+ declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
1078
+ declare const memoryTableNames: (schema: SchemaLike) => string[];
1079
+ declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
1080
+ declare const resolveRankSeekTuple: (options: {
1081
+ after?: RankPageRowKey;
1082
+ cursor?: null | string;
1083
+ }) => unknown[] | undefined;
913
1084
  interface RankPageDeps {
914
1085
  assertRankPartitionLocal: (tableName: string, definition: TableDefinitionLike, index: RankIndexDefinitionLike) => void;
915
1086
  ensureRankBackfilled: (tableName: string, index: RankIndexDefinitionLike) => void;
@@ -927,8 +1098,68 @@ interface RankPageComputation {
927
1098
  key: RankPageRowKey;
928
1099
  }[];
929
1100
  }
930
- declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
931
1101
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
1102
+ declare const SCHEDULE_OUTBOX_TABLE = "__schedule_outbox";
1103
+ interface ScheduleOutboxRow {
1104
+ attempts: number;
1105
+ envelopeJson: string;
1106
+ id: string;
1107
+ nextAttemptAt: number;
1108
+ }
1109
+ interface ScheduleOutboxEnvelope {
1110
+ args: unknown;
1111
+ options: Record<string, unknown> | undefined;
1112
+ target: unknown;
1113
+ when: number;
1114
+ }
1115
+ interface ScheduleOutbox {
1116
+ admit: (target: string) => number | undefined;
1117
+ forget: (id: string) => void;
1118
+ record: (id: string, envelope: ScheduleOutboxEnvelope) => void;
1119
+ wake: () => void;
1120
+ }
1121
+ declare const migrateScheduleOutbox: (sql: SqlExec) => void;
1122
+ declare const recordScheduleOutbox: (sql: SqlExec, id: string, envelopeJson: string, now: number) => void;
1123
+ declare const forgetScheduleOutbox: (sql: SqlExec, id: string) => void;
1124
+ declare const readDueScheduleOutbox: (sql: SqlExec, nowMs: number, limit: number) => ScheduleOutboxRow[];
1125
+ declare const deferScheduleOutbox: (sql: SqlExec, id: string, attempts: number, nextAttemptAt: number) => void;
1126
+ declare const parkScheduleOutbox: (sql: SqlExec, id: string, attempts: number) => void;
1127
+ declare const probeScheduleOutbox: (sql: SqlExec) => {
1128
+ dueAt: number | undefined;
1129
+ populated: boolean;
1130
+ };
1131
+ declare const trimScheduleOutbox: (sql: SqlExec, olderThanTs: number) => void;
1132
+ /**
1133
+ * How far a companion's backfill has progressed, and under which analysis.
1134
+ * Declared here rather than beside either engine's state table: both record the
1135
+ * same three facts, and the decisions made from them are the shared policy
1136
+ * below.
1137
+ */
1138
+ interface BackfillState {
1139
+ /** Last `id` indexed, or `undefined` when no page has run yet. */
1140
+ cursor: string | undefined;
1141
+ /** True once a page came back short — the table is fully indexed. */
1142
+ done: boolean;
1143
+ /** Analyzer profile the stored rows were built with; `undefined` predates profile tracking. */
1144
+ profile: string | undefined;
1145
+ }
1146
+ declare const SEARCH_STATE_TABLE = "__lunora_search_state";
1147
+ declare const migrateSearchState: (sql: SqlExec) => void;
1148
+ declare const readSearchBackfillState: (sql: SqlExec, companion: string) => BackfillState;
1149
+ declare const writeSearchBackfillState: (sql: SqlExec, companion: string, cursor: string | undefined, done: boolean, profile: string) => void;
1150
+ declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
1151
+ declare const migrateShapePokeCursor: (sql: SqlExec) => void;
1152
+ declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
1153
+ declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
1154
+ interface ShapePokeCursorRow {
1155
+ connectionId: string;
1156
+ cursor: number;
1157
+ subId: string;
1158
+ }
1159
+ declare const writeShapePokeCursors: (sql: SqlExec, rows: ReadonlyArray<ShapePokeCursorRow>) => void;
1160
+ declare const minShapePokeCursor: (sql: SqlExec) => number | undefined;
1161
+ declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
1162
+ declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
932
1163
  declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
933
1164
  type MigrationDirection = "down" | "up";
934
1165
  type MigrationStatus = "completed" | "failed" | "in_progress";
@@ -992,6 +1223,29 @@ interface DependencyTracker {
992
1223
  declare const createDependencyTracker: () => DependencyTracker;
993
1224
  declare const runSql: <Row = Record<string, unknown>>(sql: SqlExec, query: string, ...params: unknown[]) => SqlCursor<Row>;
994
1225
  declare const runDrizzle: <Row = Record<string, unknown>>(exec: SqlExec, query: SQL) => SqlCursor<Row>;
1226
+ type RangeOperandType = "boolean" | "number" | "string";
1227
+ interface WhereFragments<T> {
1228
+ binary: (reference: T, comparator: string, value: unknown) => T;
1229
+ connect: (left: T, right: T, connector: "AND" | "OR") => T;
1230
+ constant: (value: boolean) => T;
1231
+ contains: (reference: T, term: T) => T;
1232
+ inList: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget: number) => T;
1233
+ negate: (inner: T) => T;
1234
+ nullCheck: (reference: T, negated: boolean) => T;
1235
+ value: (value: unknown) => T;
1236
+ }
1237
+ type FieldRefSql<T> = (field: string) => T;
1238
+ type SerializeValue = (value: unknown, field: string) => unknown;
1239
+ interface WhereSqlStrategy<T = SQL> {
1240
+ containsExpr?: (reference: T, term: T) => T;
1241
+ fieldRef: FieldRefSql<T>;
1242
+ inList?: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => T;
1243
+ rangeTypeGuard: (field: string, type: RangeOperandType) => T;
1244
+ relationExists?: (request: unknown) => T;
1245
+ serialize: SerializeValue;
1246
+ }
1247
+ declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1248
+ declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
995
1249
  declare const quoteIdentifier: (name: string) => string;
996
1250
  declare const serializeSqlValue: (value: unknown) => unknown;
997
1251
  declare const DOC_COLUMN = "__doc__";
@@ -1005,10 +1259,16 @@ declare const AGG_KEY: Name;
1005
1259
  declare const AGG_VALUE: Name;
1006
1260
  declare const AGG_COUNT: Name;
1007
1261
  declare const aggUpsertSql: (aggTable: string, key: unknown, value: unknown, count: unknown, set: SQL) => SQL;
1008
- declare const tableColumns: (definition: TableDefinitionLike) => [string, ColumnMetaLike][];
1262
+ declare const tableColumns: (definition: TableDefinitionLike) => ReadonlyArray<readonly [string, ColumnMetaLike]>;
1009
1263
  declare const rowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
1010
1264
  declare const tryRowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
1011
1265
  declare const isFtsAvailable: (sql: SqlExec) => boolean;
1266
+ declare const WORKERD_SQLITE_LIMITS: {
1267
+ readonly boundParams: 100;
1268
+ readonly compoundSelect: 5;
1269
+ readonly likePattern: 50;
1270
+ readonly sqlTextLength: 100000;
1271
+ };
1012
1272
  type SqlEngine = "mysql" | "postgres" | "sqlite";
1013
1273
  interface RenderedSql {
1014
1274
  params: unknown[];
@@ -1016,6 +1276,79 @@ interface RenderedSql {
1016
1276
  }
1017
1277
  declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
1018
1278
  declare const param: (value: unknown) => SQL;
1279
+ declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
1280
+ declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1281
+ type DurableStreamStatus = "complete" | "error" | "running";
1282
+ interface DurableStreamRun {
1283
+ error?: string;
1284
+ errorCode?: string;
1285
+ lastSeq: number;
1286
+ startedAt: number;
1287
+ status: DurableStreamStatus;
1288
+ }
1289
+ interface DurableStreamChunk {
1290
+ dataJson: string;
1291
+ seq: number;
1292
+ }
1293
+ declare const migrateDurableStreams: (sql: SqlExec) => void;
1294
+ declare const readStreamRun: (sql: SqlExec, runKey: string) => DurableStreamRun | undefined;
1295
+ declare const claimStreamRun: (sql: SqlExec, runKey: string, startedAt: number, ttlMs: number) => boolean;
1296
+ declare const deleteStreamRun: (sql: SqlExec, runKey: string) => void;
1297
+ declare const appendStreamChunk: (sql: SqlExec, runKey: string, seq: number, dataJson: string) => void;
1298
+ declare const readStreamChunks: (sql: SqlExec, runKey: string, sinceSeq: number) => DurableStreamChunk[];
1299
+ declare const finishStreamRun: (sql: SqlExec, runKey: string, status: "complete" | "error", lastSeq: number, failure?: {
1300
+ code: string;
1301
+ message: string;
1302
+ }) => void;
1303
+ declare const trimStreamRuns: (sql: SqlExec, now: number, live: ReadonlySet<string>) => void;
1304
+ declare const MAX_DURABLE_STREAM_CHUNKS = 50000;
1305
+ declare const MAX_DURABLE_STREAM_BYTES: number;
1306
+ interface DurableStreamSink {
1307
+ readonly chunk: (chunk: {
1308
+ data: unknown;
1309
+ generation?: number;
1310
+ seq: number;
1311
+ }) => boolean;
1312
+ readonly complete: () => void;
1313
+ readonly fail: (failure: {
1314
+ code: string;
1315
+ message: string;
1316
+ }) => void;
1317
+ }
1318
+ type DurableAttachDecision = "attach" | "interrupted" | "reclaim" | "replay-terminal";
1319
+ declare const decideDurableAttach: (run: DurableStreamRun | undefined, context: {
1320
+ generation?: number;
1321
+ live?: {
1322
+ generation: number;
1323
+ };
1324
+ resuming: boolean;
1325
+ }) => DurableAttachDecision;
1326
+ interface DurableStreamAttach {
1327
+ readonly generation?: number;
1328
+ readonly iterator: (signal: AbortSignal) => AsyncIterable<unknown>;
1329
+ readonly runKey: string;
1330
+ readonly sinceChunk: number;
1331
+ readonly sink: DurableStreamSink;
1332
+ readonly ttlMs?: number;
1333
+ }
1334
+ declare class DurableStreamRunner {
1335
+ private lastTrimAt;
1336
+ private readonly runs;
1337
+ private readonly sql;
1338
+ private readonly waitUntil;
1339
+ constructor(dependencies: {
1340
+ sql: () => SqlExec;
1341
+ waitUntil?: (promise: Promise<unknown>) => void;
1342
+ });
1343
+ attach(request: DurableStreamAttach): Promise<void>;
1344
+ detach(runKey: string, sink: DurableStreamSink): void;
1345
+ isLive(runKey: string): boolean;
1346
+ private attachOrThrow;
1347
+ private produce;
1348
+ private trim;
1349
+ }
1350
+ declare const envPositiveInt: (env: unknown, key: string, fallback: number) => number;
1351
+ declare const envOptionalPositiveInt: (env: unknown, key: string) => number | undefined;
1019
1352
  interface ExternalSourceDiffResult {
1020
1353
  changes: CdcChange[];
1021
1354
  nextBaseline: Map<string, string>;
@@ -1080,6 +1413,16 @@ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => b
1080
1413
  declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
1081
1414
  applied: number;
1082
1415
  }>;
1416
+ declare const ftsRowidMapName: (companion: string) => string;
1417
+ interface FtsWriteOptions {
1418
+ guard?: SQL;
1419
+ unmappedRowids?: ReadonlyArray<number>;
1420
+ }
1421
+ declare const ftsCompanionDdl: (companion: string) => SQL[];
1422
+ declare const ftsWriteDocument: (companion: string, id: string, text: string, options?: FtsWriteOptions) => SQL[];
1423
+ declare const ftsPurgeDocument: (companion: string, id: string, options?: FtsWriteOptions) => SQL[];
1424
+ declare const ftsUnmappedPage: (companion: string, limit: number, after?: number) => SQL;
1425
+ declare const groupUnmappedRows: (rows: ReadonlyArray<Record<string, unknown>>) => Map<string, number[]>;
1083
1426
  declare const GEO_DEFAULT_PRECISION = 9;
1084
1427
  interface GeoPoint {
1085
1428
  lat: number;
@@ -1095,6 +1438,20 @@ declare const coveringGeohashes: (center: GeoPoint, radiusMeters: number) => str
1095
1438
  declare const pointInBoundingBox: (point: GeoPoint, box: GeoBoundingBox) => boolean;
1096
1439
  declare const boundingBoxCenter: (box: GeoBoundingBox) => GeoPoint;
1097
1440
  declare const boundingBoxGeohashes: (box: GeoBoundingBox) => string[];
1441
+ declare class GlobalPollTick {
1442
+ private readonly changedTables;
1443
+ private readonly reads;
1444
+ private resync;
1445
+ private skippedCount;
1446
+ constructor(changedTables?: Set<string>);
1447
+ get readCount(): number;
1448
+ get resyncRequested(): boolean;
1449
+ get skipped(): number;
1450
+ requestResync(): void;
1451
+ rows(key: string | undefined, load: () => Promise<ShapeRow[]>): Promise<ShapeRow[]>;
1452
+ shouldRead(table: string): boolean;
1453
+ }
1454
+ declare const isInternalTableName: (name: string) => boolean;
1098
1455
  declare const ADMIN_FUNCTION_PREFIX = "__lunora_admin__:";
1099
1456
  declare const RELATION_FUNCTION_PREFIX = "__lunora_relation__:";
1100
1457
  declare const FLAGS_FUNCTION_PREFIX = "__lunora_flags__:";
@@ -1105,6 +1462,8 @@ declare const ADMIN_FUNCTIONS: {
1105
1462
  readonly aiGenerateSql: "__lunora_admin__:aiGenerateSql";
1106
1463
  readonly aiTableFilter: "__lunora_admin__:aiTableFilter";
1107
1464
  readonly assignIssue: "__lunora_admin__:assignIssue";
1465
+ readonly backfillSearch: "__lunora_admin__:backfillSearch";
1466
+ readonly backfillVectors: "__lunora_admin__:backfillVectors";
1108
1467
  readonly backRelationCounts: "__lunora_admin__:backRelationCounts";
1109
1468
  readonly cdcSync: "__lunora_admin__:cdcSync";
1110
1469
  readonly clearCapturedMail: "__lunora_admin__:clearCapturedMail";
@@ -1117,6 +1476,7 @@ declare const ADMIN_FUNCTIONS: {
1117
1476
  readonly explainIssue: "__lunora_admin__:explainIssue";
1118
1477
  readonly exportShard: "__lunora_admin__:exportShard";
1119
1478
  readonly facetColumn: "__lunora_admin__:facetColumn";
1479
+ readonly findRelated: "__lunora_admin__:findRelated";
1120
1480
  readonly getAdvisories: "__lunora_admin__:getAdvisories";
1121
1481
  readonly getAdvisorProcedures: "__lunora_admin__:getAdvisorProcedures";
1122
1482
  readonly getAuditLog: "__lunora_admin__:getAuditLog";
@@ -1143,20 +1503,24 @@ declare const ADMIN_FUNCTIONS: {
1143
1503
  readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
1144
1504
  readonly importShard: "__lunora_admin__:importShard";
1145
1505
  readonly listFlags: "__lunora_admin__:listFlags";
1506
+ readonly listReactors: "__lunora_admin__:listReactors";
1146
1507
  readonly listQueues: "__lunora_admin__:listQueues";
1147
1508
  readonly lintSql: "__lunora_admin__:lintSql";
1148
1509
  readonly listTables: "__lunora_admin__:listTables";
1149
1510
  readonly listWorkflows: "__lunora_admin__:listWorkflows";
1150
1511
  readonly maskPolicies: "__lunora_admin__:maskPolicies";
1151
1512
  readonly migrationStatus: "__lunora_admin__:migrationStatus";
1513
+ readonly patchRows: "__lunora_admin__:patchRows";
1152
1514
  readonly pitrRestore: "__lunora_admin__:pitrRestore";
1153
1515
  readonly rankBefore: "__lunora_admin__:rankBefore";
1154
1516
  readonly rankPage: "__lunora_admin__:rankPage";
1155
1517
  readonly readTablePage: "__lunora_admin__:readTablePage";
1518
+ readonly rebuildCompanions: "__lunora_admin__:rebuildCompanions";
1156
1519
  readonly recordAuthEvent: "__lunora_admin__:recordAuthEvent";
1157
1520
  readonly recordContainerEvent: "__lunora_admin__:recordContainerEvent";
1158
1521
  readonly recordMail: "__lunora_admin__:recordMail";
1159
1522
  readonly recordQueueMessage: "__lunora_admin__:recordQueueMessage";
1523
+ readonly releaseShardRegistration: "__lunora_admin__:releaseShardRegistration";
1160
1524
  readonly replayQueueMessage: "__lunora_admin__:replayQueueMessage";
1161
1525
  readonly resolveIssue: "__lunora_admin__:resolveIssue";
1162
1526
  readonly rlsPolicies: "__lunora_admin__:rlsPolicies";
@@ -1226,8 +1590,12 @@ interface TablesIndexesResult {
1226
1590
  indexesByTable: Record<string, TableIndexInfo[]>;
1227
1591
  }
1228
1592
  interface ColumnMeta {
1593
+ bucket?: string;
1594
+ enumValues?: string[];
1229
1595
  isStorage?: boolean;
1230
1596
  name: string;
1597
+ nullable?: boolean;
1598
+ onDelete?: "cascade" | "restrict" | "set null";
1231
1599
  optional: boolean;
1232
1600
  pk?: boolean;
1233
1601
  ref?: string;
@@ -1324,6 +1692,12 @@ interface StudioFeaturesResult {
1324
1692
  mail: boolean;
1325
1693
  notifications: boolean;
1326
1694
  payments: boolean;
1695
+ platform?: {
1696
+ id: string;
1697
+ name: string;
1698
+ unsupported: string[];
1699
+ };
1700
+ privacy: boolean;
1327
1701
  queues: boolean;
1328
1702
  scheduler: boolean;
1329
1703
  storage: boolean;
@@ -1342,8 +1716,20 @@ interface FlagsResult {
1342
1716
  configured: boolean;
1343
1717
  flags: FlagEvaluation[];
1344
1718
  }
1719
+ interface ReactorMetadata {
1720
+ errors: number;
1721
+ lastError?: string;
1722
+ lastRanAt?: number;
1723
+ path: string;
1724
+ runs: number;
1725
+ state: "active" | "failing" | "idle";
1726
+ suppressed: number;
1727
+ tables?: ReadonlyArray<string>;
1728
+ }
1729
+ interface ReactorsResult {
1730
+ reactors: ReactorMetadata[];
1731
+ }
1345
1732
  interface WorkflowMetadata {
1346
- binding: string;
1347
1733
  className: string;
1348
1734
  exportName: string;
1349
1735
  name: string;
@@ -1357,11 +1743,12 @@ interface QueueMetadata {
1357
1743
  exportName: string;
1358
1744
  mode: "pull" | "push";
1359
1745
  name: string;
1746
+ topic?: string;
1360
1747
  }
1361
1748
  interface QueuesResult {
1362
1749
  queues: QueueMetadata[];
1363
1750
  }
1364
- type WorkflowInstanceState = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1751
+ type WorkflowInstanceState = "complete" | "errored" | "paused" | "queued" | "rollingBack" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1365
1752
  interface CreateWorkflowInstanceResult {
1366
1753
  id: string;
1367
1754
  status: WorkflowInstanceState;
@@ -1400,12 +1787,15 @@ interface TablePage {
1400
1787
  columns: string[];
1401
1788
  refs?: Record<string, string>;
1402
1789
  rows: Record<string, unknown>[];
1790
+ sqlColumns: string[];
1403
1791
  total?: number;
1404
1792
  }
1405
- type FilterOperator = "contains" | "eq" | "gt" | "gte" | "lt" | "lte" | "ne";
1793
+ type ColumnKinds = Readonly<Record<string, string>>;
1794
+ type FilterOperator = "contains" | "eq" | "gt" | "gte" | "has" | "lt" | "lte" | "ne";
1406
1795
  interface FilterClause {
1407
1796
  column: string;
1408
1797
  operator: FilterOperator;
1798
+ path?: string[];
1409
1799
  value?: unknown;
1410
1800
  }
1411
1801
  interface OrderByClause {
@@ -1413,6 +1803,7 @@ interface OrderByClause {
1413
1803
  direction: SortDirection;
1414
1804
  }
1415
1805
  interface ReadTablePageOptions {
1806
+ columnKinds?: ColumnKinds;
1416
1807
  filters?: FilterClause[];
1417
1808
  limit?: number;
1418
1809
  offset?: number;
@@ -1423,6 +1814,8 @@ interface ReadTablePageOptions {
1423
1814
  table: string;
1424
1815
  }
1425
1816
  interface SelectMatchingIdsOptions {
1817
+ after?: string;
1818
+ columnKinds?: ColumnKinds;
1426
1819
  filters?: FilterClause[];
1427
1820
  limit?: number;
1428
1821
  search?: string;
@@ -1430,6 +1823,7 @@ interface SelectMatchingIdsOptions {
1430
1823
  }
1431
1824
  interface FacetColumnOptions {
1432
1825
  column: string;
1826
+ columnKinds?: ColumnKinds;
1433
1827
  filters?: FilterClause[];
1434
1828
  limit?: number;
1435
1829
  search?: string;
@@ -1445,6 +1839,7 @@ interface FacetColumnResult {
1445
1839
  }
1446
1840
  declare const MAX_PAGE_SIZE = 500;
1447
1841
  declare const listTables: (sql: SqlExec) => TableInfo[];
1842
+ declare const isVacuousFilterClause: (clause: FilterClause) => boolean;
1448
1843
  declare const readTablePage: (sql: SqlExec, options: ReadTablePageOptions) => TablePage;
1449
1844
  declare const selectMatchingIds: (sql: SqlExec, options: SelectMatchingIdsOptions) => {
1450
1845
  hasMore: boolean;
@@ -1463,6 +1858,7 @@ interface StorageReferenceResult {
1463
1858
  declare const findStorageReferences: (sql: SqlExec, storageColumns: Record<string, string[]>, keys: string[]) => StorageReferenceResult;
1464
1859
  interface SocketAttachmentLike {
1465
1860
  admin?: boolean;
1861
+ authenticated?: boolean;
1466
1862
  subs?: Record<string, SubscriptionInfo>;
1467
1863
  }
1468
1864
  declare const summarizeSubscriptions: (attachments: SocketAttachmentLike[]) => SubscriptionsResult;
@@ -1479,18 +1875,29 @@ interface FanoutPathCounters {
1479
1875
  socketsIterated: number;
1480
1876
  totalMs: number;
1481
1877
  }
1878
+ interface ShapeProbeCounters {
1879
+ run: number;
1880
+ served: number;
1881
+ }
1882
+ interface GlobalPollCounters {
1883
+ drains: number;
1884
+ pairsSkipped: number;
1885
+ }
1482
1886
  interface FanoutMetricsResult {
1887
+ globalPoll: GlobalPollCounters;
1483
1888
  maxRelays: number;
1484
1889
  peakSubscribers: number;
1485
1890
  promoted: boolean;
1486
1891
  relayCount: number;
1487
1892
  shapePoke: FanoutPathCounters;
1893
+ shapeProbe: ShapeProbeCounters;
1488
1894
  sinceMs: number;
1489
1895
  topics: FanoutTopicStat[];
1490
1896
  totalConnections: number;
1491
1897
  whisper: FanoutPathCounters;
1492
1898
  }
1493
1899
  interface FanoutAttachmentLike {
1900
+ authenticated?: boolean;
1494
1901
  shapes?: Record<string, {
1495
1902
  name?: string;
1496
1903
  }>;
@@ -1498,6 +1905,10 @@ interface FanoutAttachmentLike {
1498
1905
  }
1499
1906
  declare const DEFAULT_FANOUT_TOPIC_LIMIT = 20;
1500
1907
  declare const createFanoutCounters: () => FanoutPathCounters;
1908
+ declare const createShapeProbeCounters: () => ShapeProbeCounters;
1909
+ declare const createGlobalPollCounters: () => GlobalPollCounters;
1910
+ declare const recordGlobalPollPass: (counters: GlobalPollCounters, drains: number, pairsSkipped: number) => GlobalPollCounters;
1911
+ declare const recordShapeProbePass: (counters: ShapeProbeCounters, run: number, served: number) => ShapeProbeCounters;
1501
1912
  declare const recordFanoutPass: (counters: FanoutPathCounters, iterated: number, delivered: number, ms: number) => FanoutPathCounters;
1502
1913
  declare const summarizeFanoutTopics: (attachments: FanoutAttachmentLike[], limit?: number) => {
1503
1914
  peakSubscribers: number;
@@ -1545,6 +1956,11 @@ declare const clearCapturedMail: (sql: SqlExec) => {
1545
1956
  declare class NotFoundError extends LunoraError {
1546
1957
  constructor(message?: string);
1547
1958
  }
1959
+ declare const operatorFields: (definition: TableDefinitionLike, patch: Record<string, unknown>) => ReadonlySet<string>;
1960
+ declare const resolvePatch: (definition: TableDefinitionLike, patch: Record<string, unknown>, current: Record<string, unknown>) => Record<string, unknown>;
1961
+ declare const patchDependsOnRow: (definition: TableDefinitionLike, patch: Record<string, unknown>) => boolean;
1962
+ declare const assertPatchAllowed: (options: PatchWriteOptions | undefined, previous: Record<string, unknown>, next: Record<string, unknown>) => void;
1963
+ declare const readPatchField: (document: Record<string, unknown>, field: string) => unknown;
1548
1964
  interface PitrStorage {
1549
1965
  getBookmarkForTime?: (time: Date | number) => Promise<string>;
1550
1966
  getCurrentBookmark?: () => Promise<string>;
@@ -1566,7 +1982,22 @@ interface PitrRestoreArgs {
1566
1982
  }
1567
1983
  declare const readBookmark: (storage: PitrStorage, time?: number | string) => Promise<PitrBookmarkResult>;
1568
1984
  declare const armRestore: (storage: PitrStorage, args: PitrRestoreArgs) => Promise<Omit<PitrRestoreResult, "restarted">>;
1569
- declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined) => OrderKey[];
1985
+ declare const tiebreakDirectionFor: (keys: ReadonlyArray<{
1986
+ direction?: string;
1987
+ }>) => SortDirection;
1988
+ declare const equalityPinnedFields: (where: undefined | WhereInput) => ReadonlySet<string>;
1989
+ declare const uniqueIndexFields: (indexes: ReadonlyArray<{
1990
+ fields: ReadonlyArray<string>;
1991
+ unique?: boolean;
1992
+ }> | undefined, shape: Record<string, ValidatorLike> | undefined) => ReadonlyArray<ReadonlyArray<string>>;
1993
+ interface OrderKeyConstraints {
1994
+ pinned?: ReadonlySet<string>;
1995
+ uniqueBy?: ReadonlyArray<ReadonlyArray<string>>;
1996
+ }
1997
+ declare const nullsFirstOf: (key: Pick<OrderKey, "direction" | "nulls">) => boolean;
1998
+ declare const nullsOrderSuffix: (nullsFirst: boolean) => string;
1999
+ declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>, constraints?: OrderKeyConstraints) => OrderKey[];
2000
+ declare const CURSOR_PREFIX = "~4";
1570
2001
  declare const encodeCursor: (record: Record<string, unknown>, keys: OrderKey[]) => string;
1571
2002
  declare const decodeCursor: (cursor: string) => unknown[];
1572
2003
  declare const buildSeekWhere: (keys: OrderKey[], cursorValues: unknown[]) => WhereInput;
@@ -1626,7 +2057,36 @@ declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: R
1626
2057
  rowId: string;
1627
2058
  sortValues: unknown[];
1628
2059
  };
2060
+ declare const rankPivotConditionSql: (column: string, value: unknown, direction: "asc" | "desc", wantLater: boolean) => SQL | undefined;
1629
2061
  declare const matchesRankStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
2062
+ declare const REACTOR_STATE_TABLE = "__reactor_state";
2063
+ interface ReactorState {
2064
+ digest: string;
2065
+ lastError?: string;
2066
+ lastRanAt: number;
2067
+ stats: ReactorStats;
2068
+ tables?: ReadonlyArray<string>;
2069
+ }
2070
+ interface ReactorStats {
2071
+ errors: number;
2072
+ runs: number;
2073
+ suppressed: number;
2074
+ }
2075
+ declare const migrateReactorState: (sql: SqlExec) => void;
2076
+ declare const readReactorState: (sql: SqlExec, path: string) => ReactorState | undefined;
2077
+ declare const listReactorStates: (sql: SqlExec) => {
2078
+ path: string;
2079
+ state: ReactorState;
2080
+ }[];
2081
+ type ReactorDispatchResult = "error" | "ran" | "suppressed";
2082
+ declare const writeReactorState: (sql: SqlExec, path: string, outcome: {
2083
+ digest?: string;
2084
+ error?: string;
2085
+ now: number;
2086
+ result: ReactorDispatchResult;
2087
+ tables?: ReadonlyArray<string>;
2088
+ }) => void;
2089
+ declare const reactorNeedsRun: (state: Pick<ReactorState, "tables"> | undefined, changed: ReadonlySet<string>) => boolean;
1630
2090
  interface ReadFootprint {
1631
2091
  onRead: (table: string, idOrScan?: string) => void;
1632
2092
  onReadRange: (range: KeyRange) => void;
@@ -1634,16 +2094,33 @@ interface ReadFootprint {
1634
2094
  tables: Set<string>;
1635
2095
  }
1636
2096
  declare const createReadFootprint: () => ReadFootprint;
2097
+ declare const UNVOUCHABLE_DEP = "!unvouchable";
2098
+ declare const markUnvouchableReads: <T extends object>(facade: T, onRead: ReadFootprint["onRead"] | undefined, methods: ReadonlyArray<string>) => T;
2099
+ declare const WHERE_FILTER: unique symbol;
2100
+ type RowPredicate = (document: Record<string, unknown>) => boolean;
2101
+ type WhereFilter = RowPredicate & {
2102
+ readonly [WHERE_FILTER]: WhereInput;
2103
+ };
2104
+ declare const whereFilter: (where: WhereInput, predicate: RowPredicate) => WhereFilter;
2105
+ declare const whereOfFilter: (predicate: RowPredicate) => undefined | WhereInput;
2106
+ declare const isPushableWhere: (where: WhereInput, shape: Readonly<Record<string, ValidatorLike>>, exactText?: boolean) => boolean;
2107
+ declare const RELATED_MAX_DEPTH = 4;
2108
+ declare const RELATED_DEFAULT_LIMIT = 50;
2109
+ declare const RELATED_MAX_LIMIT = 200;
2110
+ declare const RELATED_DEPTH_DECAY = 0.5;
2111
+ declare const deriveRelationEdges: (schema: SchemaLike) => RelationEdge[];
2112
+ type RelationGraphReader = Pick<DatabaseWriterLike, "findMany"> & Pick<Partial<DatabaseWriterLike>, "lookupById">;
2113
+ declare const findRelated: (reader: RelationGraphReader, edges: ReadonlyArray<RelationEdge>, start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
1637
2114
  declare const DEFAULT_MAX_RELATION_KEYS = 5000;
1638
2115
  interface RelationExistsMarker {
1639
2116
  childWhere: WhereInput;
1640
2117
  negated: boolean;
1641
2118
  parentTable: string;
1642
- relation: RelationDefinitionLike;
2119
+ relation: KeyedRelationDefinitionLike;
1643
2120
  }
1644
2121
  type ExistsPushMode = "always" | "auto";
1645
2122
  interface ResolveRelationPredicatesOptions {
1646
- canPushExists?: (relation: RelationDefinitionLike) => boolean;
2123
+ canPushExists?: (relation: KeyedRelationDefinitionLike) => boolean;
1647
2124
  existsPushMode?: ExistsPushMode;
1648
2125
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
1649
2126
  maxRelationKeys?: number;
@@ -1654,7 +2131,7 @@ interface ResolveRelationPredicatesOptions {
1654
2131
  tableName: string;
1655
2132
  }
1656
2133
  interface ResolveContext {
1657
- canPushExists?: (relation: RelationDefinitionLike) => boolean;
2134
+ canPushExists?: (relation: KeyedRelationDefinitionLike) => boolean;
1658
2135
  existsPushMode: ExistsPushMode;
1659
2136
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
1660
2137
  maxRelationKeys: number;
@@ -1667,15 +2144,24 @@ declare const isRelationPredicate: (value: unknown) => value is Record<string, W
1667
2144
  declare const containsRelationPredicate: (where: WhereInput, schema: ResolveContext["schema"], tableName: string) => boolean;
1668
2145
  declare const assertFlatPredicate: (where: WhereInput | undefined, schema: ResolveContext["schema"], tableName: string, op: string) => void;
1669
2146
  declare const resolveRelationPredicates: (where: WhereInput | undefined, options: ResolveRelationPredicatesOptions) => Promise<WhereInput | undefined>;
2147
+ declare const composeReadPredicate: (definition: TableDefinitionLike, args: QueryArgs, relation: Omit<ResolveRelationPredicatesOptions, "relationBaseWhere">) => Promise<{
2148
+ fetchLimit: number | undefined;
2149
+ limit: number | undefined;
2150
+ orderKeys: OrderKey[];
2151
+ predicate: WhereInput | undefined;
2152
+ }>;
1670
2153
  declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
1671
- declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask">;
2154
+ declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask"> & Pick<ResolveWithOptions, "fanOutBudget">;
1672
2155
  declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
1673
2156
  declare const distinctValues: (rows: Record<string, unknown>[], field: string) => unknown[];
1674
2157
  declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
1675
2158
  interface ApplyOnDeleteOptions {
1676
2159
  deletedId: string;
1677
2160
  deletedReference: (references: string) => unknown;
1678
- findHolders: (holderTable: string, field: string, value: unknown) => Promise<Record<string, unknown>[]>;
2161
+ findHolders: (holderTable: string, field: string, value: unknown, page: {
2162
+ limit: number;
2163
+ select?: ReadonlyArray<string>;
2164
+ }) => Promise<Record<string, unknown>[]>;
1679
2165
  onCascade: (holderTable: string, id: string) => Promise<void>;
1680
2166
  onRestrict: (message: string) => never;
1681
2167
  onSetNull: (holderTable: string, id: string, field: string) => Promise<void>;
@@ -1685,7 +2171,15 @@ interface ApplyOnDeleteOptions {
1685
2171
  tableName: string;
1686
2172
  }
1687
2173
  declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
1688
- declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, tolerateStoredNull?: boolean) => void;
2174
+ interface RowValidatorOptions {
2175
+ only?: ReadonlySet<string>;
2176
+ previous?: () => Readonly<Record<string, unknown>> | undefined;
2177
+ supplied?: Readonly<Record<string, unknown>>;
2178
+ tolerateStoredNull?: boolean;
2179
+ trusted?: boolean;
2180
+ }
2181
+ declare const applyInsertDefaults: (definition: TableDefinitionLike, document: Record<string, unknown>, auth: ServerDefaultContextLike["auth"]) => Record<string, unknown>;
2182
+ declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, options?: RowValidatorOptions) => Record<string, unknown>;
1689
2183
  interface ShapeRowOp {
1690
2184
  key: string;
1691
2185
  op: "delete" | "insert" | "update";
@@ -1693,6 +2187,8 @@ interface ShapeRowOp {
1693
2187
  value?: Record<string, unknown>;
1694
2188
  }
1695
2189
  interface ShapePokePart {
2190
+ baseCheckpoint?: number;
2191
+ reset?: boolean;
1696
2192
  rowsPatch: ShapeRowOp[];
1697
2193
  shapeId: string;
1698
2194
  }
@@ -1727,15 +2223,18 @@ declare const clampPromotionThresholds: (tUp: number, tDownRaw: number) => Promo
1727
2223
  declare const relayCountFor: (subscribers: number, perRelayCapacity: number, maxRelays: number) => number;
1728
2224
  interface RelayAttach {
1729
2225
  relayIndex: number;
2226
+ seq?: number;
1730
2227
  type: "relay_attach";
1731
2228
  }
1732
2229
  interface RelayDetach {
1733
2230
  relayIndex: number;
2231
+ seq?: number;
1734
2232
  type: "relay_detach";
1735
2233
  }
1736
2234
  interface RelayFrame {
1737
2235
  cursor?: number;
1738
2236
  epoch?: string;
2237
+ exceptConnectionId?: string;
1739
2238
  frame: string;
1740
2239
  originRelay?: number;
1741
2240
  topic: string;
@@ -1753,6 +2252,12 @@ interface RelayShapeSubscribe {
1753
2252
  type: "relay_shape_subscribe";
1754
2253
  userId?: string;
1755
2254
  }
2255
+ interface RelayShapeUnsubscribe {
2256
+ connectionId: string;
2257
+ relayIndex: number;
2258
+ subId?: string;
2259
+ type: "relay_shape_unsubscribe";
2260
+ }
1756
2261
  interface RelayShapeSeed {
1757
2262
  cursor?: number;
1758
2263
  epoch?: string;
@@ -1772,44 +2277,85 @@ interface RelayShapePoke {
1772
2277
  targetConnectionId?: string;
1773
2278
  type: "relay_shape_poke";
1774
2279
  }
1775
- type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayShapePoke | RelayShapeSubscribe;
1776
- declare const DEFAULT_MAX_RELAYS = 8;
1777
- interface RelayStub {
1778
- fetch: (url: string, init?: RequestInit) => Promise<Response>;
2280
+ interface RelayRoomEvent {
2281
+ attachment: Pick<SocketAttachment, "connectionId" | "context" | "identity" | "ip" | "userId">;
2282
+ connectionId: string;
2283
+ data?: unknown;
2284
+ kind: "join" | "leave" | "message";
2285
+ relayIndex: number;
2286
+ topic: string;
2287
+ type: "relay_room_event";
2288
+ }
2289
+ interface RelayRoomVerdict {
2290
+ admitted: boolean;
2291
+ }
2292
+ interface LiveSocketControlCall {
2293
+ action: unknown;
2294
+ callerId: string;
2295
+ connectionId: string;
2296
+ identityExpiry?: number;
2297
+ key: string;
2298
+ seq?: number;
2299
+ subscriptionId: string;
1779
2300
  }
1780
- interface RelayNamespaceLike {
1781
- get: (id: unknown) => RelayStub;
1782
- getByName?: (name: string) => RelayStub;
1783
- idFromName: (name: string) => unknown;
2301
+ interface RelayLiveControl {
2302
+ control: LiveSocketControlCall;
2303
+ type: "relay_live_control";
1784
2304
  }
2305
+ interface RelayLiveFrame {
2306
+ frame: string;
2307
+ key: string;
2308
+ topic: string;
2309
+ type: "relay_live_frame";
2310
+ }
2311
+ type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayLiveControl | RelayLiveFrame | RelayRoomEvent | RelayShapePoke | RelayShapeSubscribe | RelayShapeUnsubscribe;
2312
+ declare const RELAY_SIGNATURE_HEADER = "x-lunora-relay-sig";
2313
+ declare const siblingSecretOf: (env: unknown) => string | undefined;
2314
+ declare const signSiblingBody: (secret: string, body: string) => Promise<string>;
2315
+ declare const verifySiblingBody: (env: unknown, supplied: null | string, raw: string) => Promise<boolean>;
2316
+ interface SiblingStub {
2317
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
2318
+ }
2319
+ declare const stubByName: (value: unknown, name: string, jurisdiction?: string) => SiblingStub | undefined;
2320
+ declare const DEFAULT_MAX_RELAYS = 8;
1785
2321
  interface RelayHost {
1786
2322
  buildShapeDiff: (resolved: ResolvedShape, fromCursor: number, toCursor: number) => ShapeRowOp[];
1787
2323
  computeOpLogShapeSeed: (shape: ShapeSubscriptionQuery, resolved: ResolvedShape) => {
1788
2324
  baseCheckpoint: number | undefined;
1789
2325
  cursor: number;
1790
2326
  epoch: string | undefined;
2327
+ reset: boolean;
1791
2328
  rowsPatch: ShapeRowOp[];
1792
2329
  };
1793
2330
  currentCdcEpoch: () => string | undefined;
2331
+ deliverLiveLocal: (topic: string, key: string, frame: string) => number;
1794
2332
  deliverWhisperLocal: (topic: string, frame: string, exclude: undefined | ShardSocketLike) => number;
1795
2333
  doName: () => string | undefined;
1796
2334
  env: () => unknown;
1797
2335
  getWebSockets: () => ShardSocketLike[];
2336
+ liveControl: (control: LiveSocketControlCall) => Promise<Response>;
1798
2337
  maskMetadata: () => MaskPoliciesResult;
1799
2338
  nextPokeId: () => string;
1800
2339
  readAttachment: (ws: ShardSocketLike) => SocketAttachment;
1801
2340
  recordShapePokeFanout: (iterated: number, delivered: number, elapsedMs: number) => void;
2341
+ relayRoomEvent: (event: RelayRoomEvent) => Promise<RelayRoomVerdict>;
1802
2342
  resolveShape: (name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity) => ResolvedShape | undefined;
1803
2343
  rlsMetadata: () => RlsPoliciesResult;
1804
2344
  shardBinding: () => string | undefined;
2345
+ shardJurisdiction: () => string | undefined;
1805
2346
  sql: () => SqlExec;
1806
2347
  }
2348
+ interface RelayPokeDelivery {
2349
+ delivered: number;
2350
+ matched: number;
2351
+ }
1807
2352
  declare abstract class RelayLink {
1808
2353
  protected readonly host: RelayHost;
1809
2354
  protected readonly roleId: {
1810
2355
  ownerKey: string;
1811
2356
  relayIndex?: number;
1812
2357
  };
2358
+ private lastSequence;
1813
2359
  protected constructor(host: RelayHost, roleId: {
1814
2360
  ownerKey: string;
1815
2361
  relayIndex?: number;
@@ -1817,81 +2363,194 @@ declare abstract class RelayLink {
1817
2363
  handleControl(request: Request): Promise<Response>;
1818
2364
  maxRelays(): number;
1819
2365
  protected canAddressSiblings(): boolean;
1820
- protected relayNamespace(): RelayNamespaceLike | undefined;
2366
+ protected isAdmitted(ws: ShardSocketLike): boolean;
2367
+ protected siblingStub(targetName: string): SiblingStub | undefined;
2368
+ protected bindingName(): string | undefined;
2369
+ protected nextRelaySeq(): number;
1821
2370
  protected postRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<void>;
1822
2371
  protected requestRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<Response | undefined>;
1823
- abstract forwardWhisper(topic: string, frame: string): Promise<void>;
2372
+ abstract forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
1824
2373
  abstract onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
1825
2374
  abstract seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | undefined | {
1826
2375
  code: string;
1827
2376
  message: string;
1828
2377
  }>;
1829
- abstract announce(): Promise<void>;
2378
+ abstract announce(): Promise<boolean>;
1830
2379
  abstract announceDrain(closing: ShardSocketLike): Promise<void>;
2380
+ abstract releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
1831
2381
  abstract relayCount(): number;
1832
2382
  abstract isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
1833
- protected abstract onAttach(index: number): void;
1834
- protected abstract onDetach(index: number): void;
2383
+ abstract minShapeCursor(): number | undefined;
2384
+ protected abstract onAttach(index: number, seq: number | undefined): boolean;
2385
+ protected abstract onDetach(index: number, seq: number | undefined): boolean;
2386
+ protected abstract onLiveControl(control: LiveSocketControlCall): Promise<Response>;
1835
2387
  protected abstract onWhisperFrame(message: RelayFrame): Promise<void>;
2388
+ protected abstract refusesAsIdle(): boolean;
1836
2389
  protected abstract onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
1837
- protected abstract onShapePoke(poke: RelayShapePoke): number;
2390
+ protected abstract onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2391
+ protected abstract onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
1838
2392
  }
1839
2393
  declare class OwnerRelay extends RelayLink {
1840
2394
  private readonly shapeUniformCache;
1841
2395
  private relaySetCache;
1842
- private readonly relayShapeRegistry;
1843
- private readonly relayShapeProxies;
2396
+ private liveGrantRelayCache;
2397
+ private relayTablesReady;
2398
+ private readonly relaySeqMarks;
2399
+ private readonly pendingSubscribeRelays;
2400
+ private registryCache;
2401
+ private recordedBinding;
1844
2402
  private promotionState;
1845
2403
  constructor(host: RelayHost, ownerKey: string);
1846
- forwardWhisper(topic: string, frame: string): Promise<void>;
2404
+ forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
2405
+ forwardLiveControl(call: LiveSocketControlCall): Promise<Response | undefined>;
2406
+ forwardLiveFrame(topic: string, key: string, frame: string): Promise<void>;
1847
2407
  onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
1848
2408
  seedRelayShape(): Promise<"ok" | undefined | {
1849
2409
  code: string;
1850
2410
  message: string;
1851
2411
  }>;
1852
- announce(): Promise<void>;
2412
+ announce(): Promise<boolean>;
1853
2413
  announceDrain(): Promise<void>;
2414
+ releaseRelayShapes(): Promise<void>;
1854
2415
  relayCount(): number;
2416
+ minShapeCursor(): number | undefined;
1855
2417
  isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
1856
- protected onAttach(index: number): void;
1857
- protected onDetach(index: number): void;
2418
+ protected onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2419
+ protected onAttach(index: number, seq: number | undefined): boolean;
2420
+ protected onDetach(index: number, seq: number | undefined): boolean;
2421
+ protected refusesAsIdle(): boolean;
2422
+ protected onLiveControl(control: LiveSocketControlCall): Promise<Response>;
1858
2423
  protected onWhisperFrame(message: RelayFrame): Promise<void>;
1859
2424
  protected onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
1860
- protected onShapePoke(): number;
2425
+ protected onShapePoke(): RelayPokeDelivery;
2426
+ private relaySeqMark;
2427
+ private recordRelaySeq;
2428
+ private acceptRelaySeq;
1861
2429
  private buildShapePoke;
1862
2430
  private multicastShapePokes;
2431
+ private multicastToRelays;
1863
2432
  private proxyShapePokes;
2433
+ private proxyToRelay;
1864
2434
  private buildShapeSeedFrames;
1865
- private ensureRelayTable;
2435
+ private ensureRelayTables;
2436
+ protected bindingName(): string | undefined;
2437
+ private relayShapes;
2438
+ private rewindShapeCursor;
1866
2439
  private ownerRelaySet;
2440
+ private liveGrantRelaySet;
2441
+ private recordLiveGrantRelay;
1867
2442
  private addRelayToSet;
2443
+ private forwardToRelay;
2444
+ private requestDroppingIdle;
1868
2445
  private removeRelayFromSet;
1869
2446
  private probeShapeRelayUniform;
1870
2447
  private tableHasAnyMask;
2448
+ private liveControlAnswer;
1871
2449
  }
1872
2450
  declare class RelayMember extends RelayLink {
1873
2451
  private relayAnnounced;
1874
- private readonly shapeRelayMemos;
2452
+ private readonly liveControlSeqs;
2453
+ private pendingAnnounce;
2454
+ private announceGeneration;
2455
+ private pendingDetach;
2456
+ private relayMemoCache;
2457
+ private readonly shapeControl;
1875
2458
  constructor(host: RelayHost, ownerKey: string, relayIndex: number);
1876
2459
  forwardWhisper(topic: string, frame: string): Promise<void>;
2460
+ forwardRoomEvent(event: Omit<RelayRoomEvent, "relayIndex" | "type">): Promise<boolean>;
1877
2461
  onFlush(): Promise<void>;
1878
2462
  seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | {
1879
2463
  code: string;
1880
2464
  message: string;
1881
2465
  }>;
1882
- announce(): Promise<void>;
2466
+ announce(): Promise<boolean>;
1883
2467
  announceDrain(closing: ShardSocketLike): Promise<void>;
2468
+ releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
1884
2469
  relayCount(): number;
1885
2470
  isShapeRelayUniform(): boolean;
1886
- protected onAttach(): void;
1887
- protected onDetach(): void;
2471
+ minShapeCursor(): number | undefined;
2472
+ protected onAttach(): boolean;
2473
+ protected refusesAsIdle(): boolean;
2474
+ protected onDetach(): boolean;
2475
+ protected onLiveControl(control: LiveSocketControlCall): Promise<Response>;
1888
2476
  protected onWhisperFrame(): Promise<void>;
1889
2477
  protected onShapeSubscribe(): RelayShapeSeed;
1890
- protected onShapePoke(poke: RelayShapePoke): number;
2478
+ protected onShapeUnsubscribe(): void;
2479
+ protected onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
2480
+ private queueShapeControl;
2481
+ private relayMemos;
2482
+ private connectionMemos;
1891
2483
  private recordRelayShapeMemo;
2484
+ private forgetRelayShapeMemos;
1892
2485
  private deliverShapePoke;
2486
+ private pokeSocketShapes;
1893
2487
  }
1894
2488
  declare const createRelayLink: (host: RelayHost) => OwnerRelay | RelayMember | undefined;
2489
+ declare const REGION_HINTS: readonly ["wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"];
2490
+ type RegionHint = (typeof REGION_HINTS)[number];
2491
+ type ReplicaReadiness = "fresh" | "stale" | "unavailable";
2492
+ interface ShardSiblingHost {
2493
+ doName: () => string | undefined;
2494
+ env: () => unknown;
2495
+ shardBinding: () => string | undefined;
2496
+ shardJurisdiction: () => string | undefined;
2497
+ sql: () => SqlExec;
2498
+ }
2499
+ interface ReplicaOwnerHost extends ShardSiblingHost {
2500
+ exportRows: () => Promise<ExportRow[]>;
2501
+ ownerCursor: () => number | undefined;
2502
+ ownerEpoch: () => string | undefined;
2503
+ ownerFloor: () => number | undefined;
2504
+ readChanges: (sinceSeq: number, limit: number) => {
2505
+ changes: CdcChange[];
2506
+ cursor: number;
2507
+ };
2508
+ rowCount: () => number;
2509
+ }
2510
+ interface ReplicaFollowerHost extends ShardSiblingHost {
2511
+ applyChanges: (changes: ReadonlyArray<CdcChange>) => Promise<number>;
2512
+ exportRows: () => Promise<ExportRow[]>;
2513
+ importRows: (rows: ReadonlyArray<ExportRow>) => Promise<{
2514
+ errors: ReadonlyArray<unknown>;
2515
+ }>;
2516
+ reportError?: (scope: string, error: unknown) => void;
2517
+ transactionLimits: () => Partial<TransactionLimits>;
2518
+ }
2519
+ declare const handleReplicaControl: (host: ReplicaOwnerHost, request: Request) => Promise<Response>;
2520
+ declare class ShardReplica {
2521
+ private readonly host;
2522
+ readonly ownerKey: string;
2523
+ readonly region: RegionHint;
2524
+ private divergent;
2525
+ private inFlight;
2526
+ constructor(host: ReplicaFollowerHost, ownerKey: string, region: RegionHint);
2527
+ ensureFresh(minSeq?: number): Promise<ReplicaReadiness>;
2528
+ appliedSeq(): number;
2529
+ isDivergent(): boolean;
2530
+ private advance;
2531
+ private isCaughtUp;
2532
+ private catchUp;
2533
+ private verdict;
2534
+ private recover;
2535
+ private whenOwnerUnreachable;
2536
+ private applyPage;
2537
+ private applyAtomically;
2538
+ private fetchSnapshot;
2539
+ private resnapshot;
2540
+ private overWriteBudget;
2541
+ private bootstrap;
2542
+ private isFreshEnough;
2543
+ private pull;
2544
+ private request;
2545
+ }
2546
+ declare const createReplicaLink: (host: ReplicaFollowerHost) => ShardReplica | undefined;
2547
+ declare const gateReplicaDispatch: (replica: ShardReplica, request: Request, functionPath: string) => Promise<Response | undefined>;
2548
+ declare const REPROJECTION_MIGRATION_PREFIX = "__lunora_reproject__";
2549
+ declare const reprojectionMigrationId: (table: string) => string;
2550
+ declare const reprojectableFields: (definition: TableDefinitionLike) => string[];
2551
+ declare const reprojectionTables: (schema: SchemaLike) => string[];
2552
+ declare const countLegacyRows: (sql: SqlExec, table: string, fields: ReadonlyArray<string>) => number;
2553
+ declare const buildReprojectionMigration: (id: string, schema: SchemaLike, sql: SqlExec) => DataMigrationLike | undefined;
1895
2554
  declare const RLS_UNWRAP_SYMBOL: symbol;
1896
2555
  declare class RlsRequiredError extends LunoraError {
1897
2556
  readonly table: string;
@@ -1908,7 +2567,7 @@ interface GuardableSchema {
1908
2567
  }
1909
2568
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
1910
2569
  type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
1911
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
2570
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds, relationEdges?: ReadonlyArray<RelationEdge>) => W;
1912
2571
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
1913
2572
  interface SchemaVersionRow {
1914
2573
  appliedAt: number;
@@ -1919,8 +2578,24 @@ interface SchemaVersionRow {
1919
2578
  declare const recordSchemaVersion: (sql: SqlExec, hash: string, snapshotJson: string, now?: number) => boolean;
1920
2579
  declare const readSchemaHistory: (sql: SqlExec) => SchemaVersionRow[];
1921
2580
  declare const readSchemaVersion: (sql: SqlExec, hash: string) => SchemaVersionRow | undefined;
2581
+ declare const readDeployInfo: (rawEnv: unknown) => DeployInfo;
1922
2582
  declare const isDevEnvironment: (rawEnv: unknown) => boolean;
1923
2583
  declare const buildSettings: (rawEnv: unknown) => SettingsResult;
2584
+ declare class ShapeDiffCache {
2585
+ private readonly keyScans;
2586
+ private readonly memberProbes;
2587
+ private run;
2588
+ private served;
2589
+ get probesRun(): number;
2590
+ get probesServed(): number;
2591
+ changedKeys(rangeKey: string, load: () => CdcChangeKey[]): ReadonlyArray<CdcChangeKey>;
2592
+ members(resolved: ResolvedShape, rangeKey: string, load: () => Map<string, Record<string, unknown>>): ReadonlyMap<string, Record<string, unknown>>;
2593
+ private getOrLoad;
2594
+ }
2595
+ declare const createShapeDiffCache: () => ShapeDiffCache;
2596
+ declare const globalShapeReadKey: (resolved: ResolvedShape, identity: SubscriptionIdentity) => string | undefined;
2597
+ type ReadShapeCdcKeys = (sql: SqlExec, table: string, sinceSeq: number, upTo: number) => CdcChangeKey[];
2598
+ declare const buildShapeDiff: (sql: SqlExec, resolved: ResolvedShape, sinceSeq: number, upTo: number, cache: ShapeDiffCache, readKeys?: ReadShapeCdcKeys) => ShapeRowOp[];
1924
2599
  interface ShardRunnerOptions {
1925
2600
  handlers?: {
1926
2601
  handleAlarm?: () => Promise<void>;
@@ -1936,7 +2611,7 @@ declare class ShardRunner {
1936
2611
  socketFor(raw: unknown): ShardSocketLike;
1937
2612
  sockets(tag?: string): SocketHandle[];
1938
2613
  background(work: Promise<unknown>): boolean;
1939
- runInTransaction<T>(work: () => Promise<T>): Promise<T>;
2614
+ runInTransaction<T>(work: () => Promise<T>, onCommitted?: () => void): Promise<T>;
1940
2615
  handleFetch(request: Request): Promise<Response>;
1941
2616
  handleAlarm(): Promise<void>;
1942
2617
  }
@@ -1962,6 +2637,11 @@ interface SqlDiagnostic {
1962
2637
  source: "gate" | "plan" | "syntax";
1963
2638
  }
1964
2639
  declare const lintReadonlySql: (sql: SqlExec, query: string) => SqlLintResult;
2640
+ declare const BIGINT_KEY_DIGITS = 39;
2641
+ declare const bigintSqlKey: (value: bigint) => string;
2642
+ declare const decodeBigintSqlKey: (raw: string) => bigint | undefined;
2643
+ declare const float64SqlKey: (value: number) => string;
2644
+ declare const decodeFloat64SqlKey: (raw: string) => number | undefined;
1965
2645
  declare const subscriptionListDeltas: (previousJson: string, nextResult: unknown, table: string, frames?: string[]) => MutationDelta[] | undefined;
1966
2646
  interface FrameSink {
1967
2647
  send: (data: string) => void;
@@ -1970,7 +2650,17 @@ interface DrainableSink {
1970
2650
  readonly bufferedAmount?: unknown;
1971
2651
  }
1972
2652
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1973
- declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string, lastMutationId?: number) => boolean;
2653
+ interface SubscriptionFrameInput {
2654
+ cursorSuffix: string;
2655
+ lastMutationId?: number;
2656
+ nextResult: unknown;
2657
+ pageDeltas?: boolean;
2658
+ previousJson?: string;
2659
+ snapshotJson: string;
2660
+ subId: string;
2661
+ table: string;
2662
+ }
2663
+ declare const subscriptionFrames: (input: SubscriptionFrameInput) => string[];
1974
2664
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1975
2665
  interface SubscriptionReadFootprint {
1976
2666
  ranges?: Map<string, KeyRange[]>;
@@ -1998,13 +2688,31 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
1998
2688
  hasMore: boolean;
1999
2689
  ids: string[];
2000
2690
  };
2001
- type FieldRefSql = (field: string) => SQL;
2002
- type SerializeValue = (value: unknown) => unknown;
2003
- interface WhereSqlStrategy {
2004
- fieldRef: FieldRefSql;
2005
- likeContains?: (reference: SQL, term: SQL) => SQL;
2006
- relationExists?: (request: unknown) => SQL;
2007
- serialize: SerializeValue;
2691
+ declare const nextTtlExpiry: (sql: SqlExec, spec: TtlSweepSpec) => number | undefined;
2692
+ declare const VECTOR_BACKFILL_MAX_PAGES = 20;
2693
+ interface VectorBackfillTarget {
2694
+ profile: string;
2695
+ table: string;
2696
+ }
2697
+ interface VectorBackfillProgress {
2698
+ done: boolean;
2699
+ error?: string;
2700
+ failed: number;
2701
+ failedIds: string[];
2702
+ pages: number;
2703
+ rows: number;
2008
2704
  }
2009
- declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2010
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2705
+ type VectorPageSync = (table: string, rows: ReadonlyArray<{
2706
+ doc: Record<string, unknown>;
2707
+ id: string;
2708
+ }>) => Promise<ReadonlyArray<{
2709
+ error: unknown;
2710
+ id: string;
2711
+ }>>;
2712
+ type OrderedAfterWrites = <T, U>(read: () => T, work: (value: T) => Promise<U>) => Promise<U>;
2713
+ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<VectorBackfillTarget>, sync: VectorPageSync, options: {
2714
+ maxPages?: number;
2715
+ ordered: OrderedAfterWrites;
2716
+ restart?: boolean;
2717
+ }) => Promise<VectorBackfillProgress>;
2718
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };