@lunora/shard-engine 1.0.0-alpha.20 → 1.0.0-alpha.201

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 (169) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +1 -1
  3. package/dist/conformance/index.mjs +1 -1
  4. package/dist/index.d.mts +1042 -227
  5. package/dist/index.d.ts +1042 -227
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs +14 -0
  8. package/dist/packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs +1 -0
  9. package/dist/packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs +1 -0
  10. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
  11. package/dist/packem_shared/AGG_COUNT-dVi3FAjZ.mjs +1 -0
  12. package/dist/packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs +8 -0
  13. package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
  14. package/dist/packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs +18 -0
  15. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs +7 -0
  16. package/dist/packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs +4 -0
  17. package/dist/packem_shared/CURSOR_PREFIX-rOdoinP8.mjs +1 -0
  18. package/dist/packem_shared/CompanionMemo-BXU5vfak.mjs +1 -0
  19. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  20. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs +31 -0
  21. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-B0nxRm8q.mjs +1 -0
  22. package/dist/packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs +8 -0
  23. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-VU44O5kq.mjs +1 -0
  24. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs +1 -0
  25. package/dist/packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs +1 -0
  26. package/dist/packem_shared/DurableStreamRunner-MMlV5qKQ.mjs +1 -0
  27. package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
  28. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs +7 -0
  29. package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
  30. package/dist/packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs +7 -0
  31. package/dist/packem_shared/MAIL_RETENTION-DMolrLYt.mjs +18 -0
  32. package/dist/packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs +5 -0
  33. package/dist/packem_shared/MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs +1 -0
  34. package/dist/packem_shared/NotUniqueError-BezPdXmB.mjs +1 -0
  35. package/dist/packem_shared/QUEUE_TABLE-C-goXtGd.mjs +17 -0
  36. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
  37. package/dist/packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs +28 -0
  38. package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs +1 -0
  39. package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
  40. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs +1 -0
  41. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
  42. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs +1 -0
  43. package/dist/packem_shared/ReactiveCache-BG9z3FE9.mjs +1 -0
  44. package/dist/packem_shared/SCAN_DEP-B4Uu4g7l.mjs +1 -0
  45. package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs +18 -0
  46. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs +6 -0
  47. package/dist/packem_shared/SEARCH_STATE_TABLE-D7w8mRsm.mjs +1 -0
  48. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs +8 -0
  49. package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
  50. package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
  51. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs +1 -0
  52. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +1 -0
  53. package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
  54. package/dist/packem_shared/adminTokenExists-CQ0qedmu.mjs +8 -0
  55. package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
  56. package/dist/packem_shared/appendStreamChunk-BZYgGE9Y.mjs +17 -0
  57. package/dist/packem_shared/applyInsertDefaults-nXMzGae5.mjs +1 -0
  58. package/dist/packem_shared/archiveCdcSegment-Cr8oGLfB.mjs +4 -0
  59. package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
  60. package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
  61. package/dist/packem_shared/backfillAggregateIndexes-BwCpPW7h.mjs +1 -0
  62. package/dist/packem_shared/buildIndexRange-BTChxh3k.mjs +1 -0
  63. package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
  64. package/dist/packem_shared/buildReprojectionMigration-B8aEpETD.mjs +1 -0
  65. package/dist/packem_shared/buildSettings-CFkvTaHx.mjs +1 -0
  66. package/dist/packem_shared/buildShapeDiff-CdLJTijm.mjs +1 -0
  67. package/dist/packem_shared/clearMemoryTables-aMRERF0w.mjs +1 -0
  68. package/dist/packem_shared/compileWhereSql-TgKZIvWM.mjs +1 -0
  69. package/dist/packem_shared/computeRankPage-B6umzbg4.mjs +1 -0
  70. package/dist/packem_shared/constant-time-equal-BRh9yUCr.mjs +1 -0
  71. package/dist/packem_shared/createCompanionSync-DO92CQek.mjs +1 -0
  72. package/dist/packem_shared/createReplicaLink-DtqXBi-0.mjs +7 -0
  73. package/dist/packem_shared/createSystemReader-BSCxr8Qs.mjs +1 -0
  74. package/dist/packem_shared/ctx-db-relay-shapes-DBobAek2.mjs +17 -0
  75. package/dist/packem_shared/ctx-db-search-state-CPKPy8N6.mjs +1 -0
  76. package/dist/packem_shared/defineEngineContractSuite-BxYuR8CF.mjs +1 -0
  77. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
  78. package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
  79. package/dist/packem_shared/do-sql-105TONaE.mjs +1 -0
  80. package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
  81. package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
  82. package/dist/packem_shared/estimate-bytes-C-C35VXL.mjs +1 -0
  83. package/dist/packem_shared/exportShardRows-CZh4wrvI.mjs +1 -0
  84. package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +1 -0
  85. package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +1 -0
  86. package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
  87. package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
  88. package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
  89. package/dist/packem_shared/isSoftDeleted-BBWKE0Sm.mjs +9 -0
  90. package/dist/packem_shared/isTtlExpired-DNxmZA6e.mjs +1 -0
  91. package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
  92. package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
  93. package/dist/packem_shared/materializeExternalRows-CHPRx8fu.mjs +1 -0
  94. package/dist/packem_shared/mergeChangedKeys-DPKhen6e.mjs +1 -0
  95. package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
  96. package/dist/packem_shared/relay-CKEdfUjH.mjs +1 -0
  97. package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +1 -0
  98. package/dist/packem_shared/runShardMigrations-Bc7PsQhM.mjs +5 -0
  99. package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
  100. package/dist/packem_shared/selectShapeMembers-Dqx_m7BF.mjs +1 -0
  101. package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
  102. package/dist/packem_shared/stubByName-DQSivmvb.mjs +1 -0
  103. package/dist/packem_shared/where-sql-BjY4rnqb.mjs +1 -0
  104. package/package.json +6 -5
  105. package/dist/packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs +0 -1
  106. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
  107. package/dist/packem_shared/AGG_COUNT-CqQLWpb4.mjs +0 -1
  108. package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
  109. package/dist/packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs +0 -8
  110. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
  111. package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
  112. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
  113. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-sPcXaWFW.mjs +0 -1
  114. package/dist/packem_shared/DEFAULT_MAX_RELAYS-CPBmX1FO.mjs +0 -1
  115. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs +0 -1
  116. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs +0 -1
  117. package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
  118. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
  119. package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
  120. package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
  121. package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
  122. package/dist/packem_shared/NotUniqueError-BItFDsAw.mjs +0 -1
  123. package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
  124. package/dist/packem_shared/RANK_TIEBREAK-DYDRmLKH.mjs +0 -1
  125. package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
  126. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +0 -1
  127. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
  128. package/dist/packem_shared/ReactiveCache-Cu8IfE1M.mjs +0 -1
  129. package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
  130. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
  131. package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
  132. package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
  133. package/dist/packem_shared/aggregateTableName-DV-K7ft2.mjs +0 -1
  134. package/dist/packem_shared/applyOnDelete-BB6tr2G0.mjs +0 -1
  135. package/dist/packem_shared/applySelect-i17LYhIU.mjs +0 -1
  136. package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +0 -1
  137. package/dist/packem_shared/backfillAggregateIndexes-tK0jrl43.mjs +0 -1
  138. package/dist/packem_shared/base64-fKomMf5D.mjs +0 -1
  139. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
  140. package/dist/packem_shared/buildPokeFrames-CqxaN8_H.mjs +0 -1
  141. package/dist/packem_shared/buildReprojectionMigration-Ctl4r84d.mjs +0 -1
  142. package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
  143. package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
  144. package/dist/packem_shared/computeRankPage-CRFgJbuz.mjs +0 -1
  145. package/dist/packem_shared/createCompanionSync-Gp-AesYj.mjs +0 -1
  146. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
  147. package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
  148. package/dist/packem_shared/ctx-db-companions-CAJOSdN-.mjs +0 -1
  149. package/dist/packem_shared/defineEngineContractSuite-CZccUN4c.mjs +0 -1
  150. package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
  151. package/dist/packem_shared/do-sql-1Yi1_Yq0.mjs +0 -1
  152. package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +0 -1
  153. package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
  154. package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
  155. package/dist/packem_shared/isSoftDeleted-Bo-y3DOe.mjs +0 -9
  156. package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
  157. package/dist/packem_shared/materializeExternalRows-DcCENzpV.mjs +0 -1
  158. package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
  159. package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
  160. package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
  161. package/dist/packem_shared/runShardMigrations-n2dKcH5E.mjs +0 -5
  162. package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
  163. package/dist/packem_shared/selectExpiredIds-C6nQK7E2.mjs +0 -1
  164. package/dist/packem_shared/selectShapeMemberIds-BdBcbrUP.mjs +0 -1
  165. package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +0 -1
  166. package/dist/packem_shared/sql-projection-jfoe331H.mjs +0 -1
  167. package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
  168. package/dist/packem_shared/stableWireKey-l3cjIt-9.mjs +0 -1
  169. package/dist/packem_shared/wire-codec-Dsy70M3Q.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,46 @@ 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;
56
+ completedAt?: number;
29
57
  enqueuedAt: number;
30
- functionPath: string;
58
+ error?: string;
59
+ functionPath?: string;
31
60
  id: string;
61
+ pool?: string;
32
62
  scheduledFor: number;
33
63
  shardKey?: string;
64
+ state?: "canceled" | "failed" | "pending" | "running" | "succeeded";
65
+ workflow?: string;
34
66
  }
35
67
  interface StorageMetadata {
36
68
  contentType?: string;
@@ -86,6 +118,90 @@ interface WhereInput {
86
118
  OR?: WhereInput[];
87
119
  }
88
120
  declare const RELATION_EXISTS_KEY = "__relationExists";
121
+ interface SubscriptionQuery {
122
+ args?: Record<string, unknown>;
123
+ functionPath?: string;
124
+ sinceClaims?: string;
125
+ sinceEpoch?: string;
126
+ sinceSeq?: number;
127
+ table?: string;
128
+ }
129
+ interface ShapeSubscriptionQuery {
130
+ args?: Record<string, unknown>;
131
+ name: string;
132
+ sinceEpoch?: string;
133
+ sinceSeq?: number;
134
+ }
135
+ interface SubscriptionEnvelope {
136
+ caps?: string[];
137
+ clientId?: string;
138
+ context?: Record<string, unknown>;
139
+ data?: unknown;
140
+ generation?: number;
141
+ id: string;
142
+ query?: SubscriptionQuery;
143
+ shape?: {
144
+ args?: Record<string, unknown>;
145
+ name: string;
146
+ };
147
+ sinceCheckpoint?: number;
148
+ sinceChunk?: number;
149
+ sinceClaims?: string;
150
+ sinceEpoch?: string;
151
+ token?: string;
152
+ topic?: string;
153
+ type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
154
+ }
155
+ interface RpcRequest {
156
+ args?: Record<string, unknown>;
157
+ functionPath: string;
158
+ }
159
+ interface SocketAttachment {
160
+ admin?: boolean;
161
+ adminBinding?: string;
162
+ authenticated?: boolean;
163
+ broadcastSubs?: Record<string, string>;
164
+ clientId?: string;
165
+ connected?: boolean;
166
+ connectionId?: string;
167
+ context?: Record<string, unknown>;
168
+ deliveryPermits?: Record<string, {
169
+ epoch: number;
170
+ scope: string;
171
+ }>;
172
+ expiresAt?: number;
173
+ identity?: Record<string, unknown>;
174
+ ip?: string;
175
+ liveGrants?: Record<string, string>;
176
+ pageDeltas?: boolean;
177
+ pendingSince?: number;
178
+ refreshBatch?: boolean;
179
+ revalidateAt?: number;
180
+ shapes?: Record<string, ShapeSubscriptionQuery>;
181
+ socketFunction?: string;
182
+ socketPath?: string;
183
+ subs: Record<string, SubscriptionQuery>;
184
+ userId?: string;
185
+ whispers?: string[];
186
+ }
187
+ interface ResolvedShape {
188
+ columns?: ReadonlyArray<string>;
189
+ effectiveWhere?: WhereInput;
190
+ global?: boolean;
191
+ table: string;
192
+ }
193
+ interface SubscriptionIdentity {
194
+ identity?: Record<string, unknown>;
195
+ ip?: string;
196
+ userId?: string;
197
+ }
198
+ interface ShardSocketLike {
199
+ readonly bufferedAmount?: number;
200
+ close?: (code?: number, reason?: string) => void;
201
+ deserializeAttachment?: () => unknown;
202
+ send: (data: string) => void;
203
+ serializeAttachment?: (value: unknown) => void;
204
+ }
89
205
  type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
90
206
  interface AggregateIndexDefinitionLike {
91
207
  readonly by?: ReadonlyArray<string>;
@@ -137,6 +253,11 @@ interface ColumnMetaLike {
137
253
  interface ValidatorLike {
138
254
  readonly _meta?: {
139
255
  readonly column?: ColumnMetaLike;
256
+ readonly inner?: ValidatorLike;
257
+ readonly members?: ReadonlyArray<ValidatorLike>;
258
+ readonly shape?: Readonly<Record<string, ValidatorLike>>;
259
+ readonly tableName?: string;
260
+ readonly value?: unknown;
140
261
  };
141
262
  readonly kind?: string;
142
263
  readonly parse?: (value: unknown) => unknown;
@@ -144,7 +265,7 @@ interface ValidatorLike {
144
265
  type TriggerTimingLike = "after" | "before";
145
266
  type TriggerOpLike = "delete" | "insert" | "update";
146
267
  interface SchedulableWorkflowReferenceLike {
147
- readonly binding?: string;
268
+ readonly className?: string;
148
269
  readonly isLunoraWorkflow: true;
149
270
  readonly name?: string;
150
271
  }
@@ -178,11 +299,18 @@ interface SchemaLike {
178
299
  readonly rlsMode?: "required";
179
300
  readonly tables: Record<string, TableDefinitionLike>;
180
301
  }
302
+ type PatchVerifier = (previous: Record<string, unknown>, next: Record<string, unknown>) => boolean;
303
+ interface PatchWriteOptions {
304
+ verify?: PatchVerifier;
305
+ }
181
306
  interface TableDefinitionLike {
182
307
  readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
308
+ readonly commitOrderedMode?: boolean;
309
+ readonly dropStalePatchesMode?: boolean;
183
310
  readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
184
311
  readonly indexes: ReadonlyArray<IndexDefinitionLike>;
185
312
  readonly isPublic?: boolean;
313
+ readonly memoryMode?: boolean;
186
314
  readonly rankIndexes?: ReadonlyArray<RankIndexDefinitionLike>;
187
315
  readonly relationMap?: Record<string, RelationDefinitionLike>;
188
316
  readonly searchIndexes?: ReadonlyArray<SearchIndexDefinitionLike>;
@@ -200,13 +328,25 @@ interface TableDefinitionLike {
200
328
  field: string;
201
329
  };
202
330
  }
203
- interface RelationDefinitionLike {
331
+ interface KeyedRelationDefinitionLike {
204
332
  readonly field: string;
205
333
  readonly kind: "many" | "one";
206
334
  readonly onDelete?: OnDeleteActionLike;
207
335
  readonly references: string;
208
336
  readonly table: string;
337
+ readonly through?: never;
338
+ }
339
+ interface RelationThroughLike {
340
+ readonly from: string;
341
+ readonly table: string;
342
+ readonly to: string;
209
343
  }
344
+ interface ThroughRelationDefinitionLike {
345
+ readonly kind: "many";
346
+ readonly table: string;
347
+ readonly through: RelationThroughLike;
348
+ }
349
+ type RelationDefinitionLike = KeyedRelationDefinitionLike | ThroughRelationDefinitionLike;
210
350
  type OnDeleteActionLike = "cascade" | "restrict" | "set null";
211
351
  interface NestedWith {
212
352
  limit?: number;
@@ -219,13 +359,11 @@ interface WithInput {
219
359
  [relationName: string]: NestedWith | Record<string, true> | boolean | undefined;
220
360
  _count?: Record<string, true>;
221
361
  }
222
- interface ApplyOnDeleteOptions$1 {
223
- database: DatabaseWriterLike;
224
- relation: RelationDefinitionLike;
225
- row: Record<string, unknown>;
226
- tableName: string;
362
+ interface FanOutBudget {
363
+ remaining: number;
227
364
  }
228
365
  interface ResolveWithOptions {
366
+ fanOutBudget?: FanOutBudget;
229
367
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
230
368
  groupedCounter: (tableName: string, whereField: string, values: unknown[], policyWhere?: WhereInput) => Promise<Map<unknown, number>>;
231
369
  parents: Record<string, unknown>[];
@@ -243,12 +381,19 @@ interface ResolveWithResult {
243
381
  rows: Record<string, unknown>[];
244
382
  }
245
383
  type SortDirection = "asc" | "desc";
246
- type OrderByInput = Record<string, SortDirection>;
384
+ type NullPlacement = "first" | "last";
385
+ type OrderByInput = Record<string, SortDirection | {
386
+ nulls: NullPlacement;
387
+ sort: SortDirection;
388
+ }>;
247
389
  interface QueryArgs {
248
390
  baseWhere?: WhereInput;
391
+ consistency?: "primary";
249
392
  cursor?: null | string;
393
+ endCursor?: null | string;
250
394
  includeDeleted?: boolean;
251
395
  limit?: number;
396
+ omitContinueCursor?: boolean;
252
397
  orderBy?: OrderByInput[];
253
398
  relationBaseWhere?: (table: string) => undefined | WhereInput;
254
399
  relationMask?: RelationMask;
@@ -264,15 +409,60 @@ interface CrossShardReadArgs {
264
409
  with?: WithInput;
265
410
  }
266
411
  type RelationMask = (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
412
+ interface QueryPlan {
413
+ params: unknown[];
414
+ plan: string[];
415
+ sql: string;
416
+ }
267
417
  interface QueryPage {
268
418
  continueCursor: null | string;
269
419
  isDone: boolean;
270
420
  page: Record<string, unknown>[];
271
421
  splitCursor?: null | string;
422
+ splitRequired?: boolean;
423
+ }
424
+ interface RelationEdge {
425
+ readonly array: boolean;
426
+ readonly column: string;
427
+ readonly name: string;
428
+ readonly sourceTable: string;
429
+ readonly targetTable: string;
430
+ }
431
+ interface RelatedStartReference {
432
+ id: string;
433
+ table: string;
434
+ }
435
+ type RelatedStart = (Record<string, unknown> & {
436
+ _id: string;
437
+ }) | RelatedStartReference;
438
+ type RelatedDirection = "both" | "in" | "out";
439
+ interface RelatedOptions {
440
+ cursor?: null | string;
441
+ depth?: number;
442
+ direction?: RelatedDirection;
443
+ edges?: ReadonlyArray<string>;
444
+ limit?: number;
445
+ relationBaseWhere?: (table: string) => undefined | WhereInput;
446
+ relationMask?: RelationMask;
447
+ }
448
+ interface RelatedNode {
449
+ depth: number;
450
+ document: Record<string, unknown>;
451
+ path: ReadonlyArray<string>;
452
+ pathIds: ReadonlyArray<string>;
453
+ score: number;
454
+ table: string;
455
+ }
456
+ interface RelatedPage {
457
+ continueCursor: null | string;
458
+ isDone: boolean;
459
+ nodes: RelatedNode[];
272
460
  }
273
461
  interface OrderKey {
274
462
  direction: SortDirection;
275
463
  field: string;
464
+ nullable: boolean;
465
+ nulls?: NullPlacement;
276
466
  }
277
467
  interface RestrictableQueryOptions {
278
468
  baseWhere?: WhereInput;
@@ -401,17 +591,15 @@ interface IndexRangeBuilderLike {
401
591
  lte: (field: string, value: unknown) => IndexRangeBuilderLike;
402
592
  }
403
593
  type BroadcastDelta = (delta: MutationDelta) => void;
404
- type ReadHook = (table: string, idOrScan?: string) => void;
594
+ type ReadHook = (table: string, idOrScan?: string, exact?: boolean) => void;
405
595
  interface LifecycleEvent {
406
596
  connectionId: string;
407
597
  context?: Record<string, unknown>;
408
598
  shardKey: string;
409
599
  userId: string | null;
410
600
  }
411
- interface LifecycleDispatchInfo {
601
+ interface LifecycleDispatchInfo extends SubscriptionIdentity {
412
602
  event: LifecycleEvent;
413
- identity: Record<string, unknown> | undefined;
414
- userId: string | undefined;
415
603
  }
416
604
  interface MutationDelta {
417
605
  indexKeys?: ReadonlyArray<IndexKeyEntry>;
@@ -423,9 +611,18 @@ interface MutationDelta {
423
611
  interface DatabaseWriterLike {
424
612
  aggregate: (tableName: string, options: AggregateOptions) => Promise<AggregateResult>;
425
613
  asId?: (tableName: string, id: string) => string;
614
+ assertPatchAllowed?: (table: string, id: string) => Promise<void>;
615
+ cdcChangedTables?: (sinceSeq: number, options?: {
616
+ cursorOnly?: boolean;
617
+ }) => Promise<{
618
+ cursor: number;
619
+ floor?: number;
620
+ tables: string[];
621
+ } | undefined>;
426
622
  count: (tableName: string, where?: RestrictableQueryOptions | WhereInput) => Promise<number>;
427
- delete: (id: string, expectedTable?: string, options?: {
623
+ delete: (table: string, id: string, options?: {
428
624
  hard?: boolean;
625
+ skipOnDelete?: boolean;
429
626
  }) => Promise<void>;
430
627
  deleteAll?: (tableName: string, options?: {
431
628
  chunkSize?: number;
@@ -433,20 +630,22 @@ interface DatabaseWriterLike {
433
630
  }) => Promise<{
434
631
  deleted: number;
435
632
  }>;
436
- deleteMany?: (ids: ReadonlyArray<string>, options?: {
633
+ deleteMany?: (table: string, ids: ReadonlyArray<string>, options?: {
437
634
  limit?: number;
438
- }, expectedTable?: string) => Promise<{
635
+ }) => Promise<{
439
636
  deleted: number;
440
637
  }>;
638
+ deleteRereadTables?: ReadonlySet<string>;
441
639
  deleteWhere?: (tableName: string, where: WhereInput, options?: {
442
640
  limit?: number;
443
641
  }) => Promise<{
444
642
  deleted: number;
445
643
  }>;
644
+ explain: (tableName: string, args?: QueryArgs) => Promise<QueryPlan>;
446
645
  findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
447
646
  findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
448
647
  findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
449
- get: (id: string, expectedTable?: string) => Promise<Record<string, unknown> | null>;
648
+ get: (table: string, id: string) => Promise<Record<string, unknown> | null>;
450
649
  groupBy: (tableName: string, options: GroupByOptions) => Promise<ReadonlyArray<GroupByEntry>>;
451
650
  insert: (tableName: string, document: Record<string, unknown>, options?: {
452
651
  allowExplicitId?: boolean;
@@ -460,18 +659,27 @@ interface DatabaseWriterLike {
460
659
  allowExplicitId?: boolean;
461
660
  limit?: number;
462
661
  }) => Promise<string[]>;
662
+ inTransaction?: () => boolean;
463
663
  lookupById?: (id: string, expectedTable?: string) => Promise<null | {
464
664
  row: Record<string, unknown>;
465
665
  tableName: string;
466
666
  }>;
467
667
  normalizeId: (tableName: string, id: string) => null | string;
468
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
469
- patchMany?: (patches: ReadonlyArray<{
668
+ patch: (table: string, id: string, patch: Record<string, unknown>, options?: PatchWriteOptions) => Promise<void>;
669
+ patchIf?: (tableName: string, id: string, args: {
670
+ patch: Record<string, unknown>;
671
+ verify?: PatchVerifier;
672
+ where: WhereInput;
673
+ }) => Promise<{
674
+ applied: boolean;
675
+ doc: Record<string, unknown> | null;
676
+ }>;
677
+ patchMany?: (table: string, patches: ReadonlyArray<{
470
678
  id: string;
471
679
  patch: Record<string, unknown>;
472
680
  }>, options?: {
473
681
  limit?: number;
474
- }, expectedTable?: string) => Promise<{
682
+ }) => Promise<{
475
683
  patched: number;
476
684
  }>;
477
685
  patchWhere?: (tableName: string, args: {
@@ -487,10 +695,14 @@ interface DatabaseWriterLike {
487
695
  rankBefore?: (tableName: string, indexName: string, options: RankBeforeOptions) => Promise<RankBeforeResult>;
488
696
  rankPage: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<RankPage>;
489
697
  rankPageRows?: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<ShardRankPageResult>;
490
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string, options?: {
698
+ related?: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
699
+ relationEdges?: ReadonlyArray<RelationEdge>;
700
+ relationWrites?: RelationWriteMap;
701
+ replace: (table: string, id: string, document: Record<string, unknown>, options?: {
491
702
  allowExplicitId?: boolean;
492
703
  }) => Promise<void>;
493
- restore?: (id: string, expectedTable?: string) => Promise<void>;
704
+ restore?: (table: string, id: string) => Promise<void>;
705
+ softDeleteFields?: ReadonlyMap<string, string>;
494
706
  system?: SystemDatabaseReader;
495
707
  wipeShard?: (options?: {
496
708
  chunkSize?: number;
@@ -515,17 +727,25 @@ interface ExportShardArgs {
515
727
  batchSize?: number;
516
728
  tables?: ReadonlyArray<string>;
517
729
  }
730
+ type ImportConflictMode = "replace" | "skip";
731
+ interface ImportRow extends ExportRow {
732
+ op?: string;
733
+ }
518
734
  interface ImportShardArgs {
519
- rows: ReadonlyArray<ExportRow>;
735
+ deletes?: boolean;
736
+ dryRun?: boolean;
737
+ onConflict?: ImportConflictMode;
738
+ rows: ReadonlyArray<ImportRow>;
520
739
  startLine?: number;
521
740
  }
522
741
  interface ImportShardResult {
523
742
  conflicts: number;
743
+ deleted: number;
524
744
  errors: ImportError[];
525
745
  inserted: Record<string, number>;
746
+ replaced: number;
526
747
  }
527
748
  declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
528
- declare const exportShardTable: (writer: DatabaseWriterLike, table: string, batchSize?: number) => AsyncGenerator<ExportRow, void, undefined>;
529
749
  declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
530
750
  declare const validateImportRow: (schema: SchemaLike, table: string, record: Record<string, unknown>) => string | undefined;
531
751
  declare const importShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportShardArgs) => Promise<ImportShardResult>;
@@ -534,47 +754,21 @@ interface ExportShardAdminArgs {
534
754
  tables?: ReadonlyArray<string>;
535
755
  }
536
756
  interface ImportShardAdminArgs {
537
- rows: ReadonlyArray<ExportRow>;
757
+ deletes: boolean;
758
+ dryRun: boolean;
759
+ onConflict: ImportConflictMode;
760
+ rows: ReadonlyArray<ImportRow>;
538
761
  startLine?: number;
539
762
  }
540
763
  declare const parseExportShardArgs: (args: Record<string, unknown>) => ExportShardAdminArgs;
541
764
  declare const parseImportShardArgs: (args: Record<string, unknown>) => ImportShardAdminArgs;
542
- declare const matchesStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
543
- declare const normalizeCountArgument: (argument: RestrictableQueryOptions | undefined | WhereInput) => RestrictableQueryOptions;
544
- declare const AGGREGATE_SQL_FUNCTION: Record<string, string>;
545
- declare const aggregateSqlFunction: (op: string) => string;
546
- declare const throwingScheduler: SchedulerLike;
547
- declare const aggregateTableName: (table: string, indexName: string) => string;
548
- declare const coerceAggregateNumber: (value: unknown) => number | undefined;
549
- interface AggregateTally {
550
- count: number;
551
- value: null | number;
765
+ declare const ADMIN_TOKEN_SCOPES: readonly ["migrations"];
766
+ type AdminTokenScope = (typeof ADMIN_TOKEN_SCOPES)[number];
767
+ declare const clearCompanionSignatures: (sql: SqlExec) => void;
768
+ declare class CompanionMemo {
769
+ readonly verified: Set<string>;
770
+ invalidate(): void;
552
771
  }
553
- declare const foldAggregateTally: (tallies: Map<string, AggregateTally>, encoded: string, index: AggregateIndexDefinitionLike, record: Record<string, unknown>) => void;
554
- declare const readAggregateValue: (op: string, row: {
555
- count: number;
556
- value: null | number;
557
- } | undefined) => null | number;
558
- declare const encodeAggregateKey: (by: ReadonlyArray<string>, source: Record<string, unknown>) => string;
559
- declare class CountRlsUnsupportedError extends LunoraError {
560
- constructor(table?: string);
561
- }
562
- declare const mergeWhere: (left: undefined | WhereInput, right: undefined | WhereInput) => undefined | WhereInput;
563
- declare const planAggregateLookup: (index: AggregateIndexDefinitionLike, requestedWhere: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
564
- declare const selectIndexForCount: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
565
- index: AggregateIndexDefinitionLike;
566
- key: Record<string, unknown>;
567
- };
568
- declare const selectIndexForAggregate: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string, requestedWhere: Record<string, unknown> | undefined) => undefined | {
569
- index: AggregateIndexDefinitionLike;
570
- key: Record<string, unknown>;
571
- };
572
- declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string | undefined, by: ReadonlyArray<string>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
573
- index: AggregateIndexDefinitionLike;
574
- partial: Record<string, unknown>;
575
- };
576
- declare const stableStringify: (value: unknown) => string;
577
- declare const stableWireKey: (value: unknown) => string;
578
772
  interface CacheEntry {
579
773
  bytes: number;
580
774
  deps: Set<string>;
@@ -600,6 +794,7 @@ declare class ReactiveCache {
600
794
  private readonly maxBytes;
601
795
  private readonly now;
602
796
  private monotonic;
797
+ private generation;
603
798
  constructor(options?: ReactiveCacheOptions);
604
799
  run<R>(key: string, deps: Set<string>, run: () => Promise<R>, ranges?: () => ReadonlyArray<KeyRange>): Promise<R>;
605
800
  invalidate(table: string, id: string, indexKeys?: ReadonlyArray<IndexKeyEntry>): string[];
@@ -627,28 +822,45 @@ declare class ReactiveCache {
627
822
  }
628
823
  declare const reactiveCacheKey: (functionPath: string, args: Record<string, unknown>, identity: null | string) => string;
629
824
  interface TransactionLimits {
825
+ maxReadBytes: number;
630
826
  maxReadRows: number;
631
827
  maxWrittenBytes: number;
632
828
  maxWrittenRows: number;
633
829
  }
634
830
  interface TransactionHeadroom {
831
+ readBytes: number;
635
832
  readRows: number;
833
+ remainingReadBytes: number;
636
834
  remainingReadRows: number;
637
835
  remainingWrittenBytes: number;
638
836
  remainingWrittenRows: number;
639
837
  writtenBytes: number;
640
838
  writtenRows: number;
641
839
  }
840
+ type TransactionLimitKind = "readBytes" | "readRows" | "writtenBytes" | "writtenRows";
841
+ interface TransactionLimitWarning {
842
+ kind: TransactionLimitKind;
843
+ limit: number;
844
+ used: number;
845
+ }
642
846
  declare const DEFAULT_TRANSACTION_LIMITS: TransactionLimits;
643
847
  declare class TransactionHeadroomTracker {
848
+ private readBytes;
644
849
  private readRows;
645
850
  private writtenRows;
646
851
  private writtenBytes;
647
852
  private readonly limits;
648
- constructor(limits?: Partial<TransactionLimits>);
853
+ private readonly onNearLimit;
854
+ private readonly warned;
855
+ private readonly chargedDocuments;
856
+ constructor(limits?: Partial<TransactionLimits>, onNearLimit?: (warning: TransactionLimitWarning) => void);
649
857
  recordRead(count: number): void;
858
+ recordReadBytes(bytes: number): void;
859
+ recordDocumentRead(key: string, bytes: number): void;
860
+ beginReadWindow(): void;
650
861
  recordWrite(row: unknown): void;
651
862
  headroom(): TransactionHeadroom;
863
+ private check;
652
864
  }
653
865
  interface RunTriggersOptions {
654
866
  ctx: TriggerContextLike;
@@ -660,12 +872,18 @@ interface RunTriggersOptions {
660
872
  }
661
873
  declare const runTriggers: (options: RunTriggersOptions) => Promise<void>;
662
874
  declare const hasTrigger: (schema: SchemaLike, tableName: string, op: TriggerOpLike) => boolean;
875
+ interface SearchBackfillProgress {
876
+ done: boolean;
877
+ pages: number;
878
+ }
663
879
  declare const backfillAggregateIndexes: (sql: SqlExec, schema: SchemaLike) => void;
664
880
  declare const backfillRankIndexes: (sql: SqlExec, schema: SchemaLike) => void;
665
881
  declare const backfillSearchIndexesForTable: (sql: SqlExec, tableName: string, definition: {
666
882
  searchIndexes?: ReadonlyArray<SearchIndexDefinitionLike>;
667
883
  }) => void;
668
- declare const backfillSearchIndexes: (sql: SqlExec, schema: SchemaLike) => void;
884
+ declare const backfillSearchIndexes: (sql: SqlExec, schema: SchemaLike, options?: {
885
+ maxPages?: number;
886
+ }) => SearchBackfillProgress;
669
887
  declare const CDC_LOG_TABLE = "__cdc_log";
670
888
  interface CdcChange {
671
889
  doc?: Record<string, unknown>;
@@ -675,19 +893,35 @@ interface CdcChange {
675
893
  table: string;
676
894
  ts: number;
677
895
  }
678
- declare const migrateCdcLog: (sql: SqlExec) => void;
896
+ declare const CDC_LOG_TABLE_SEQ_INDEX = "__cdc_log_table_seq";
897
+ declare const migrateCdcLog: (sql: SqlExec, options?: {
898
+ rowHistoryIndex?: boolean;
899
+ }) => void;
679
900
  declare const appendCdcChange: (sql: SqlExec, ts: number, table: string, id: string, op: CdcChange["op"], doc: Record<string, unknown> | undefined) => void;
680
901
  declare const readCdcChanges: (sql: SqlExec, options?: {
681
902
  limit?: number;
682
903
  sinceSeq?: number;
683
- tables?: ReadonlySet<string>;
684
904
  }) => {
685
905
  changes: CdcChange[];
686
906
  cursor: number;
687
907
  };
688
- declare const trimCdcChanges: (sql: SqlExec, throughSeq: number) => void;
908
+ declare const cdcTouchesTables: (sql: SqlExec, sinceSeq: number, tables: ReadonlySet<string>) => boolean;
909
+ declare const cdcCanVouchFor: (sql: SqlExec, deps: ReadonlySet<string>) => boolean;
910
+ interface CdcChangeKey {
911
+ id: string;
912
+ op: CdcChange["op"];
913
+ seq: number;
914
+ }
915
+ declare const readCdcChangeKeys: (sql: SqlExec, table: string, sinceSeq: number, upTo: number) => CdcChangeKey[];
916
+ declare const trimCdcChanges: (sql: SqlExec, throughSeq: number, maxRows: number) => void;
917
+ declare const compactCdcDocs: (sql: SqlExec, throughSeq: number, maxRows: number) => void;
918
+ declare const cdcSeqLeavingRows: (sql: SqlExec, keep: number) => number | undefined;
689
919
  declare const readCdcCursor: (sql: SqlExec) => number;
920
+ declare const cursorBelowRetainedFloor: (floor: number | undefined, sinceSeq: number) => boolean;
921
+ declare const cdcTrimmedError: (floor: number, sinceSeq: number, scope: "global" | "shard") => LunoraError;
922
+ declare const cdcForkedError: (cursor: number, sinceSeq: number, scope: "global" | "shard", epoch?: string) => LunoraError;
690
923
  declare const minCdcSeq: (sql: SqlExec) => number | undefined;
924
+ declare const minCdcReplayableSeq: (sql: SqlExec) => number | undefined;
691
925
  declare const CDC_META_TABLE = "__cdc_meta";
692
926
  declare const migrateCdcMeta: (sql: SqlExec) => void;
693
927
  declare const readCdcEpoch: (sql: SqlExec) => string;
@@ -697,12 +931,6 @@ declare const CLIENT_WATERMARK_TABLE = "__client_watermark";
697
931
  declare const migrateClientWatermark: (sql: SqlExec) => void;
698
932
  declare const readClientWatermark: (sql: SqlExec, identity: string, clientId: string) => number;
699
933
  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
934
  declare const IDEMPOTENCY_TABLE = "__idempotency";
707
935
  interface IdempotentRecord {
708
936
  resultJson: string;
@@ -714,61 +942,32 @@ declare const writeIdempotent: (sql: SqlExec, identity: string, mutationId: stri
714
942
  declare const trimIdempotent: (sql: SqlExec, olderThanTs: number) => void;
715
943
  declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
716
944
  cdc?: boolean;
945
+ deferBlockedUniqueIndexes?: boolean;
717
946
  schemaSnapshot?: {
718
947
  hash: string;
719
948
  json: string;
720
949
  };
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;
950
+ }) => ReadonlyArray<string>;
755
951
  interface ShapeRow {
756
952
  doc: Record<string, unknown>;
757
953
  id: string;
758
954
  }
759
955
  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>;
956
+ declare const selectShapeMembers: (sql: SqlExec, table: string, effectiveWhere: WhereInput | undefined, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
761
957
  interface SqlExec {
762
958
  exec: <Row = Record<string, unknown>>(sql: string, ...params: unknown[]) => SqlCursor<Row>;
763
959
  }
764
960
  interface SqlCursor<Row> extends Iterable<Row> {
961
+ readonly columnNames?: string[];
765
962
  one: () => Row;
963
+ raw?: () => IterableIterator<unknown[]>;
766
964
  toArray: () => Row[];
767
965
  }
768
966
  type IndexUseHook = (table: string, indexName: string, kind: "geo" | "index" | "rank" | "search") => void;
769
967
  type Clock = () => number;
770
968
  type IdGenerator = () => string;
771
969
  declare const assertValidClientId: (clientId: string) => void;
970
+ declare const assertStorableRowId: (id: string) => void;
772
971
  interface WriteEvent {
773
972
  doc?: Record<string, unknown>;
774
973
  id: string;
@@ -778,18 +977,26 @@ interface WriteEvent {
778
977
  type WriteHook = (event: WriteEvent) => Promise<void> | void;
779
978
  interface CtxDbOptions {
780
979
  auth?: ServerDefaultContextLike["auth"];
980
+ baselineSeq?: () => number | undefined;
781
981
  broadcast?: BroadcastDelta;
782
982
  cache?: ReactiveCache;
783
983
  cdc?: boolean;
784
984
  clock?: Clock;
985
+ companionMemo?: CompanionMemo;
785
986
  enforceRls?: boolean;
786
987
  globalDb?: DatabaseWriterLike;
787
988
  headroom?: TransactionHeadroomTracker;
788
989
  idGenerator?: IdGenerator;
990
+ inTransaction?: () => boolean;
789
991
  maxRelationKeys?: number;
790
992
  onIndexUse?: IndexUseHook;
791
993
  onRead?: ReadHook;
792
994
  onReadRange?: (range: KeyRange) => void;
995
+ onStalePatchDropped?: (event: {
996
+ fields: string[];
997
+ id: string;
998
+ table: string;
999
+ }) => void;
793
1000
  onWrite?: WriteHook;
794
1001
  relationExistsPushDown?: "always" | "auto" | "never";
795
1002
  scheduler?: SchedulerLike;
@@ -802,7 +1009,66 @@ declare class NotUniqueError extends LunoraError {
802
1009
  constructor(message?: string);
803
1010
  }
804
1011
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
1012
+ declare const assertNoExplicitUndefined: (op: "patch" | "patchIf" | "replace", document: Record<string, unknown>) => void;
1013
+ declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
805
1014
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
1015
+ declare const ADMIN_TOKEN_TABLE = "__lunora_admin_tokens__";
1016
+ interface AdminTokenSummary {
1017
+ createdAt: number;
1018
+ expiresAt?: number;
1019
+ lastUsedAt?: number;
1020
+ name: string;
1021
+ scopes: AdminTokenScope[];
1022
+ }
1023
+ declare const createAdminTokenRecord: (sql: SqlExec, record: {
1024
+ createdAt: number;
1025
+ digest: string;
1026
+ expiresAt?: number;
1027
+ name: string;
1028
+ scopes?: ReadonlyArray<AdminTokenScope>;
1029
+ }) => boolean;
1030
+ declare const listAdminTokens: (sql: SqlExec) => AdminTokenSummary[];
1031
+ declare const revokeAdminTokenRecord: (sql: SqlExec, name: string, createdAt: number) => boolean;
1032
+ declare const verifyAdminTokenDigest: (sql: SqlExec, name: string, digest: string, now: number) => undefined | {
1033
+ createdAt: number;
1034
+ expiresAt?: number;
1035
+ scopes: AdminTokenScope[];
1036
+ };
1037
+ declare const adminTokenExists: (sql: SqlExec, name: string) => boolean;
1038
+ declare const matchesStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
1039
+ declare const normalizeCountArgument: (argument: RestrictableQueryOptions | undefined | WhereInput) => RestrictableQueryOptions;
1040
+ declare const AGGREGATE_SQL_FUNCTION: Record<string, string>;
1041
+ declare const aggregateSqlFunction: (op: string) => string;
1042
+ declare const throwingScheduler: SchedulerLike;
1043
+ declare const aggregateTableName: (table: string, indexName: string) => string;
1044
+ declare const coerceAggregateNumber: (value: unknown) => number | undefined;
1045
+ interface AggregateTally {
1046
+ count: number;
1047
+ value: null | number;
1048
+ }
1049
+ declare const foldAggregateTally: (tallies: Map<string, AggregateTally>, encoded: string, index: AggregateIndexDefinitionLike, record: Record<string, unknown>) => void;
1050
+ declare const readAggregateValue: (op: string, row: {
1051
+ count: number;
1052
+ value: null | number;
1053
+ } | undefined) => null | number;
1054
+ declare const encodeAggregateKey: (by: ReadonlyArray<string>, source: Record<string, unknown>) => string;
1055
+ declare class CountRlsUnsupportedError extends LunoraError {
1056
+ constructor(table?: string);
1057
+ }
1058
+ declare const mergeWhere: (left: undefined | WhereInput, right: undefined | WhereInput) => undefined | WhereInput;
1059
+ declare const planAggregateLookup: (index: AggregateIndexDefinitionLike, requestedWhere: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
1060
+ declare const selectIndexForCount: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
1061
+ index: AggregateIndexDefinitionLike;
1062
+ key: Record<string, unknown>;
1063
+ };
1064
+ declare const selectIndexForAggregate: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string, requestedWhere: Record<string, unknown> | undefined) => undefined | {
1065
+ index: AggregateIndexDefinitionLike;
1066
+ key: Record<string, unknown>;
1067
+ };
1068
+ declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string | undefined, by: ReadonlyArray<string>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
1069
+ index: AggregateIndexDefinitionLike;
1070
+ partial: Record<string, unknown>;
1071
+ };
806
1072
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
807
1073
  interface AuditEntry {
808
1074
  detail?: Record<string, unknown>;
@@ -825,68 +1091,23 @@ declare const readAuditLog: (sql: SqlExec, options?: {
825
1091
  limit?: number;
826
1092
  sinceSeq?: number;
827
1093
  }) => 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
- }
1094
+ interface CdcArchiveScope {
1095
+ epoch: string;
1096
+ shard: string;
1097
+ }
1098
+ declare const readCdcArchivedThrough: (sql: SqlExec) => number;
1099
+ declare const writeCdcArchivedThrough: (sql: SqlExec, seq: number) => void;
1100
+ declare const archiveCdcSegment: (bucket: R2BucketLike, scope: CdcArchiveScope, changes: CdcChange[]) => Promise<void>;
1101
+ declare const cdcArchiveRewound: (bucket: R2BucketLike, scope: CdcArchiveScope, archivedThrough: number) => Promise<boolean>;
1102
+ declare const readArchivedCdcChanges: (bucket: R2BucketLike, scope: CdcArchiveScope, sinceSeq: number, limit: number | undefined) => Promise<{
1103
+ changes: CdcChange[];
1104
+ cursor: number;
1105
+ } | undefined>;
1106
+ declare const COMMIT_SEQ_TABLE = "__commit_seq";
1107
+ declare const COMMIT_SEQ_FIELD = "_commitSeq";
1108
+ declare const migrateCommitSeq: (sql: SqlExec) => void;
1109
+ declare const readCommitSeq: (sql: SqlExec) => number;
1110
+ declare const allocateCommitSeq: (sql: SqlExec) => number;
890
1111
  interface CompanionSyncDeps {
891
1112
  broadcast: (delta: MutationDelta) => void;
892
1113
  indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
@@ -897,6 +1118,7 @@ interface CompanionSyncDeps {
897
1118
  recordCdc: (table: string, id: string, op: "delete" | "insert" | "update", doc?: Record<string, unknown>) => void;
898
1119
  schema: SchemaLike;
899
1120
  sql: SqlExec;
1121
+ verified?: Set<string>;
900
1122
  }
901
1123
  interface CompanionSync {
902
1124
  ensureBackfilledForTable: (tableName: string) => void;
@@ -910,6 +1132,19 @@ interface CompanionSync {
910
1132
  syncSearch: (tableName: string, id: string, document: Record<string, unknown> | undefined, previous?: Record<string, unknown>) => void;
911
1133
  }
912
1134
  declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
1135
+ declare const GLOBAL_SHAPE_SNAPSHOT_TABLE = "__global_shape_snapshot";
1136
+ declare const migrateGlobalShapeSnapshot: (sql: SqlExec) => void;
1137
+ declare const readGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => Map<string, string> | undefined;
1138
+ declare const writeGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string, snapshot: Map<string, string>) => void;
1139
+ declare const deleteGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => void;
1140
+ declare const deleteGlobalShapeSnapshotsForConnection: (sql: SqlExec, connectionId: string) => void;
1141
+ declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
1142
+ declare const memoryTableNames: (schema: SchemaLike) => string[];
1143
+ declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
1144
+ declare const resolveRankSeekTuple: (options: {
1145
+ after?: RankPageRowKey;
1146
+ cursor?: null | string;
1147
+ }) => unknown[] | undefined;
913
1148
  interface RankPageDeps {
914
1149
  assertRankPartitionLocal: (tableName: string, definition: TableDefinitionLike, index: RankIndexDefinitionLike) => void;
915
1150
  ensureRankBackfilled: (tableName: string, index: RankIndexDefinitionLike) => void;
@@ -927,8 +1162,92 @@ interface RankPageComputation {
927
1162
  key: RankPageRowKey;
928
1163
  }[];
929
1164
  }
930
- declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
931
1165
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
1166
+ declare const SCHEDULE_OUTBOX_TABLE = "__schedule_outbox";
1167
+ interface ScheduleOutboxRow {
1168
+ attempts: number;
1169
+ envelopeJson: string;
1170
+ id: string;
1171
+ nextAttemptAt: number;
1172
+ }
1173
+ interface ScheduleOutboxEntry {
1174
+ attempts: number;
1175
+ createdAt: number;
1176
+ forever: boolean;
1177
+ id: string;
1178
+ nextAttemptAt: number;
1179
+ parked: boolean;
1180
+ target: string | undefined;
1181
+ when: number | undefined;
1182
+ }
1183
+ interface ScheduleOutboxEnvelope {
1184
+ args: unknown;
1185
+ options: Record<string, unknown> | undefined;
1186
+ target: unknown;
1187
+ when: number;
1188
+ }
1189
+ interface ScheduleOutbox {
1190
+ admit: (target: string) => number | undefined;
1191
+ forget: (id: string) => void;
1192
+ handOff?: (id: string, run: () => Promise<unknown>, token?: string) => Promise<void>;
1193
+ record: (id: string, envelope: ScheduleOutboxEnvelope) => string | undefined;
1194
+ wake: () => void;
1195
+ }
1196
+ declare const migrateScheduleOutbox: (sql: SqlExec) => void;
1197
+ declare const recordScheduleOutbox: (sql: SqlExec, id: string, envelopeJson: string, now: number) => void;
1198
+ declare const forgetScheduleOutbox: (sql: SqlExec, id: string) => void;
1199
+ declare const readDueScheduleOutbox: (sql: SqlExec, nowMs: number, limit: number) => ScheduleOutboxRow[];
1200
+ declare const readDueScheduleOutboxEntry: (sql: SqlExec, id: string, nowMs: number) => ScheduleOutboxRow | undefined;
1201
+ declare const deferScheduleOutbox: (sql: SqlExec, id: string, attempts: number, nextAttemptAt: number) => void;
1202
+ declare const parkScheduleOutbox: (sql: SqlExec, id: string, attempts: number, now: number) => void;
1203
+ declare const probeScheduleOutbox: (sql: SqlExec) => {
1204
+ dueAt: number | undefined;
1205
+ populated: boolean;
1206
+ };
1207
+ declare const trimScheduleOutbox: (sql: SqlExec, olderThanTs: number) => void;
1208
+ declare const readScheduleOutbox: (sql: SqlExec, limit: number, cursor?: string) => {
1209
+ entries: ScheduleOutboxEntry[];
1210
+ nextCursor: string | undefined;
1211
+ };
1212
+ declare const readScheduleOutboxState: (sql: SqlExec, id: string) => {
1213
+ createdAt: number;
1214
+ parked: boolean;
1215
+ version: string;
1216
+ } | undefined;
1217
+ declare const hasScheduleOutboxEntry: (sql: SqlExec, id: string) => boolean;
1218
+ declare const requeueScheduleOutbox: (sql: SqlExec, id: string, now: number) => boolean;
1219
+ declare const dropScheduleOutbox: (sql: SqlExec, id: string) => boolean;
1220
+ /**
1221
+ * How far a companion's backfill has progressed, and under which analysis.
1222
+ * Declared here rather than beside either engine's state table: both record the
1223
+ * same three facts, and the decisions made from them are the shared policy
1224
+ * below.
1225
+ */
1226
+ interface BackfillState {
1227
+ /** Last `id` indexed, or `undefined` when no page has run yet. */
1228
+ cursor: string | undefined;
1229
+ /** True once a page came back short — the table is fully indexed. */
1230
+ done: boolean;
1231
+ /** Analyzer profile the stored rows were built with; `undefined` predates profile tracking. */
1232
+ profile: string | undefined;
1233
+ }
1234
+ declare const SEARCH_STATE_TABLE = "__lunora_search_state";
1235
+ declare const migrateSearchState: (sql: SqlExec) => void;
1236
+ declare const readSearchBackfillState: (sql: SqlExec, companion: string) => BackfillState;
1237
+ declare const writeSearchBackfillState: (sql: SqlExec, companion: string, cursor: string | undefined, done: boolean, profile: string) => void;
1238
+ declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
1239
+ declare const migrateShapePokeCursor: (sql: SqlExec) => void;
1240
+ declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
1241
+ declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
1242
+ interface ShapePokeCursorRow {
1243
+ connectionId: string;
1244
+ cursor: number;
1245
+ subId: string;
1246
+ }
1247
+ declare const writeShapePokeCursors: (sql: SqlExec, rows: ReadonlyArray<ShapePokeCursorRow>) => void;
1248
+ declare const minShapePokeCursor: (sql: SqlExec) => number | undefined;
1249
+ declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
1250
+ declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
932
1251
  declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
933
1252
  type MigrationDirection = "down" | "up";
934
1253
  type MigrationStatus = "completed" | "failed" | "in_progress";
@@ -992,6 +1311,29 @@ interface DependencyTracker {
992
1311
  declare const createDependencyTracker: () => DependencyTracker;
993
1312
  declare const runSql: <Row = Record<string, unknown>>(sql: SqlExec, query: string, ...params: unknown[]) => SqlCursor<Row>;
994
1313
  declare const runDrizzle: <Row = Record<string, unknown>>(exec: SqlExec, query: SQL) => SqlCursor<Row>;
1314
+ type RangeOperandType = "boolean" | "number" | "string";
1315
+ interface WhereFragments<T> {
1316
+ binary: (reference: T, comparator: string, value: unknown) => T;
1317
+ connect: (left: T, right: T, connector: "AND" | "OR") => T;
1318
+ constant: (value: boolean) => T;
1319
+ contains: (reference: T, term: T) => T;
1320
+ inList: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget: number) => T;
1321
+ negate: (inner: T) => T;
1322
+ nullCheck: (reference: T, negated: boolean) => T;
1323
+ value: (value: unknown) => T;
1324
+ }
1325
+ type FieldRefSql<T> = (field: string) => T;
1326
+ type SerializeValue = (value: unknown, field: string) => unknown;
1327
+ interface WhereSqlStrategy<T = SQL> {
1328
+ containsExpr?: (reference: T, term: T) => T;
1329
+ fieldRef: FieldRefSql<T>;
1330
+ inList?: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => T;
1331
+ rangeTypeGuard: (field: string, type: RangeOperandType) => T;
1332
+ relationExists?: (request: unknown) => T;
1333
+ serialize: SerializeValue;
1334
+ }
1335
+ declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1336
+ declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
995
1337
  declare const quoteIdentifier: (name: string) => string;
996
1338
  declare const serializeSqlValue: (value: unknown) => unknown;
997
1339
  declare const DOC_COLUMN = "__doc__";
@@ -1005,10 +1347,16 @@ declare const AGG_KEY: Name;
1005
1347
  declare const AGG_VALUE: Name;
1006
1348
  declare const AGG_COUNT: Name;
1007
1349
  declare const aggUpsertSql: (aggTable: string, key: unknown, value: unknown, count: unknown, set: SQL) => SQL;
1008
- declare const tableColumns: (definition: TableDefinitionLike) => [string, ColumnMetaLike][];
1350
+ declare const tableColumns: (definition: TableDefinitionLike) => ReadonlyArray<readonly [string, ColumnMetaLike]>;
1009
1351
  declare const rowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
1010
1352
  declare const tryRowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
1011
- declare const isFtsAvailable: (sql: SqlExec) => boolean;
1353
+ declare const isFtsAvailable: (wrapper: SqlExec) => boolean;
1354
+ declare const WORKERD_SQLITE_LIMITS: {
1355
+ readonly boundParams: 100;
1356
+ readonly compoundSelect: 5;
1357
+ readonly likePattern: 50;
1358
+ readonly sqlTextLength: 100000;
1359
+ };
1012
1360
  type SqlEngine = "mysql" | "postgres" | "sqlite";
1013
1361
  interface RenderedSql {
1014
1362
  params: unknown[];
@@ -1016,6 +1364,79 @@ interface RenderedSql {
1016
1364
  }
1017
1365
  declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
1018
1366
  declare const param: (value: unknown) => SQL;
1367
+ declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
1368
+ declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1369
+ type DurableStreamStatus = "complete" | "error" | "running";
1370
+ interface DurableStreamRun {
1371
+ error?: string;
1372
+ errorCode?: string;
1373
+ lastSeq: number;
1374
+ startedAt: number;
1375
+ status: DurableStreamStatus;
1376
+ }
1377
+ interface DurableStreamChunk {
1378
+ dataJson: string;
1379
+ seq: number;
1380
+ }
1381
+ declare const migrateDurableStreams: (sql: SqlExec) => void;
1382
+ declare const readStreamRun: (sql: SqlExec, runKey: string) => DurableStreamRun | undefined;
1383
+ declare const claimStreamRun: (sql: SqlExec, runKey: string, startedAt: number, ttlMs: number) => boolean;
1384
+ declare const deleteStreamRun: (sql: SqlExec, runKey: string) => void;
1385
+ declare const appendStreamChunk: (sql: SqlExec, runKey: string, seq: number, dataJson: string) => void;
1386
+ declare const readStreamChunks: (sql: SqlExec, runKey: string, sinceSeq: number) => DurableStreamChunk[];
1387
+ declare const finishStreamRun: (sql: SqlExec, runKey: string, status: "complete" | "error", lastSeq: number, failure?: {
1388
+ code: string;
1389
+ message: string;
1390
+ }) => void;
1391
+ declare const trimStreamRuns: (sql: SqlExec, now: number, live: ReadonlySet<string>) => void;
1392
+ declare const MAX_DURABLE_STREAM_CHUNKS = 50000;
1393
+ declare const MAX_DURABLE_STREAM_BYTES: number;
1394
+ interface DurableStreamSink {
1395
+ readonly chunk: (chunk: {
1396
+ data: unknown;
1397
+ generation?: number;
1398
+ seq: number;
1399
+ }) => boolean;
1400
+ readonly complete: () => void;
1401
+ readonly fail: (failure: {
1402
+ code: string;
1403
+ message: string;
1404
+ }) => void;
1405
+ }
1406
+ type DurableAttachDecision = "attach" | "interrupted" | "reclaim" | "replay-terminal";
1407
+ declare const decideDurableAttach: (run: DurableStreamRun | undefined, context: {
1408
+ generation?: number;
1409
+ live?: {
1410
+ generation: number;
1411
+ };
1412
+ resuming: boolean;
1413
+ }) => DurableAttachDecision;
1414
+ interface DurableStreamAttach {
1415
+ readonly generation?: number;
1416
+ readonly iterator: (signal: AbortSignal) => AsyncIterable<unknown>;
1417
+ readonly runKey: string;
1418
+ readonly sinceChunk: number;
1419
+ readonly sink: DurableStreamSink;
1420
+ readonly ttlMs?: number;
1421
+ }
1422
+ declare class DurableStreamRunner {
1423
+ private lastTrimAt;
1424
+ private readonly runs;
1425
+ private readonly sql;
1426
+ private readonly waitUntil;
1427
+ constructor(dependencies: {
1428
+ sql: () => SqlExec;
1429
+ waitUntil?: (promise: Promise<unknown>) => void;
1430
+ });
1431
+ attach(request: DurableStreamAttach): Promise<void>;
1432
+ detach(runKey: string, sink: DurableStreamSink): void;
1433
+ isLive(runKey: string): boolean;
1434
+ private attachOrThrow;
1435
+ private produce;
1436
+ private trim;
1437
+ }
1438
+ declare const envPositiveInt: (env: unknown, key: string, fallback: number) => number;
1439
+ declare const envOptionalPositiveInt: (env: unknown, key: string) => number | undefined;
1019
1440
  interface ExternalSourceDiffResult {
1020
1441
  changes: CdcChange[];
1021
1442
  nextBaseline: Map<string, string>;
@@ -1080,6 +1501,16 @@ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => b
1080
1501
  declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
1081
1502
  applied: number;
1082
1503
  }>;
1504
+ declare const ftsRowidMapName: (companion: string) => string;
1505
+ interface FtsWriteOptions {
1506
+ guard?: SQL;
1507
+ unmappedRowids?: ReadonlyArray<number>;
1508
+ }
1509
+ declare const ftsCompanionDdl: (companion: string) => SQL[];
1510
+ declare const ftsWriteDocument: (companion: string, id: string, text: string, options?: FtsWriteOptions) => SQL[];
1511
+ declare const ftsPurgeDocument: (companion: string, id: string, options?: FtsWriteOptions) => SQL[];
1512
+ declare const ftsUnmappedPage: (companion: string, limit: number, after?: number) => SQL;
1513
+ declare const groupUnmappedRows: (rows: ReadonlyArray<Record<string, unknown>>) => Map<string, number[]>;
1083
1514
  declare const GEO_DEFAULT_PRECISION = 9;
1084
1515
  interface GeoPoint {
1085
1516
  lat: number;
@@ -1095,6 +1526,20 @@ declare const coveringGeohashes: (center: GeoPoint, radiusMeters: number) => str
1095
1526
  declare const pointInBoundingBox: (point: GeoPoint, box: GeoBoundingBox) => boolean;
1096
1527
  declare const boundingBoxCenter: (box: GeoBoundingBox) => GeoPoint;
1097
1528
  declare const boundingBoxGeohashes: (box: GeoBoundingBox) => string[];
1529
+ declare class GlobalPollTick {
1530
+ private readonly changedTables;
1531
+ private readonly reads;
1532
+ private resync;
1533
+ private skippedCount;
1534
+ constructor(changedTables?: Set<string>);
1535
+ get readCount(): number;
1536
+ get resyncRequested(): boolean;
1537
+ get skipped(): number;
1538
+ requestResync(): void;
1539
+ rows(key: string | undefined, load: () => Promise<ShapeRow[]>): Promise<ShapeRow[]>;
1540
+ shouldRead(table: string): boolean;
1541
+ }
1542
+ declare const isInternalTableName: (name: string) => boolean;
1098
1543
  declare const ADMIN_FUNCTION_PREFIX = "__lunora_admin__:";
1099
1544
  declare const RELATION_FUNCTION_PREFIX = "__lunora_relation__:";
1100
1545
  declare const FLAGS_FUNCTION_PREFIX = "__lunora_flags__:";
@@ -1102,23 +1547,29 @@ declare const ADMIN_FUNCTIONS: {
1102
1547
  readonly applyCdc: "__lunora_admin__:applyCdc";
1103
1548
  readonly aiAvailable: "__lunora_admin__:aiAvailable";
1104
1549
  readonly aiChartConfig: "__lunora_admin__:aiChartConfig";
1550
+ readonly aiCronExpression: "__lunora_admin__:aiCronExpression";
1105
1551
  readonly aiGenerateSql: "__lunora_admin__:aiGenerateSql";
1552
+ readonly aiNameQuery: "__lunora_admin__:aiNameQuery";
1106
1553
  readonly aiTableFilter: "__lunora_admin__:aiTableFilter";
1107
1554
  readonly assignIssue: "__lunora_admin__:assignIssue";
1555
+ readonly backfillSearch: "__lunora_admin__:backfillSearch";
1556
+ readonly backfillVectors: "__lunora_admin__:backfillVectors";
1108
1557
  readonly backRelationCounts: "__lunora_admin__:backRelationCounts";
1109
1558
  readonly cdcSync: "__lunora_admin__:cdcSync";
1110
1559
  readonly clearCapturedMail: "__lunora_admin__:clearCapturedMail";
1111
1560
  readonly clearQueueMessages: "__lunora_admin__:clearQueueMessages";
1112
1561
  readonly clearTable: "__lunora_admin__:clearTable";
1562
+ readonly createAdminToken: "__lunora_admin__:createAdminToken";
1113
1563
  readonly createWorkflowInstance: "__lunora_admin__:createWorkflowInstance";
1114
1564
  readonly deleteRows: "__lunora_admin__:deleteRows";
1115
1565
  readonly describeTable: "__lunora_admin__:describeTable";
1116
1566
  readonly describeTables: "__lunora_admin__:describeTables";
1567
+ readonly dropOutboxEntry: "__lunora_admin__:dropOutboxEntry";
1117
1568
  readonly explainIssue: "__lunora_admin__:explainIssue";
1118
1569
  readonly exportShard: "__lunora_admin__:exportShard";
1119
1570
  readonly facetColumn: "__lunora_admin__:facetColumn";
1571
+ readonly findRelated: "__lunora_admin__:findRelated";
1120
1572
  readonly getAdvisories: "__lunora_admin__:getAdvisories";
1121
- readonly getAdvisorProcedures: "__lunora_admin__:getAdvisorProcedures";
1122
1573
  readonly getAuditLog: "__lunora_admin__:getAuditLog";
1123
1574
  readonly getAuthMetrics: "__lunora_admin__:getAuthMetrics";
1124
1575
  readonly getCapturedMail: "__lunora_admin__:getCapturedMail";
@@ -1127,6 +1578,7 @@ declare const ADMIN_FUNCTIONS: {
1127
1578
  readonly getIssues: "__lunora_admin__:getIssues";
1128
1579
  readonly getMetricHistory: "__lunora_admin__:getMetricHistory";
1129
1580
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
1581
+ readonly getScheduleOutbox: "__lunora_admin__:getScheduleOutbox";
1130
1582
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
1131
1583
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
1132
1584
  readonly listTablesIndexes: "__lunora_admin__:listTablesIndexes";
@@ -1142,23 +1594,30 @@ declare const ADMIN_FUNCTIONS: {
1142
1594
  readonly getWorkflowInstanceStatus: "__lunora_admin__:getWorkflowInstanceStatus";
1143
1595
  readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
1144
1596
  readonly importShard: "__lunora_admin__:importShard";
1597
+ readonly listAdminTokens: "__lunora_admin__:listAdminTokens";
1145
1598
  readonly listFlags: "__lunora_admin__:listFlags";
1599
+ readonly listReactors: "__lunora_admin__:listReactors";
1146
1600
  readonly listQueues: "__lunora_admin__:listQueues";
1147
1601
  readonly lintSql: "__lunora_admin__:lintSql";
1148
1602
  readonly listTables: "__lunora_admin__:listTables";
1149
1603
  readonly listWorkflows: "__lunora_admin__:listWorkflows";
1150
1604
  readonly maskPolicies: "__lunora_admin__:maskPolicies";
1151
1605
  readonly migrationStatus: "__lunora_admin__:migrationStatus";
1606
+ readonly patchRows: "__lunora_admin__:patchRows";
1152
1607
  readonly pitrRestore: "__lunora_admin__:pitrRestore";
1153
1608
  readonly rankBefore: "__lunora_admin__:rankBefore";
1154
1609
  readonly rankPage: "__lunora_admin__:rankPage";
1155
1610
  readonly readTablePage: "__lunora_admin__:readTablePage";
1611
+ readonly rebuildCompanions: "__lunora_admin__:rebuildCompanions";
1156
1612
  readonly recordAuthEvent: "__lunora_admin__:recordAuthEvent";
1157
1613
  readonly recordContainerEvent: "__lunora_admin__:recordContainerEvent";
1158
1614
  readonly recordMail: "__lunora_admin__:recordMail";
1159
1615
  readonly recordQueueMessage: "__lunora_admin__:recordQueueMessage";
1616
+ readonly releaseShardRegistration: "__lunora_admin__:releaseShardRegistration";
1160
1617
  readonly replayQueueMessage: "__lunora_admin__:replayQueueMessage";
1618
+ readonly retryOutboxEntry: "__lunora_admin__:retryOutboxEntry";
1161
1619
  readonly resolveIssue: "__lunora_admin__:resolveIssue";
1620
+ readonly revokeAdminToken: "__lunora_admin__:revokeAdminToken";
1162
1621
  readonly rlsPolicies: "__lunora_admin__:rlsPolicies";
1163
1622
  readonly schemaHistory: "__lunora_admin__:schemaHistory";
1164
1623
  readonly schemaVersion: "__lunora_admin__:schemaVersion";
@@ -1167,11 +1626,13 @@ declare const ADMIN_FUNCTIONS: {
1167
1626
  readonly runSql: "__lunora_admin__:runSql";
1168
1627
  readonly sendQueueMessage: "__lunora_admin__:sendQueueMessage";
1169
1628
  readonly sendTestMail: "__lunora_admin__:sendTestMail";
1629
+ readonly sendWorkflowEvent: "__lunora_admin__:sendWorkflowEvent";
1170
1630
  readonly setIssueSeverity: "__lunora_admin__:setIssueSeverity";
1171
1631
  readonly storageOrphans: "__lunora_admin__:storageOrphans";
1172
1632
  readonly storageReferences: "__lunora_admin__:storageReferences";
1173
1633
  readonly storageRules: "__lunora_admin__:storageRules";
1174
1634
  readonly studioFeatures: "__lunora_admin__:studioFeatures";
1635
+ readonly verifyAdminToken: "__lunora_admin__:verifyAdminToken";
1175
1636
  readonly writeRow: "__lunora_admin__:writeRow";
1176
1637
  };
1177
1638
  interface TableInfo {
@@ -1226,8 +1687,12 @@ interface TablesIndexesResult {
1226
1687
  indexesByTable: Record<string, TableIndexInfo[]>;
1227
1688
  }
1228
1689
  interface ColumnMeta {
1690
+ bucket?: string;
1691
+ enumValues?: string[];
1229
1692
  isStorage?: boolean;
1230
1693
  name: string;
1694
+ nullable?: boolean;
1695
+ onDelete?: "cascade" | "restrict" | "set null";
1231
1696
  optional: boolean;
1232
1697
  pk?: boolean;
1233
1698
  ref?: string;
@@ -1249,6 +1714,11 @@ interface AdvisoryFinding {
1249
1714
  metadata: Record<string, unknown>;
1250
1715
  name: string;
1251
1716
  remediation: string;
1717
+ suppressed?: {
1718
+ file: string;
1719
+ line: number;
1720
+ reason: string;
1721
+ };
1252
1722
  title: string;
1253
1723
  }
1254
1724
  interface AdvisoriesResult {
@@ -1279,9 +1749,6 @@ interface AdvisorProcedure {
1279
1749
  visibility: "internal" | "public";
1280
1750
  writesUserTable?: boolean;
1281
1751
  }
1282
- interface AdvisorProceduresResult {
1283
- procedures: AdvisorProcedure[];
1284
- }
1285
1752
  interface RlsPolicyMetadata {
1286
1753
  file: string;
1287
1754
  on: "delete" | "insert" | "read" | "update";
@@ -1324,6 +1791,12 @@ interface StudioFeaturesResult {
1324
1791
  mail: boolean;
1325
1792
  notifications: boolean;
1326
1793
  payments: boolean;
1794
+ platform?: {
1795
+ id: string;
1796
+ name: string;
1797
+ unsupported: string[];
1798
+ };
1799
+ privacy: boolean;
1327
1800
  queues: boolean;
1328
1801
  scheduler: boolean;
1329
1802
  storage: boolean;
@@ -1342,13 +1815,26 @@ interface FlagsResult {
1342
1815
  configured: boolean;
1343
1816
  flags: FlagEvaluation[];
1344
1817
  }
1818
+ interface ReactorMetadata {
1819
+ errors: number;
1820
+ lastError?: string;
1821
+ lastRanAt?: number;
1822
+ path: string;
1823
+ runs: number;
1824
+ state: "active" | "failing" | "idle";
1825
+ suppressed: number;
1826
+ tables?: ReadonlyArray<string>;
1827
+ }
1828
+ interface ReactorsResult {
1829
+ reactors: ReactorMetadata[];
1830
+ }
1345
1831
  interface WorkflowMetadata {
1346
- binding: string;
1347
1832
  className: string;
1348
1833
  exportName: string;
1349
1834
  name: string;
1350
1835
  }
1351
1836
  interface WorkflowsResult {
1837
+ eventTypes?: string[];
1352
1838
  workflows: WorkflowMetadata[];
1353
1839
  }
1354
1840
  interface QueueMetadata {
@@ -1357,11 +1843,12 @@ interface QueueMetadata {
1357
1843
  exportName: string;
1358
1844
  mode: "pull" | "push";
1359
1845
  name: string;
1846
+ topic?: string;
1360
1847
  }
1361
1848
  interface QueuesResult {
1362
1849
  queues: QueueMetadata[];
1363
1850
  }
1364
- type WorkflowInstanceState = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1851
+ type WorkflowInstanceState = "complete" | "errored" | "paused" | "queued" | "rollingBack" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1365
1852
  interface CreateWorkflowInstanceResult {
1366
1853
  id: string;
1367
1854
  status: WorkflowInstanceState;
@@ -1400,12 +1887,15 @@ interface TablePage {
1400
1887
  columns: string[];
1401
1888
  refs?: Record<string, string>;
1402
1889
  rows: Record<string, unknown>[];
1890
+ sqlColumns: string[];
1403
1891
  total?: number;
1404
1892
  }
1405
- type FilterOperator = "contains" | "eq" | "gt" | "gte" | "lt" | "lte" | "ne";
1893
+ type ColumnKinds = Readonly<Record<string, string>>;
1894
+ type FilterOperator = "contains" | "eq" | "gt" | "gte" | "has" | "lt" | "lte" | "ne";
1406
1895
  interface FilterClause {
1407
1896
  column: string;
1408
1897
  operator: FilterOperator;
1898
+ path?: string[];
1409
1899
  value?: unknown;
1410
1900
  }
1411
1901
  interface OrderByClause {
@@ -1413,6 +1903,7 @@ interface OrderByClause {
1413
1903
  direction: SortDirection;
1414
1904
  }
1415
1905
  interface ReadTablePageOptions {
1906
+ columnKinds?: ColumnKinds;
1416
1907
  filters?: FilterClause[];
1417
1908
  limit?: number;
1418
1909
  offset?: number;
@@ -1423,6 +1914,8 @@ interface ReadTablePageOptions {
1423
1914
  table: string;
1424
1915
  }
1425
1916
  interface SelectMatchingIdsOptions {
1917
+ after?: string;
1918
+ columnKinds?: ColumnKinds;
1426
1919
  filters?: FilterClause[];
1427
1920
  limit?: number;
1428
1921
  search?: string;
@@ -1430,6 +1923,7 @@ interface SelectMatchingIdsOptions {
1430
1923
  }
1431
1924
  interface FacetColumnOptions {
1432
1925
  column: string;
1926
+ columnKinds?: ColumnKinds;
1433
1927
  filters?: FilterClause[];
1434
1928
  limit?: number;
1435
1929
  search?: string;
@@ -1445,6 +1939,7 @@ interface FacetColumnResult {
1445
1939
  }
1446
1940
  declare const MAX_PAGE_SIZE = 500;
1447
1941
  declare const listTables: (sql: SqlExec) => TableInfo[];
1942
+ declare const isVacuousFilterClause: (clause: FilterClause) => boolean;
1448
1943
  declare const readTablePage: (sql: SqlExec, options: ReadTablePageOptions) => TablePage;
1449
1944
  declare const selectMatchingIds: (sql: SqlExec, options: SelectMatchingIdsOptions) => {
1450
1945
  hasMore: boolean;
@@ -1463,6 +1958,7 @@ interface StorageReferenceResult {
1463
1958
  declare const findStorageReferences: (sql: SqlExec, storageColumns: Record<string, string[]>, keys: string[]) => StorageReferenceResult;
1464
1959
  interface SocketAttachmentLike {
1465
1960
  admin?: boolean;
1961
+ authenticated?: boolean;
1466
1962
  subs?: Record<string, SubscriptionInfo>;
1467
1963
  }
1468
1964
  declare const summarizeSubscriptions: (attachments: SocketAttachmentLike[]) => SubscriptionsResult;
@@ -1479,18 +1975,29 @@ interface FanoutPathCounters {
1479
1975
  socketsIterated: number;
1480
1976
  totalMs: number;
1481
1977
  }
1978
+ interface ShapeProbeCounters {
1979
+ run: number;
1980
+ served: number;
1981
+ }
1982
+ interface GlobalPollCounters {
1983
+ drains: number;
1984
+ pairsSkipped: number;
1985
+ }
1482
1986
  interface FanoutMetricsResult {
1987
+ globalPoll: GlobalPollCounters;
1483
1988
  maxRelays: number;
1484
1989
  peakSubscribers: number;
1485
1990
  promoted: boolean;
1486
1991
  relayCount: number;
1487
1992
  shapePoke: FanoutPathCounters;
1993
+ shapeProbe: ShapeProbeCounters;
1488
1994
  sinceMs: number;
1489
1995
  topics: FanoutTopicStat[];
1490
1996
  totalConnections: number;
1491
1997
  whisper: FanoutPathCounters;
1492
1998
  }
1493
1999
  interface FanoutAttachmentLike {
2000
+ authenticated?: boolean;
1494
2001
  shapes?: Record<string, {
1495
2002
  name?: string;
1496
2003
  }>;
@@ -1498,6 +2005,10 @@ interface FanoutAttachmentLike {
1498
2005
  }
1499
2006
  declare const DEFAULT_FANOUT_TOPIC_LIMIT = 20;
1500
2007
  declare const createFanoutCounters: () => FanoutPathCounters;
2008
+ declare const createShapeProbeCounters: () => ShapeProbeCounters;
2009
+ declare const createGlobalPollCounters: () => GlobalPollCounters;
2010
+ declare const recordGlobalPollPass: (counters: GlobalPollCounters, drains: number, pairsSkipped: number) => GlobalPollCounters;
2011
+ declare const recordShapeProbePass: (counters: ShapeProbeCounters, run: number, served: number) => ShapeProbeCounters;
1501
2012
  declare const recordFanoutPass: (counters: FanoutPathCounters, iterated: number, delivered: number, ms: number) => FanoutPathCounters;
1502
2013
  declare const summarizeFanoutTopics: (attachments: FanoutAttachmentLike[], limit?: number) => {
1503
2014
  peakSubscribers: number;
@@ -1545,6 +2056,11 @@ declare const clearCapturedMail: (sql: SqlExec) => {
1545
2056
  declare class NotFoundError extends LunoraError {
1546
2057
  constructor(message?: string);
1547
2058
  }
2059
+ declare const operatorFields: (definition: TableDefinitionLike, patch: Record<string, unknown>) => ReadonlySet<string>;
2060
+ declare const resolvePatch: (definition: TableDefinitionLike, patch: Record<string, unknown>, current: Record<string, unknown>) => Record<string, unknown>;
2061
+ declare const patchDependsOnRow: (definition: TableDefinitionLike, patch: Record<string, unknown>) => boolean;
2062
+ declare const assertPatchAllowed: (options: PatchWriteOptions | undefined, previous: Record<string, unknown>, next: Record<string, unknown>) => void;
2063
+ declare const readPatchField: (document: Record<string, unknown>, field: string) => unknown;
1548
2064
  interface PitrStorage {
1549
2065
  getBookmarkForTime?: (time: Date | number) => Promise<string>;
1550
2066
  getCurrentBookmark?: () => Promise<string>;
@@ -1566,7 +2082,22 @@ interface PitrRestoreArgs {
1566
2082
  }
1567
2083
  declare const readBookmark: (storage: PitrStorage, time?: number | string) => Promise<PitrBookmarkResult>;
1568
2084
  declare const armRestore: (storage: PitrStorage, args: PitrRestoreArgs) => Promise<Omit<PitrRestoreResult, "restarted">>;
1569
- declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined) => OrderKey[];
2085
+ declare const tiebreakDirectionFor: (keys: ReadonlyArray<{
2086
+ direction?: string;
2087
+ }>) => SortDirection;
2088
+ declare const equalityPinnedFields: (where: undefined | WhereInput) => ReadonlySet<string>;
2089
+ declare const uniqueIndexFields: (indexes: ReadonlyArray<{
2090
+ fields: ReadonlyArray<string>;
2091
+ unique?: boolean;
2092
+ }> | undefined, shape: Record<string, ValidatorLike> | undefined) => ReadonlyArray<ReadonlyArray<string>>;
2093
+ interface OrderKeyConstraints {
2094
+ pinned?: ReadonlySet<string>;
2095
+ uniqueBy?: ReadonlyArray<ReadonlyArray<string>>;
2096
+ }
2097
+ declare const nullsFirstOf: (key: Pick<OrderKey, "direction" | "nulls">) => boolean;
2098
+ declare const nullsOrderSuffix: (nullsFirst: boolean) => string;
2099
+ declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>, constraints?: OrderKeyConstraints) => OrderKey[];
2100
+ declare const CURSOR_PREFIX = "~4";
1570
2101
  declare const encodeCursor: (record: Record<string, unknown>, keys: OrderKey[]) => string;
1571
2102
  declare const decodeCursor: (cursor: string) => unknown[];
1572
2103
  declare const buildSeekWhere: (keys: OrderKey[], cursorValues: unknown[]) => WhereInput;
@@ -1626,24 +2157,71 @@ declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: R
1626
2157
  rowId: string;
1627
2158
  sortValues: unknown[];
1628
2159
  };
2160
+ declare const rankPivotConditionSql: (column: string, value: unknown, direction: "asc" | "desc", wantLater: boolean) => SQL | undefined;
1629
2161
  declare const matchesRankStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
2162
+ declare const REACTOR_STATE_TABLE = "__reactor_state";
2163
+ interface ReactorState {
2164
+ digest: string;
2165
+ lastError?: string;
2166
+ lastRanAt: number;
2167
+ stats: ReactorStats;
2168
+ tables?: ReadonlyArray<string>;
2169
+ }
2170
+ interface ReactorStats {
2171
+ errors: number;
2172
+ runs: number;
2173
+ suppressed: number;
2174
+ }
2175
+ declare const migrateReactorState: (sql: SqlExec) => void;
2176
+ declare const readReactorState: (sql: SqlExec, path: string) => ReactorState | undefined;
2177
+ declare const listReactorStates: (sql: SqlExec) => {
2178
+ path: string;
2179
+ state: ReactorState;
2180
+ }[];
2181
+ type ReactorDispatchResult = "error" | "ran" | "suppressed";
2182
+ declare const writeReactorState: (sql: SqlExec, path: string, outcome: {
2183
+ digest?: string;
2184
+ error?: string;
2185
+ now: number;
2186
+ result: ReactorDispatchResult;
2187
+ tables?: ReadonlyArray<string>;
2188
+ }) => void;
2189
+ declare const reactorNeedsRun: (state: Pick<ReactorState, "tables"> | undefined, changed: ReadonlySet<string>) => boolean;
1630
2190
  interface ReadFootprint {
1631
- onRead: (table: string, idOrScan?: string) => void;
2191
+ onRead: (table: string, idOrScan?: string, exact?: boolean) => void;
1632
2192
  onReadRange: (range: KeyRange) => void;
1633
2193
  ranges: () => Map<string, KeyRange[]> | undefined;
1634
2194
  tables: Set<string>;
1635
2195
  }
1636
2196
  declare const createReadFootprint: () => ReadFootprint;
2197
+ declare const ADMIN_WILDCARD = "*";
2198
+ declare const UNVOUCHABLE_DEP = "!unvouchable";
2199
+ declare const markUnvouchableReads: <T extends object>(facade: T, onRead: ReadFootprint["onRead"] | undefined, methods: ReadonlyArray<string>) => T;
2200
+ declare const WHERE_FILTER: unique symbol;
2201
+ type RowPredicate = (document: Record<string, unknown>) => boolean;
2202
+ type WhereFilter = RowPredicate & {
2203
+ readonly [WHERE_FILTER]: WhereInput;
2204
+ };
2205
+ declare const whereFilter: (where: WhereInput, predicate: RowPredicate) => WhereFilter;
2206
+ declare const whereOfFilter: (predicate: RowPredicate) => undefined | WhereInput;
2207
+ declare const isPushableWhere: (where: WhereInput, shape: Readonly<Record<string, ValidatorLike>>, exactText?: boolean) => boolean;
2208
+ declare const RELATED_MAX_DEPTH = 4;
2209
+ declare const RELATED_DEFAULT_LIMIT = 50;
2210
+ declare const RELATED_MAX_LIMIT = 200;
2211
+ declare const RELATED_DEPTH_DECAY = 0.5;
2212
+ declare const deriveRelationEdges: (schema: SchemaLike) => RelationEdge[];
2213
+ type RelationGraphReader = Pick<DatabaseWriterLike, "findMany"> & Pick<Partial<DatabaseWriterLike>, "lookupById">;
2214
+ declare const findRelated: (reader: RelationGraphReader, edges: ReadonlyArray<RelationEdge>, start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
1637
2215
  declare const DEFAULT_MAX_RELATION_KEYS = 5000;
1638
2216
  interface RelationExistsMarker {
1639
2217
  childWhere: WhereInput;
1640
2218
  negated: boolean;
1641
2219
  parentTable: string;
1642
- relation: RelationDefinitionLike;
2220
+ relation: KeyedRelationDefinitionLike;
1643
2221
  }
1644
2222
  type ExistsPushMode = "always" | "auto";
1645
2223
  interface ResolveRelationPredicatesOptions {
1646
- canPushExists?: (relation: RelationDefinitionLike) => boolean;
2224
+ canPushExists?: (relation: KeyedRelationDefinitionLike) => boolean;
1647
2225
  existsPushMode?: ExistsPushMode;
1648
2226
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
1649
2227
  maxRelationKeys?: number;
@@ -1654,7 +2232,7 @@ interface ResolveRelationPredicatesOptions {
1654
2232
  tableName: string;
1655
2233
  }
1656
2234
  interface ResolveContext {
1657
- canPushExists?: (relation: RelationDefinitionLike) => boolean;
2235
+ canPushExists?: (relation: KeyedRelationDefinitionLike) => boolean;
1658
2236
  existsPushMode: ExistsPushMode;
1659
2237
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
1660
2238
  maxRelationKeys: number;
@@ -1667,15 +2245,30 @@ declare const isRelationPredicate: (value: unknown) => value is Record<string, W
1667
2245
  declare const containsRelationPredicate: (where: WhereInput, schema: ResolveContext["schema"], tableName: string) => boolean;
1668
2246
  declare const assertFlatPredicate: (where: WhereInput | undefined, schema: ResolveContext["schema"], tableName: string, op: string) => void;
1669
2247
  declare const resolveRelationPredicates: (where: WhereInput | undefined, options: ResolveRelationPredicatesOptions) => Promise<WhereInput | undefined>;
2248
+ declare const composeReadPredicate: (definition: TableDefinitionLike, args: QueryArgs, relation: Omit<ResolveRelationPredicatesOptions, "relationBaseWhere">) => Promise<{
2249
+ fetchLimit: number | undefined;
2250
+ limit: number | undefined;
2251
+ orderKeys: OrderKey[];
2252
+ predicate: WhereInput | undefined;
2253
+ }>;
2254
+ declare const findManyPage: (documents: Record<string, unknown>[], read: {
2255
+ endCursor?: null | string;
2256
+ limit: number | undefined;
2257
+ omitContinueCursor?: boolean;
2258
+ orderKeys: OrderKey[];
2259
+ }) => QueryPage;
1670
2260
  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">;
2261
+ declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask"> & Pick<ResolveWithOptions, "fanOutBudget">;
1672
2262
  declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
1673
2263
  declare const distinctValues: (rows: Record<string, unknown>[], field: string) => unknown[];
1674
2264
  declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
1675
2265
  interface ApplyOnDeleteOptions {
1676
2266
  deletedId: string;
1677
2267
  deletedReference: (references: string) => unknown;
1678
- findHolders: (holderTable: string, field: string, value: unknown) => Promise<Record<string, unknown>[]>;
2268
+ findHolders: (holderTable: string, field: string, value: unknown, page: {
2269
+ limit: number;
2270
+ select?: ReadonlyArray<string>;
2271
+ }) => Promise<Record<string, unknown>[]>;
1679
2272
  onCascade: (holderTable: string, id: string) => Promise<void>;
1680
2273
  onRestrict: (message: string) => never;
1681
2274
  onSetNull: (holderTable: string, id: string, field: string) => Promise<void>;
@@ -1685,7 +2278,15 @@ interface ApplyOnDeleteOptions {
1685
2278
  tableName: string;
1686
2279
  }
1687
2280
  declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
1688
- declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, tolerateStoredNull?: boolean) => void;
2281
+ interface RowValidatorOptions {
2282
+ only?: ReadonlySet<string>;
2283
+ previous?: () => Readonly<Record<string, unknown>> | undefined;
2284
+ supplied?: Readonly<Record<string, unknown>>;
2285
+ tolerateStoredNull?: boolean;
2286
+ trusted?: boolean;
2287
+ }
2288
+ declare const applyInsertDefaults: (definition: TableDefinitionLike, document: Record<string, unknown>, auth: ServerDefaultContextLike["auth"]) => Record<string, unknown>;
2289
+ declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, options?: RowValidatorOptions) => Record<string, unknown>;
1689
2290
  interface ShapeRowOp {
1690
2291
  key: string;
1691
2292
  op: "delete" | "insert" | "update";
@@ -1693,6 +2294,8 @@ interface ShapeRowOp {
1693
2294
  value?: Record<string, unknown>;
1694
2295
  }
1695
2296
  interface ShapePokePart {
2297
+ baseCheckpoint?: number;
2298
+ reset?: boolean;
1696
2299
  rowsPatch: ShapeRowOp[];
1697
2300
  shapeId: string;
1698
2301
  }
@@ -1727,15 +2330,18 @@ declare const clampPromotionThresholds: (tUp: number, tDownRaw: number) => Promo
1727
2330
  declare const relayCountFor: (subscribers: number, perRelayCapacity: number, maxRelays: number) => number;
1728
2331
  interface RelayAttach {
1729
2332
  relayIndex: number;
2333
+ seq?: number;
1730
2334
  type: "relay_attach";
1731
2335
  }
1732
2336
  interface RelayDetach {
1733
2337
  relayIndex: number;
2338
+ seq?: number;
1734
2339
  type: "relay_detach";
1735
2340
  }
1736
2341
  interface RelayFrame {
1737
2342
  cursor?: number;
1738
2343
  epoch?: string;
2344
+ exceptConnectionId?: string;
1739
2345
  frame: string;
1740
2346
  originRelay?: number;
1741
2347
  topic: string;
@@ -1753,6 +2359,12 @@ interface RelayShapeSubscribe {
1753
2359
  type: "relay_shape_subscribe";
1754
2360
  userId?: string;
1755
2361
  }
2362
+ interface RelayShapeUnsubscribe {
2363
+ connectionId: string;
2364
+ relayIndex: number;
2365
+ subId?: string;
2366
+ type: "relay_shape_unsubscribe";
2367
+ }
1756
2368
  interface RelayShapeSeed {
1757
2369
  cursor?: number;
1758
2370
  epoch?: string;
@@ -1772,44 +2384,88 @@ interface RelayShapePoke {
1772
2384
  targetConnectionId?: string;
1773
2385
  type: "relay_shape_poke";
1774
2386
  }
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>;
2387
+ interface RelayRoomEvent {
2388
+ attachment: Pick<SocketAttachment, "connectionId" | "context" | "expiresAt" | "identity" | "ip" | "revalidateAt" | "userId">;
2389
+ connectionId: string;
2390
+ data?: unknown;
2391
+ kind: "join" | "leave" | "message";
2392
+ relayIndex: number;
2393
+ topic: string;
2394
+ type: "relay_room_event";
2395
+ }
2396
+ interface RelayRoomVerdict {
2397
+ admitted: boolean;
2398
+ }
2399
+ interface LiveSocketControlCall {
2400
+ action: unknown;
2401
+ adminReauth?: true;
2402
+ callerId: string;
2403
+ connectionId: string;
2404
+ identity?: Record<string, unknown>;
2405
+ identityExpiry?: number;
2406
+ key: string;
2407
+ seq?: number;
2408
+ subscriptionId: string;
2409
+ }
2410
+ interface RelayLiveControl {
2411
+ control: LiveSocketControlCall;
2412
+ type: "relay_live_control";
1779
2413
  }
1780
- interface RelayNamespaceLike {
1781
- get: (id: unknown) => RelayStub;
1782
- getByName?: (name: string) => RelayStub;
1783
- idFromName: (name: string) => unknown;
2414
+ interface RelayLiveFrame {
2415
+ frame: string;
2416
+ key: string;
2417
+ topic: string;
2418
+ type: "relay_live_frame";
2419
+ }
2420
+ type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayLiveControl | RelayLiveFrame | RelayRoomEvent | RelayShapePoke | RelayShapeSubscribe | RelayShapeUnsubscribe;
2421
+ declare const RELAY_SIGNATURE_HEADER = "x-lunora-relay-sig";
2422
+ declare const siblingSecretOf: (env: unknown) => string | undefined;
2423
+ declare const signSiblingBody: (secret: string, body: string) => Promise<string>;
2424
+ declare const verifySiblingBody: (env: unknown, supplied: null | string, raw: string) => Promise<boolean>;
2425
+ interface SiblingStub {
2426
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
1784
2427
  }
2428
+ declare const stubByName: (value: unknown, name: string, jurisdiction?: string) => SiblingStub | undefined;
2429
+ declare const DEFAULT_MAX_RELAYS = 8;
1785
2430
  interface RelayHost {
1786
2431
  buildShapeDiff: (resolved: ResolvedShape, fromCursor: number, toCursor: number) => ShapeRowOp[];
1787
2432
  computeOpLogShapeSeed: (shape: ShapeSubscriptionQuery, resolved: ResolvedShape) => {
1788
2433
  baseCheckpoint: number | undefined;
1789
2434
  cursor: number;
1790
2435
  epoch: string | undefined;
2436
+ reset: boolean;
1791
2437
  rowsPatch: ShapeRowOp[];
1792
2438
  };
1793
2439
  currentCdcEpoch: () => string | undefined;
2440
+ deliverLiveLocal: (topic: string, key: string, frame: string) => number;
1794
2441
  deliverWhisperLocal: (topic: string, frame: string, exclude: undefined | ShardSocketLike) => number;
1795
2442
  doName: () => string | undefined;
2443
+ dropIfLapsed: (ws: ShardSocketLike) => boolean;
1796
2444
  env: () => unknown;
1797
2445
  getWebSockets: () => ShardSocketLike[];
2446
+ liveControl: (control: LiveSocketControlCall) => Promise<Response>;
1798
2447
  maskMetadata: () => MaskPoliciesResult;
1799
2448
  nextPokeId: () => string;
1800
2449
  readAttachment: (ws: ShardSocketLike) => SocketAttachment;
1801
2450
  recordShapePokeFanout: (iterated: number, delivered: number, elapsedMs: number) => void;
2451
+ relayRoomEvent: (event: RelayRoomEvent) => Promise<RelayRoomVerdict>;
1802
2452
  resolveShape: (name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity) => ResolvedShape | undefined;
1803
2453
  rlsMetadata: () => RlsPoliciesResult;
1804
2454
  shardBinding: () => string | undefined;
2455
+ shardJurisdiction: () => string | undefined;
1805
2456
  sql: () => SqlExec;
1806
2457
  }
2458
+ interface RelayPokeDelivery {
2459
+ delivered: number;
2460
+ matched: number;
2461
+ }
1807
2462
  declare abstract class RelayLink {
1808
2463
  protected readonly host: RelayHost;
1809
2464
  protected readonly roleId: {
1810
2465
  ownerKey: string;
1811
2466
  relayIndex?: number;
1812
2467
  };
2468
+ private lastSequence;
1813
2469
  protected constructor(host: RelayHost, roleId: {
1814
2470
  ownerKey: string;
1815
2471
  relayIndex?: number;
@@ -1817,81 +2473,188 @@ declare abstract class RelayLink {
1817
2473
  handleControl(request: Request): Promise<Response>;
1818
2474
  maxRelays(): number;
1819
2475
  protected canAddressSiblings(): boolean;
1820
- protected relayNamespace(): RelayNamespaceLike | undefined;
2476
+ protected isAdmitted(ws: ShardSocketLike): boolean;
2477
+ protected siblingStub(targetName: string): SiblingStub | undefined;
2478
+ protected bindingName(): string | undefined;
2479
+ protected nextRelaySeq(): number;
1821
2480
  protected postRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<void>;
1822
2481
  protected requestRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<Response | undefined>;
1823
- abstract forwardWhisper(topic: string, frame: string): Promise<void>;
2482
+ abstract forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
1824
2483
  abstract onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
1825
2484
  abstract seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | undefined | {
1826
2485
  code: string;
1827
2486
  message: string;
1828
2487
  }>;
1829
- abstract announce(): Promise<void>;
2488
+ abstract announce(): Promise<boolean>;
1830
2489
  abstract announceDrain(closing: ShardSocketLike): Promise<void>;
2490
+ abstract releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
1831
2491
  abstract relayCount(): number;
1832
2492
  abstract isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
1833
- protected abstract onAttach(index: number): void;
1834
- protected abstract onDetach(index: number): void;
2493
+ abstract minShapeCursor(): number | undefined;
2494
+ protected abstract onAttach(index: number, seq: number | undefined): boolean;
2495
+ protected abstract onDetach(index: number, seq: number | undefined): boolean;
2496
+ protected abstract onLiveControl(control: LiveSocketControlCall): Promise<Response>;
1835
2497
  protected abstract onWhisperFrame(message: RelayFrame): Promise<void>;
2498
+ protected abstract refusesAsIdle(): boolean;
1836
2499
  protected abstract onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
1837
- protected abstract onShapePoke(poke: RelayShapePoke): number;
2500
+ protected abstract onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2501
+ protected abstract onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
1838
2502
  }
1839
2503
  declare class OwnerRelay extends RelayLink {
1840
2504
  private readonly shapeUniformCache;
1841
2505
  private relaySetCache;
1842
- private readonly relayShapeRegistry;
1843
- private readonly relayShapeProxies;
2506
+ private liveGrantRelayCache;
2507
+ private relayTablesReady;
2508
+ private readonly relaySeqMarks;
2509
+ private readonly pendingSubscribeRelays;
2510
+ private registryCache;
2511
+ private recorded;
1844
2512
  private promotionState;
1845
2513
  constructor(host: RelayHost, ownerKey: string);
1846
- forwardWhisper(topic: string, frame: string): Promise<void>;
2514
+ forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
2515
+ forwardLiveControl(call: LiveSocketControlCall): Promise<Response | undefined>;
2516
+ forwardLiveFrame(topic: string, key: string, frame: string): Promise<void>;
1847
2517
  onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
1848
2518
  seedRelayShape(): Promise<"ok" | undefined | {
1849
2519
  code: string;
1850
2520
  message: string;
1851
2521
  }>;
1852
- announce(): Promise<void>;
2522
+ announce(): Promise<boolean>;
1853
2523
  announceDrain(): Promise<void>;
2524
+ releaseRelayShapes(): Promise<void>;
1854
2525
  relayCount(): number;
2526
+ minShapeCursor(): number | undefined;
1855
2527
  isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
1856
- protected onAttach(index: number): void;
1857
- protected onDetach(index: number): void;
2528
+ protected onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2529
+ protected onAttach(index: number, seq: number | undefined): boolean;
2530
+ protected onDetach(index: number, seq: number | undefined): boolean;
2531
+ protected refusesAsIdle(): boolean;
2532
+ protected onLiveControl(control: LiveSocketControlCall): Promise<Response>;
1858
2533
  protected onWhisperFrame(message: RelayFrame): Promise<void>;
1859
2534
  protected onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
1860
- protected onShapePoke(): number;
2535
+ protected onShapePoke(): RelayPokeDelivery;
2536
+ private relaySeqMark;
2537
+ private recordRelaySeq;
2538
+ private acceptRelaySeq;
1861
2539
  private buildShapePoke;
1862
2540
  private multicastShapePokes;
2541
+ private multicastToRelays;
1863
2542
  private proxyShapePokes;
2543
+ private proxyToRelay;
1864
2544
  private buildShapeSeedFrames;
1865
- private ensureRelayTable;
2545
+ private ensureRelayTables;
2546
+ protected bindingName(): string | undefined;
2547
+ private relayShapes;
2548
+ private rewindShapeCursor;
1866
2549
  private ownerRelaySet;
2550
+ private liveGrantRelaySet;
2551
+ private recordLiveGrantRelay;
1867
2552
  private addRelayToSet;
2553
+ private forwardToRelay;
2554
+ private requestDroppingIdle;
1868
2555
  private removeRelayFromSet;
1869
2556
  private probeShapeRelayUniform;
1870
2557
  private tableHasAnyMask;
2558
+ private liveControlAnswer;
1871
2559
  }
1872
2560
  declare class RelayMember extends RelayLink {
1873
2561
  private relayAnnounced;
1874
- private readonly shapeRelayMemos;
2562
+ private readonly liveControlSeqs;
2563
+ private pendingAnnounce;
2564
+ private announceGeneration;
2565
+ private pendingDetach;
2566
+ private relayMemoCache;
2567
+ private readonly shapeControl;
1875
2568
  constructor(host: RelayHost, ownerKey: string, relayIndex: number);
1876
2569
  forwardWhisper(topic: string, frame: string): Promise<void>;
2570
+ forwardRoomEvent(event: Omit<RelayRoomEvent, "relayIndex" | "type">): Promise<boolean>;
1877
2571
  onFlush(): Promise<void>;
1878
2572
  seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | {
1879
2573
  code: string;
1880
2574
  message: string;
1881
2575
  }>;
1882
- announce(): Promise<void>;
2576
+ announce(): Promise<boolean>;
1883
2577
  announceDrain(closing: ShardSocketLike): Promise<void>;
2578
+ releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
1884
2579
  relayCount(): number;
1885
2580
  isShapeRelayUniform(): boolean;
1886
- protected onAttach(): void;
1887
- protected onDetach(): void;
2581
+ minShapeCursor(): number | undefined;
2582
+ protected onAttach(): boolean;
2583
+ protected refusesAsIdle(): boolean;
2584
+ protected onDetach(): boolean;
2585
+ protected onLiveControl(control: LiveSocketControlCall): Promise<Response>;
1888
2586
  protected onWhisperFrame(): Promise<void>;
1889
2587
  protected onShapeSubscribe(): RelayShapeSeed;
1890
- protected onShapePoke(poke: RelayShapePoke): number;
2588
+ protected onShapeUnsubscribe(): void;
2589
+ protected onShapePoke(poke: RelayShapePoke): RelayPokeDelivery;
2590
+ private queueShapeControl;
2591
+ private relayMemos;
2592
+ private connectionMemos;
1891
2593
  private recordRelayShapeMemo;
2594
+ private forgetRelayShapeMemos;
1892
2595
  private deliverShapePoke;
2596
+ private pokeSocketShapes;
1893
2597
  }
1894
2598
  declare const createRelayLink: (host: RelayHost) => OwnerRelay | RelayMember | undefined;
2599
+ declare const REGION_HINTS: readonly ["wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"];
2600
+ type RegionHint = (typeof REGION_HINTS)[number];
2601
+ type ReplicaReadiness = "fresh" | "stale" | "unavailable";
2602
+ interface ShardSiblingHost {
2603
+ doName: () => string | undefined;
2604
+ env: () => unknown;
2605
+ shardBinding: () => string | undefined;
2606
+ shardJurisdiction: () => string | undefined;
2607
+ sql: () => SqlExec;
2608
+ }
2609
+ interface ReplicaOwnerHost extends ShardSiblingHost {
2610
+ exportRows: () => Promise<ExportRow[]>;
2611
+ ownerCursor: () => number | undefined;
2612
+ ownerEpoch: () => string | undefined;
2613
+ ownerFloor: () => number | undefined;
2614
+ readChanges: (sinceSeq: number, limit: number) => {
2615
+ changes: CdcChange[];
2616
+ cursor: number;
2617
+ };
2618
+ rowCount: () => number;
2619
+ }
2620
+ interface ReplicaFollowerHost extends ShardSiblingHost {
2621
+ applyChanges: (changes: ReadonlyArray<CdcChange>) => Promise<number>;
2622
+ exportRows: () => Promise<ExportRow[]>;
2623
+ importRows: (rows: ReadonlyArray<ExportRow>) => Promise<{
2624
+ errors: ReadonlyArray<unknown>;
2625
+ }>;
2626
+ reportError?: (scope: string, error: unknown) => void;
2627
+ transactionLimits: () => Partial<TransactionLimits>;
2628
+ }
2629
+ declare const handleReplicaControl: (host: ReplicaOwnerHost, request: Request) => Promise<Response>;
2630
+ declare class ShardReplica {
2631
+ private readonly host;
2632
+ readonly ownerKey: string;
2633
+ readonly region: RegionHint;
2634
+ private divergent;
2635
+ private inFlight;
2636
+ constructor(host: ReplicaFollowerHost, ownerKey: string, region: RegionHint);
2637
+ ensureFresh(minSeq?: number): Promise<ReplicaReadiness>;
2638
+ appliedSeq(): number;
2639
+ isDivergent(): boolean;
2640
+ private advance;
2641
+ private isCaughtUp;
2642
+ private catchUp;
2643
+ private verdict;
2644
+ private recover;
2645
+ private whenOwnerUnreachable;
2646
+ private applyPage;
2647
+ private applyAtomically;
2648
+ private fetchSnapshot;
2649
+ private resnapshot;
2650
+ private overWriteBudget;
2651
+ private bootstrap;
2652
+ private isFreshEnough;
2653
+ private pull;
2654
+ private request;
2655
+ }
2656
+ declare const createReplicaLink: (host: ReplicaFollowerHost) => ShardReplica | undefined;
2657
+ declare const gateReplicaDispatch: (replica: ShardReplica, request: Request, functionPath: string) => Promise<Response | undefined>;
1895
2658
  declare const REPROJECTION_MIGRATION_PREFIX = "__lunora_reproject__";
1896
2659
  declare const reprojectionMigrationId: (table: string) => string;
1897
2660
  declare const reprojectableFields: (definition: TableDefinitionLike) => string[];
@@ -1913,8 +2676,7 @@ interface GuardableSchema {
1913
2676
  }>;
1914
2677
  }
1915
2678
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
1916
- type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
1917
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
2679
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, relationEdges?: ReadonlyArray<RelationEdge>) => W;
1918
2680
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
1919
2681
  interface SchemaVersionRow {
1920
2682
  appliedAt: number;
@@ -1925,8 +2687,24 @@ interface SchemaVersionRow {
1925
2687
  declare const recordSchemaVersion: (sql: SqlExec, hash: string, snapshotJson: string, now?: number) => boolean;
1926
2688
  declare const readSchemaHistory: (sql: SqlExec) => SchemaVersionRow[];
1927
2689
  declare const readSchemaVersion: (sql: SqlExec, hash: string) => SchemaVersionRow | undefined;
2690
+ declare const readDeployInfo: (rawEnv: unknown) => DeployInfo;
1928
2691
  declare const isDevEnvironment: (rawEnv: unknown) => boolean;
1929
2692
  declare const buildSettings: (rawEnv: unknown) => SettingsResult;
2693
+ declare class ShapeDiffCache {
2694
+ private readonly keyScans;
2695
+ private readonly memberProbes;
2696
+ private run;
2697
+ private served;
2698
+ get probesRun(): number;
2699
+ get probesServed(): number;
2700
+ changedKeys(rangeKey: string, load: () => CdcChangeKey[]): ReadonlyArray<CdcChangeKey>;
2701
+ members(resolved: ResolvedShape, rangeKey: string, load: () => Map<string, Record<string, unknown>>): ReadonlyMap<string, Record<string, unknown>>;
2702
+ private getOrLoad;
2703
+ }
2704
+ declare const createShapeDiffCache: () => ShapeDiffCache;
2705
+ declare const globalShapeReadKey: (resolved: ResolvedShape, identity: SubscriptionIdentity) => string | undefined;
2706
+ type ReadShapeCdcKeys = (sql: SqlExec, table: string, sinceSeq: number, upTo: number) => CdcChangeKey[];
2707
+ declare const buildShapeDiff: (sql: SqlExec, resolved: ResolvedShape, sinceSeq: number, upTo: number, cache: ShapeDiffCache, readKeys?: ReadShapeCdcKeys) => ShapeRowOp[];
1930
2708
  interface ShardRunnerOptions {
1931
2709
  handlers?: {
1932
2710
  handleAlarm?: () => Promise<void>;
@@ -1942,7 +2720,7 @@ declare class ShardRunner {
1942
2720
  socketFor(raw: unknown): ShardSocketLike;
1943
2721
  sockets(tag?: string): SocketHandle[];
1944
2722
  background(work: Promise<unknown>): boolean;
1945
- runInTransaction<T>(work: () => Promise<T>): Promise<T>;
2723
+ runInTransaction<T>(work: () => Promise<T>, onCommitted?: () => void): Promise<T>;
1946
2724
  handleFetch(request: Request): Promise<Response>;
1947
2725
  handleAlarm(): Promise<void>;
1948
2726
  }
@@ -1968,6 +2746,13 @@ interface SqlDiagnostic {
1968
2746
  source: "gate" | "plan" | "syntax";
1969
2747
  }
1970
2748
  declare const lintReadonlySql: (sql: SqlExec, query: string) => SqlLintResult;
2749
+ declare const BIGINT_KEY_DIGITS = 39;
2750
+ declare const bigintSqlKey: (value: bigint) => string;
2751
+ declare const decodeBigintSqlKey: (raw: string) => bigint | undefined;
2752
+ declare const float64SqlKey: (value: number) => string;
2753
+ declare const decodeFloat64SqlKey: (raw: string) => number | undefined;
2754
+ declare const DELTA_PLACEHOLDER_TABLE = "__lunora__";
2755
+ declare const deltaTableFor: (tables: Iterable<string>) => string;
1971
2756
  declare const subscriptionListDeltas: (previousJson: string, nextResult: unknown, table: string, frames?: string[]) => MutationDelta[] | undefined;
1972
2757
  interface FrameSink {
1973
2758
  send: (data: string) => void;
@@ -1976,7 +2761,18 @@ interface DrainableSink {
1976
2761
  readonly bufferedAmount?: unknown;
1977
2762
  }
1978
2763
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1979
- declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string, lastMutationId?: number) => boolean;
2764
+ interface SubscriptionFrameInput {
2765
+ cursorSuffix: string;
2766
+ diffKey?: object;
2767
+ lastMutationId?: number;
2768
+ nextResult: unknown;
2769
+ pageDeltas?: boolean;
2770
+ previousJson?: string;
2771
+ snapshotJson: string;
2772
+ subId: string;
2773
+ table: string;
2774
+ }
2775
+ declare const subscriptionFrames: (input: SubscriptionFrameInput) => string[];
1980
2776
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1981
2777
  interface SubscriptionReadFootprint {
1982
2778
  ranges?: Map<string, KeyRange[]>;
@@ -2004,13 +2800,32 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
2004
2800
  hasMore: boolean;
2005
2801
  ids: string[];
2006
2802
  };
2007
- type FieldRefSql = (field: string) => SQL;
2008
- type SerializeValue = (value: unknown) => unknown;
2009
- interface WhereSqlStrategy {
2010
- fieldRef: FieldRefSql;
2011
- likeContains?: (reference: SQL, term: SQL) => SQL;
2012
- relationExists?: (request: unknown) => SQL;
2013
- serialize: SerializeValue;
2803
+ declare const isTtlExpired: (sql: SqlExec, spec: TtlSweepSpec, id: string, now: number) => boolean;
2804
+ declare const nextTtlExpiry: (sql: SqlExec, spec: TtlSweepSpec) => number | undefined;
2805
+ declare const VECTOR_BACKFILL_MAX_PAGES = 20;
2806
+ interface VectorBackfillTarget {
2807
+ profile: string;
2808
+ table: string;
2809
+ }
2810
+ interface VectorBackfillProgress {
2811
+ done: boolean;
2812
+ error?: string;
2813
+ failed: number;
2814
+ failedIds: string[];
2815
+ pages: number;
2816
+ rows: number;
2014
2817
  }
2015
- declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2016
- 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, REPROJECTION_MIGRATION_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, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, 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, reprojectableFields, reprojectionMigrationId, reprojectionTables, 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 };
2818
+ type VectorPageSync = (table: string, rows: ReadonlyArray<{
2819
+ doc: Record<string, unknown>;
2820
+ id: string;
2821
+ }>) => Promise<ReadonlyArray<{
2822
+ error: unknown;
2823
+ id: string;
2824
+ }>>;
2825
+ type OrderedAfterWrites = <T, U>(read: () => T, work: (value: T) => Promise<U>) => Promise<U>;
2826
+ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<VectorBackfillTarget>, sync: VectorPageSync, options: {
2827
+ maxPages?: number;
2828
+ ordered: OrderedAfterWrites;
2829
+ restart?: boolean;
2830
+ }) => Promise<VectorBackfillProgress>;
2831
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, ADMIN_WILDCARD, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, 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, DELTA_PLACEHOLDER_TABLE, 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 ImportConflictMode, type ImportError, type ImportRow, 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 ScheduleOutboxEntry, 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 TransactionLimitKind, type TransactionLimitWarning, 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, adminTokenExists, 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, createAdminTokenRecord, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, deltaTableFor, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findManyPage, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, 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, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, 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, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };