@supalive/core 1.16.0 → 1.17.0

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 (80) hide show
  1. package/dist/index-B2nE1y9E.d.ts +2384 -0
  2. package/dist/index-B2nE1y9E.d.ts.map +1 -0
  3. package/dist/index-B5hAqW3O.d.ts +2402 -0
  4. package/dist/index-B5hAqW3O.d.ts.map +1 -0
  5. package/dist/index-BI3MfAyI.d.ts +2399 -0
  6. package/dist/index-BI3MfAyI.d.ts.map +1 -0
  7. package/dist/index-BL90lDw7.d.ts +2400 -0
  8. package/dist/index-BL90lDw7.d.ts.map +1 -0
  9. package/dist/index-BvryqYUm.d.ts +2394 -0
  10. package/dist/index-BvryqYUm.d.ts.map +1 -0
  11. package/dist/index-DYkOBnw_.d.ts +2378 -0
  12. package/dist/index-DYkOBnw_.d.ts.map +1 -0
  13. package/dist/index-DcM2uKpT.d.ts +2393 -0
  14. package/dist/index-DcM2uKpT.d.ts.map +1 -0
  15. package/dist/index-DsvdhOKL.d.ts +2400 -0
  16. package/dist/index-DsvdhOKL.d.ts.map +1 -0
  17. package/dist/mysql-BJaQhVGE.d.ts +114 -0
  18. package/dist/mysql-BJaQhVGE.d.ts.map +1 -0
  19. package/dist/mysql-BKs5PTSR.d.ts +114 -0
  20. package/dist/mysql-BKs5PTSR.d.ts.map +1 -0
  21. package/dist/mysql-C7Km_lgc.d.ts +114 -0
  22. package/dist/mysql-C7Km_lgc.d.ts.map +1 -0
  23. package/dist/mysql-Cxro4f6T.d.ts +114 -0
  24. package/dist/mysql-Cxro4f6T.d.ts.map +1 -0
  25. package/dist/mysql-DNiYIZCK.d.ts +114 -0
  26. package/dist/mysql-DNiYIZCK.d.ts.map +1 -0
  27. package/dist/mysql-DS1s1c5M.d.ts +114 -0
  28. package/dist/mysql-DS1s1c5M.d.ts.map +1 -0
  29. package/dist/mysql-qTszEKAU.d.ts +114 -0
  30. package/dist/mysql-qTszEKAU.d.ts.map +1 -0
  31. package/dist/mysql-qW13LcGQ.d.ts +114 -0
  32. package/dist/mysql-qW13LcGQ.d.ts.map +1 -0
  33. package/dist/postgres-B0fqJe1X.d.ts +118 -0
  34. package/dist/postgres-B0fqJe1X.d.ts.map +1 -0
  35. package/dist/postgres-BATDLPml.d.ts +118 -0
  36. package/dist/postgres-BATDLPml.d.ts.map +1 -0
  37. package/dist/postgres-BUVYjnaT.d.ts +118 -0
  38. package/dist/postgres-BUVYjnaT.d.ts.map +1 -0
  39. package/dist/postgres-Bk_8PFRT.d.ts +118 -0
  40. package/dist/postgres-Bk_8PFRT.d.ts.map +1 -0
  41. package/dist/postgres-Bx79_JEy.d.ts +118 -0
  42. package/dist/postgres-Bx79_JEy.d.ts.map +1 -0
  43. package/dist/postgres-C3w741VH.d.ts +118 -0
  44. package/dist/postgres-C3w741VH.d.ts.map +1 -0
  45. package/dist/postgres-CAZYYgbZ.d.ts +118 -0
  46. package/dist/postgres-CAZYYgbZ.d.ts.map +1 -0
  47. package/dist/postgres-bhVzeRf2.d.ts +118 -0
  48. package/dist/postgres-bhVzeRf2.d.ts.map +1 -0
  49. package/dist/router-Bk0eLfmB.js +285 -0
  50. package/dist/router-Bk0eLfmB.js.map +1 -0
  51. package/dist/router-DP2ThAwh.js.map +1 -1
  52. package/dist/src/client/index.d.ts +2 -2
  53. package/dist/src/client/index.js +17 -4
  54. package/dist/src/client/index.js.map +1 -1
  55. package/dist/src/exports/mysql.d.ts +1 -1
  56. package/dist/src/exports/postgres.d.ts +1 -1
  57. package/dist/src/exports/procedure.d.ts +1 -1
  58. package/dist/src/exports/schema-sql.d.ts +1 -1
  59. package/dist/src/exports/server.d.ts +5 -4
  60. package/dist/src/exports/server.d.ts.map +1 -1
  61. package/dist/src/exports/server.js +20 -10
  62. package/dist/src/exports/server.js.map +1 -1
  63. package/dist/src/exports/types.d.ts +2 -2
  64. package/dist/types_server-AXVa_2mF.d.ts +684 -0
  65. package/dist/types_server-AXVa_2mF.d.ts.map +1 -0
  66. package/dist/types_server-CUPM08l2.d.ts +684 -0
  67. package/dist/types_server-CUPM08l2.d.ts.map +1 -0
  68. package/dist/types_server-CtYRmHdO.d.ts +684 -0
  69. package/dist/types_server-CtYRmHdO.d.ts.map +1 -0
  70. package/dist/types_server-DHRi8bGO.d.ts +684 -0
  71. package/dist/types_server-DHRi8bGO.d.ts.map +1 -0
  72. package/dist/types_server-DoeybfmY.d.ts +684 -0
  73. package/dist/types_server-DoeybfmY.d.ts.map +1 -0
  74. package/dist/types_server-JK14NE0j.d.ts +684 -0
  75. package/dist/types_server-JK14NE0j.d.ts.map +1 -0
  76. package/dist/types_server-hYv2--1M.d.ts +684 -0
  77. package/dist/types_server-hYv2--1M.d.ts.map +1 -0
  78. package/dist/types_server-kkQJDSjA.d.ts +684 -0
  79. package/dist/types_server-kkQJDSjA.d.ts.map +1 -0
  80. package/package.json +1 -1
@@ -0,0 +1,2384 @@
1
+ import { r as ObjectStorage } from "./object-storage-354KU6Mj.js";
2
+ import z, { ZodRawShape, ZodType, z as z$1 } from "zod";
3
+ import { Span } from "@opentelemetry/api";
4
+ import { RetryPolicy } from "cockatiel";
5
+ import Redis$1 from "ioredis";
6
+ import { Redis as Redis$2 } from "@upstash/redis";
7
+
8
+ //#region src/db/types_db.d.ts
9
+ /** Monotonically increasing integer from global_commit_ts sequence in Postgres */
10
+ type CommitTs = bigint;
11
+ declare const BigIntSchema: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
12
+ declare const CompareOperatorSchema: z.ZodEnum<{
13
+ "=": "=";
14
+ "!=": "!=";
15
+ ">": ">";
16
+ ">=": ">=";
17
+ "<": "<";
18
+ "<=": "<=";
19
+ like: "like";
20
+ ilike: "ilike";
21
+ contains: "contains";
22
+ icontains: "icontains";
23
+ between: "between";
24
+ in: "in";
25
+ jsonContains: "jsonContains";
26
+ jsonContainedBy: "jsonContainedBy";
27
+ jsonHasKey: "jsonHasKey";
28
+ jsonArrayContains: "jsonArrayContains";
29
+ isNull: "isNull";
30
+ isNotNull: "isNotNull";
31
+ }>;
32
+ type CompareOperator = z.infer<typeof CompareOperatorSchema>;
33
+ type Predicate = LeafPredicate | {
34
+ kind: "and";
35
+ children: Predicate[];
36
+ } | {
37
+ kind: "or";
38
+ children: Predicate[];
39
+ };
40
+ declare const PredicateSchema: z.ZodType<Predicate>;
41
+ declare const LeafPredicateSchema: z.ZodObject<{
42
+ kind: z.ZodLiteral<"leaf">;
43
+ column: z.ZodString;
44
+ operator: z.ZodEnum<{
45
+ "=": "=";
46
+ "!=": "!=";
47
+ ">": ">";
48
+ ">=": ">=";
49
+ "<": "<";
50
+ "<=": "<=";
51
+ like: "like";
52
+ ilike: "ilike";
53
+ contains: "contains";
54
+ icontains: "icontains";
55
+ between: "between";
56
+ in: "in";
57
+ jsonContains: "jsonContains";
58
+ jsonContainedBy: "jsonContainedBy";
59
+ jsonHasKey: "jsonHasKey";
60
+ jsonArrayContains: "jsonArrayContains";
61
+ isNull: "isNull";
62
+ isNotNull: "isNotNull";
63
+ }>;
64
+ value: z.ZodUnknown;
65
+ value2: z.ZodOptional<z.ZodUnknown>;
66
+ raw: z.ZodOptional<z.ZodBoolean>;
67
+ path: z.ZodOptional<z.ZodString>;
68
+ mode: z.ZodOptional<z.ZodEnum<{
69
+ one: "one";
70
+ all: "all";
71
+ }>>;
72
+ }, z.core.$strip>;
73
+ type LeafPredicate = z.infer<typeof LeafPredicateSchema>;
74
+ declare const AndPredicateSchema: z.ZodObject<{
75
+ kind: z.ZodLiteral<"and">;
76
+ children: z.ZodArray<z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>>;
77
+ }, z.core.$strip>;
78
+ type AndPredicate = z.infer<typeof AndPredicateSchema>;
79
+ declare const OrPredicateSchema: z.ZodObject<{
80
+ kind: z.ZodLiteral<"or">;
81
+ children: z.ZodArray<z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>>;
82
+ }, z.core.$strip>;
83
+ type OrPredicate = z.infer<typeof OrPredicateSchema>;
84
+ /** Query specification - what was queried (used for cache key generation) */
85
+ type QuerySpec = ReadEntry;
86
+ declare function normalizeIdToBytes(id: string | number, fromHex?: boolean): Uint8Array;
87
+ declare function normalizeToBytes(value: Uint8Array | unknown): Uint8Array;
88
+ declare function bytesFromJson(value: Uint8Array | unknown): Uint8Array;
89
+ declare const PointReadSchema: z.ZodObject<{
90
+ kind: z.ZodLiteral<"point">;
91
+ table: z.ZodString;
92
+ id: z.ZodString;
93
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
94
+ }, z.core.$strip>;
95
+ type PointRead = z.infer<typeof PointReadSchema>;
96
+ declare const RawPointReadSchema: z.ZodObject<{
97
+ kind: z.ZodLiteral<"point">;
98
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
99
+ id: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
100
+ table: z.ZodString;
101
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
102
+ }, z.core.$strip>;
103
+ type RawPointRead = z.infer<typeof RawPointReadSchema>;
104
+ /**
105
+ * Query specification for a range read (get with filters).
106
+ * This is the query definition, not the result.
107
+ */
108
+ declare const RangeReadSchema: z.ZodObject<{
109
+ kind: z.ZodLiteral<"range">;
110
+ table: z.ZodString;
111
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
112
+ columns: z.ZodArray<z.ZodString>;
113
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
114
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
115
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
116
+ }, z.core.$strip>;
117
+ type RangeRead = z.infer<typeof RangeReadSchema>;
118
+ declare const RawRangeReadSchema: z.ZodObject<{
119
+ kind: z.ZodLiteral<"range">;
120
+ table: z.ZodString;
121
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
122
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
123
+ columns: z.ZodArray<z.ZodString>;
124
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
125
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
126
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
127
+ }, z.core.$strip>;
128
+ type RawRangeRead = z.infer<typeof RawRangeReadSchema>;
129
+ declare const ReadEntrySchema: z.ZodUnion<readonly [z.ZodObject<{
130
+ kind: z.ZodLiteral<"point">;
131
+ table: z.ZodString;
132
+ id: z.ZodString;
133
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
134
+ }, z.core.$strip>, z.ZodObject<{
135
+ kind: z.ZodLiteral<"range">;
136
+ table: z.ZodString;
137
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
138
+ columns: z.ZodArray<z.ZodString>;
139
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
140
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
141
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
142
+ }, z.core.$strip>]>;
143
+ type ReadEntry = z.infer<typeof ReadEntrySchema>;
144
+ declare const RawReadEntrySchema: z.ZodUnion<readonly [z.ZodObject<{
145
+ kind: z.ZodLiteral<"point">;
146
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
147
+ id: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
148
+ table: z.ZodString;
149
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
150
+ }, z.core.$strip>, z.ZodObject<{
151
+ kind: z.ZodLiteral<"range">;
152
+ table: z.ZodString;
153
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
154
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
155
+ columns: z.ZodArray<z.ZodString>;
156
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
157
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
158
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
159
+ }, z.core.$strip>]>;
160
+ type RawReadEntry = z.infer<typeof RawReadEntrySchema>;
161
+ declare const WriteOpSchema: z.ZodEnum<{
162
+ insert: "insert";
163
+ update: "update";
164
+ delete: "delete";
165
+ }>;
166
+ type WriteOp = z.infer<typeof WriteOpSchema>;
167
+ declare const WriteEntrySchema: z.ZodObject<{
168
+ table: z.ZodString;
169
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
170
+ id: z.ZodString;
171
+ op: z.ZodEnum<{
172
+ insert: "insert";
173
+ update: "update";
174
+ delete: "delete";
175
+ }>;
176
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
177
+ prevData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
178
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
179
+ }, z.core.$strip>;
180
+ type WriteEntry = z.infer<typeof WriteEntrySchema>;
181
+ interface CommitLogEntry {
182
+ id: Uint8Array;
183
+ ts: bigint;
184
+ tableId: Uint8Array;
185
+ data: Uint8Array;
186
+ _parsedData?: Record<string, unknown> | null;
187
+ }
188
+ interface MutationResult<T> {
189
+ result: T;
190
+ writeSet: WriteEntry[];
191
+ commitTs: CommitTs;
192
+ }
193
+ interface LiveResult<T> {
194
+ ts: bigint;
195
+ data: T;
196
+ readSet: ReadEntry[];
197
+ }
198
+ declare const QueryCacheMetadataSchema: z.ZodObject<{
199
+ lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
200
+ version: z.ZodString;
201
+ readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
202
+ kind: z.ZodLiteral<"point">;
203
+ table: z.ZodString;
204
+ id: z.ZodString;
205
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
206
+ }, z.core.$strip>, z.ZodObject<{
207
+ kind: z.ZodLiteral<"range">;
208
+ table: z.ZodString;
209
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
210
+ columns: z.ZodArray<z.ZodString>;
211
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
212
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
213
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
214
+ }, z.core.$strip>]>>;
215
+ }, z.core.$strip>;
216
+ type QueryCacheMetadata = z.infer<typeof QueryCacheMetadataSchema>;
217
+ declare const QueryCacheEntrySchema: z.ZodObject<{
218
+ lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
219
+ data: z.ZodUnknown;
220
+ version: z.ZodString;
221
+ }, z.core.$strip>;
222
+ type QueryCacheEntry = z.infer<typeof QueryCacheEntrySchema>;
223
+ declare const CachedPgMetadataSchema: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodString>>;
224
+ type CachedPgMetadata = z.infer<typeof CachedPgMetadataSchema>;
225
+ interface RetryConfig {
226
+ maxAttempts: number;
227
+ backoff: "none" | "linear" | "exponential";
228
+ delayMs?: number;
229
+ onConflict?: (attempt: number, error: OccConflictError) => void;
230
+ }
231
+ declare const NO_RETRY: RetryConfig;
232
+ declare const DEFAULT_RETRY: RetryConfig;
233
+ declare class OccConflictError extends Error {
234
+ readonly reason: string;
235
+ readonly conflictDetail?: unknown | undefined;
236
+ constructor(reason: string, conflictDetail?: unknown | undefined);
237
+ static isOccConflictError(err: unknown): boolean;
238
+ }
239
+ declare class OccAbortError extends Error {
240
+ constructor(message: string);
241
+ }
242
+ //#endregion
243
+ //#region src/server/sub-manager-types.d.ts
244
+ declare const RegisterSubscriptionParamsSchema: z.ZodObject<{
245
+ subId: z.ZodString;
246
+ cacheKey: z.ZodString;
247
+ queryName: z.ZodString;
248
+ args: z.ZodUnknown;
249
+ queryIdentity: z.ZodString;
250
+ instanceName: z.ZodString;
251
+ lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
252
+ }, z.core.$strip>;
253
+ type RegisterSubscriptionParams = z.infer<typeof RegisterSubscriptionParamsSchema>;
254
+ declare const RegisterSubscriptionResultSchema: z.ZodObject<{
255
+ cacheKey: z.ZodString;
256
+ recompute: z.ZodBoolean;
257
+ readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
258
+ kind: z.ZodLiteral<"point">;
259
+ table: z.ZodString;
260
+ id: z.ZodString;
261
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
262
+ }, z.core.$strip>, z.ZodObject<{
263
+ kind: z.ZodLiteral<"range">;
264
+ table: z.ZodString;
265
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
266
+ columns: z.ZodArray<z.ZodString>;
267
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
268
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
269
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
270
+ }, z.core.$strip>]>>;
271
+ version: z.ZodOptional<z.ZodString>;
272
+ }, z.core.$strip>;
273
+ type RegisterSubscriptionResult = z.infer<typeof RegisterSubscriptionResultSchema>;
274
+ declare const UpdateSubscriptionReadSetParamsSchema: z.ZodObject<{
275
+ cacheKey: z.ZodString;
276
+ subId: z.ZodString;
277
+ instanceName: z.ZodString;
278
+ lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
279
+ readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
280
+ kind: z.ZodLiteral<"point">;
281
+ table: z.ZodString;
282
+ id: z.ZodString;
283
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
284
+ }, z.core.$strip>, z.ZodObject<{
285
+ kind: z.ZodLiteral<"range">;
286
+ table: z.ZodString;
287
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
288
+ columns: z.ZodArray<z.ZodString>;
289
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
290
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
291
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
292
+ }, z.core.$strip>]>>;
293
+ }, z.core.$strip>;
294
+ type UpdateSubscriptionReadSetParams = z.infer<typeof UpdateSubscriptionReadSetParamsSchema>;
295
+ /**
296
+ * `tracked: false` means the sub-manager has no record of this subId (e.g.
297
+ * a restart wiped state and the caller hasn't re-registered yet). The app
298
+ * server should treat this as a signal to register the sub before retrying.
299
+ */
300
+ declare const UpdateSubscriptionReadSetResultSchema: z.ZodObject<{
301
+ tracked: z.ZodBoolean;
302
+ }, z.core.$strip>;
303
+ type UpdateSubscriptionReadSetResult = z.infer<typeof UpdateSubscriptionReadSetResultSchema>;
304
+ declare const UnregisterSubscriptionParamsSchema: z.ZodObject<{
305
+ subId: z.ZodString;
306
+ instanceName: z.ZodString;
307
+ }, z.core.$strip>;
308
+ type UnregisterSubscriptionParams = z.infer<typeof UnregisterSubscriptionParamsSchema>;
309
+ declare const UnregisterSubscriptionsParamsSchema: z.ZodArray<z.ZodObject<{
310
+ subId: z.ZodString;
311
+ instanceName: z.ZodString;
312
+ }, z.core.$strip>>;
313
+ type UnregisterSubscriptionsParams = z.infer<typeof UnregisterSubscriptionsParamsSchema>;
314
+ declare const UnregisterSubscriptionResultSchema: z.ZodObject<{
315
+ ok: z.ZodBoolean;
316
+ }, z.core.$strip>;
317
+ type UnregisterSubscriptionResult = z.infer<typeof UnregisterSubscriptionResultSchema>;
318
+ declare const UnregisterSubscriptionsResultSchema: z.ZodArray<z.ZodObject<{
319
+ ok: z.ZodBoolean;
320
+ }, z.core.$strip>>;
321
+ type UnregisterSubscriptionsResult = z.infer<typeof UnregisterSubscriptionsResultSchema>;
322
+ declare const InvalidateWritesetParamsSchema: z.ZodObject<{
323
+ writeSet: z.ZodArray<z.ZodObject<{
324
+ table: z.ZodString;
325
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
326
+ id: z.ZodString;
327
+ op: z.ZodEnum<{
328
+ insert: "insert";
329
+ update: "update";
330
+ delete: "delete";
331
+ }>;
332
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
333
+ prevData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
334
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
335
+ }, z.core.$strip>>;
336
+ }, z.core.$strip>;
337
+ type InvalidateWritesetParams = z.infer<typeof InvalidateWritesetParamsSchema>;
338
+ declare const AffectedSubscriptionSchema: z.ZodObject<{
339
+ subId: z.ZodString;
340
+ queryName: z.ZodString;
341
+ args: z.ZodUnknown;
342
+ cacheKey: z.ZodString;
343
+ notifyInstances: z.ZodArray<z.ZodString>;
344
+ }, z.core.$strip>;
345
+ type AffectedSubscription = z.infer<typeof AffectedSubscriptionSchema>;
346
+ declare const InvalidateWritesetResultSchema: z.ZodObject<{
347
+ affected: z.ZodArray<z.ZodObject<{
348
+ subId: z.ZodString;
349
+ queryName: z.ZodString;
350
+ args: z.ZodUnknown;
351
+ cacheKey: z.ZodString;
352
+ notifyInstances: z.ZodArray<z.ZodString>;
353
+ }, z.core.$strip>>;
354
+ }, z.core.$strip>;
355
+ type InvalidateWritesetResult = z.infer<typeof InvalidateWritesetResultSchema>;
356
+ declare const RegistrationRecordSchema: z.ZodObject<{
357
+ queryName: z.ZodString;
358
+ args: z.ZodUnknown;
359
+ queryIdentity: z.ZodString;
360
+ cacheKey: z.ZodString;
361
+ }, z.core.$strip>;
362
+ type RegistrationRecord = z.infer<typeof RegistrationRecordSchema>;
363
+ //#endregion
364
+ //#region src/db/cache.d.ts
365
+ declare class CacheLayer {
366
+ redis: Redis$1 | Redis$2;
367
+ private readonly ttlSeconds;
368
+ /** Cached EVALSHA digests keyed by Lua source (see evalScript). */
369
+ private readonly scriptShaCache;
370
+ constructor(upstash: Redis$1 | Redis$2, ttlSeconds?: number);
371
+ /**
372
+ * Run a Lua script via EVALSHA using the script's SHA1 (computed locally — the
373
+ * same digest Redis keys scripts by, so no SCRIPT LOAD round-trip is needed on
374
+ * the hot path). On NOSCRIPT (the script isn't in Redis's cache yet, e.g. first
375
+ * use or after a Redis restart/failover) load it explicitly via SCRIPT LOAD and
376
+ * re-run via EVALSHA — so the script ends up cached server-side and subsequent
377
+ * EVALSHA calls hit. The runtime client is always ioredis (see initCacheLayer).
378
+ */
379
+ private evalScript;
380
+ /** One-shot recompute: atomically write data + metadata (CAS on version). */
381
+ setQueryCacheAndMetadataFor(cacheKey: string, data: unknown, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
382
+ /** Subscribe path: write the data blob only (CAS against the metadata's
383
+ * version). The metadata is written separately by the sub-worker; the
384
+ * `version` links the two so a divergent pair is detected on read. Takes the
385
+ * snapshot ts directly (rather than a pre-stringified version) so the entry
386
+ * can carry `lastSnapshotTs` as its own field; `version` is derived from it,
387
+ * preserving the `version === String(ts)` convention the CAS relies on. */
388
+ setQueryCacheFor(cacheKey: string, data: unknown, lastSnapshotTs: bigint, ttlSeconds?: number): Promise<void>;
389
+ getQueryCacheFor(cacheKey: string): Promise<QueryCacheEntry | null>;
390
+ /** Subscription recompute: replace the whole metadata (CAS on version). */
391
+ replaceQueryCacheMetadata(cacheKey: string, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
392
+ /** Still-fresh subscription: advance `lastSnapshotTs` only, preserving the
393
+ * data's `version` + `readSet` (no recompute). Monotonic and non-clobbering
394
+ * — see ADVANCE_META. `metaData` carries the new horizon plus the version +
395
+ * readSet the caller read, which the script keeps unless a newer computation
396
+ * has since landed. */
397
+ advanceQueryCacheMetadata(cacheKey: string, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
398
+ getQueryCacheMetaData(cacheKey: string): Promise<QueryCacheMetadata | null>;
399
+ persistRegistrationRecord(subId: string, record: RegistrationRecord): Promise<void>;
400
+ deleteRegistrationRecord(subId: string): Promise<void>;
401
+ deleteRegistrationsRecord(subIds: string[]): Promise<void>;
402
+ fetchRegistrationRecordsBatch(subIds: string[]): Promise<Map<string, RegistrationRecord | null>>;
403
+ getCachedTableColumnTypes(key: string): Promise<CachedPgMetadata | null>;
404
+ setCachedTableColumnsTypes(key: string, value: CachedPgMetadata): Promise<void>;
405
+ /**
406
+ * Race participant: try to claim `lock:recompute:<subId>:<commitTs>`
407
+ * with `SET NX EX`. The single Redis round-trip both arbitrates and
408
+ * sets a TTL fallback in case the winner crashes mid-recompute.
409
+ */
410
+ tryAcquireRecomputeLock(instanceId: string, subId: string, commitTs: string, ttl: number): Promise<boolean>;
411
+ private getRegistrationKey;
412
+ private getQueryCacheDataKey;
413
+ private getQeruyCacheMetaKey;
414
+ }
415
+ //#endregion
416
+ //#region src/db/db.d.ts
417
+ interface DbQueryResult<T = any> {
418
+ rows: T[];
419
+ rowCount?: number | null;
420
+ /**
421
+ * Auto-increment / LAST_INSERT_ID value from the driver, when applicable
422
+ * (MySQL `ResultSetHeader.insertId`). Used to read the advanced value back
423
+ * from `UPDATE ... SET id = LAST_INSERT_ID(id + 1)` without a second
424
+ * round-trip. Undefined for Postgres / SELECTs.
425
+ */
426
+ insertId?: number | bigint;
427
+ }
428
+ interface RawClient {
429
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
430
+ }
431
+ interface PooledClient extends RawClient {
432
+ release(): void;
433
+ }
434
+ type DbType = "postgres" | "mysql";
435
+ interface PendingPointEntry {
436
+ entry: PointRead;
437
+ key: string;
438
+ }
439
+ interface PreparedQuery {
440
+ sql: string;
441
+ params: unknown[] | unknown[][];
442
+ operation: "insertSingle" | "insertBatch" | "updateSingle" | "updateBatch" | "deleteSingle" | "deleteBatch" | "pointReadValidation" | "commit_logs";
443
+ table: string;
444
+ entryId?: unknown;
445
+ expectedTs?: bigint;
446
+ entries?: WriteEntry[];
447
+ pendingsEntry?: PendingPointEntry[];
448
+ }
449
+ interface PreparedQueries {
450
+ commits: PreparedQuery[];
451
+ validateReadPoints?: PreparedQuery[];
452
+ hasRangeRead: boolean;
453
+ tableIds?: Uint8Array[];
454
+ rawReadSet?: RawReadEntry[];
455
+ }
456
+ /**
457
+ * Bound to a single dedicated connection that holds the core-init lock. Passed
458
+ * to the callback of {@link Database.withCoreInitLock} so version reads/writes
459
+ * and migration statements all run under the same lock.
460
+ */
461
+ interface CoreInitLockCtx {
462
+ exec(sql: string, params?: unknown[]): Promise<DbQueryResult>;
463
+ getVersion(): Promise<bigint>;
464
+ setVersion(version: bigint): Promise<void>;
465
+ }
466
+ interface Database {
467
+ readonly dbType: DbType;
468
+ readonly sqlBuilder: SqlBuilder;
469
+ columnTypes: Map<string, Map<string, string>>;
470
+ /**
471
+ * Current core schema version stored in `metadata.core_version`, or `0n`
472
+ * when unset. Read on a pooled connection for the lock-free fast path of
473
+ * {@link initCore}.
474
+ */
475
+ getCoreVersion(): Promise<bigint>;
476
+ /**
477
+ * The app's current schema-migration marker, stored in
478
+ * `metadata.app_migration`, or `0n` when unset. This is the 14-digit
479
+ * timestamp of the last applied migration file (e.g. `20260726112333` for
480
+ * `0001_20260726112333.sql`), written by the deploy pipeline's tracked
481
+ * migrate step. Used to key the bootstrap column-type cache
482
+ * (`supalive:schema:types:<app_migration>`) so a schema change automatically
483
+ * invalidates cold instances' cached types — see `bootstrapDbTypes`.
484
+ */
485
+ getAppMigration(): Promise<bigint>;
486
+ /**
487
+ * Runtime bootstrap statements to apply when migrating core TO `toVersion`
488
+ * (i.e. the `toVersion - 1` → `toVersion` step): data seeds, backfills, or a
489
+ * schema change that must be applied directly at runtime. Dialect-specific;
490
+ * the core schema (tables, indexes, the `global_commit_ts` sequence/counter)
491
+ * lives in the generated schema instead — see `coreTablesSql`.
492
+ */
493
+ coreMigrationStatements(toVersion: bigint): string[];
494
+ /**
495
+ * Run `fn` while holding the cross-process core-init lock (PG
496
+ * `pg_advisory_xact_lock`, MySQL `GET_LOCK`) on a single dedicated
497
+ * connection, so concurrent servers can't race the core migration. All of
498
+ * `fn`'s work runs on that locked connection via {@link CoreInitLockCtx}.
499
+ */
500
+ withCoreInitLock(fn: (ctx: CoreInitLockCtx) => Promise<void>): Promise<void>;
501
+ bootstrapColumnTypes(opts: {
502
+ redis?: CacheLayer;
503
+ cacheKey: string;
504
+ tables?: string[];
505
+ }): Promise<void>;
506
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
507
+ getClient(): Promise<PooledClient>;
508
+ getTransactionClient(): Promise<TxDatabase>;
509
+ getLatestSnapshotTimestamp(): Promise<bigint>;
510
+ updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;
511
+ /**
512
+ * The retention watermark: the boundary `ts` below which commit_logs have
513
+ * been pruned, so any cache entry whose `lastSnapshotTs` is below it can no
514
+ * longer be freshness-checked (its scan window would miss deleted rows) and
515
+ * must be recomputed. Persisted in the `metadata` table (survives restarts)
516
+ * as a cheap PK read — callers load it into an in-memory variable at startup
517
+ * and keep it fresh via pub/sub rather than reading it per query. Returns the
518
+ * -1n genesis when nothing has been pruned yet (matching the empty-DB snapshot
519
+ * ts), so every entry is scannable.
520
+ */
521
+ getMinSnapshotTimestamp(): Promise<bigint>;
522
+ /**
523
+ * Advance the retention watermark. Monotonic: only ever moves forward (a
524
+ * stale writer can never lower it). Called by the sub-manager right before it
525
+ * prunes commit_logs below `ts`.
526
+ */
527
+ updateMinSnapshotTimestamp(ts: bigint): Promise<void>;
528
+ getNextTimestamp(): Promise<bigint>;
529
+ prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;
530
+ commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{
531
+ success: boolean;
532
+ }>;
533
+ close(): Promise<void>;
534
+ /**
535
+ * Delete commit_logs older than `ts` (exclusive). Used by the periodic
536
+ * retention sweep in SubscriptionManager so the table doesn't grow
537
+ * unbounded.
538
+ */
539
+ pruneCommitLogsBefore(ts: bigint): Promise<bigint>;
540
+ /**
541
+ * Oldest `ts` still present in commit_logs (i.e. the retention watermark
542
+ * after the last prune), or `null` when the table is empty. A cache entry
543
+ * whose `lastSnapshotTs` is below it can no longer be freshness-checked via
544
+ * {@link getCommitLogsBetweenTs} (the logs it would need were pruned), so the
545
+ * one-shot/register cache paths recompute instead of trusting it.
546
+ */
547
+ getMinCommitLogTs(): Promise<bigint | null>;
548
+ /**
549
+ * Half-open range scan: ts >= beginTs AND ts < endTs. Used by the
550
+ * subscription-recovery path to replay logs in a specific time window.
551
+ */
552
+ getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
553
+ /**
554
+ * Existence-only freshness probe for point reads: does any commit in the
555
+ * half-open window `[beginTs, endTs)` touch one of the exact `(tableId, id)`
556
+ * pairs in `points`? Returns as soon as one match is found.
557
+ *
558
+ * Point-read overlap is a pure key match (`checkPointReadOverlap`), so it can
559
+ * be answered entirely in SQL with a `(table_id, id)` tuple `IN` against the
560
+ * `commit_logs_by_table_and_id (table_id, id, ts)` index — no row `data`
561
+ * blobs fetched, no JSON parsed. This is the precise-filtering path used by
562
+ * {@link CacheFreshness} for tables whose read set is point-reads-only; tables
563
+ * that also carry a range read still go through {@link getCommitLogsBetweenTs}
564
+ * because their predicates must be evaluated in-app. `points` empty → `false`.
565
+ */
566
+ hasCommitForPoints(beginTs: bigint, endTs: bigint, points: {
567
+ tableId: Uint8Array;
568
+ id: Uint8Array;
569
+ }[]): Promise<boolean>;
570
+ /**
571
+ * Conflict-check scan for OCC: ts >= sinceTs AND ts <> excludeTs. The
572
+ * exclude is our own commitTs so we don't conflict with ourselves; the
573
+ * lack of an upper bound is intentional, so a concurrent peer that
574
+ * happens to have a higher commitTs but committed before us is still
575
+ * visible. (MVCC keeps in-flight peers invisible until they commit.)
576
+ */
577
+ getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
578
+ /**
579
+ * For each `update`/`delete` entry, attach `prevData` (consumed by the
580
+ * invalidator) and `expectedCommitTs` (the CAS fence).
581
+ *
582
+ * `expectedCommitTs` is preferentially copied from a prior point-read of
583
+ * the same row in `readSet` — that's the value the handler's logic
584
+ * actually depended on, so the CAS check enforces beginTs-level isolation
585
+ * for read-then-update patterns. If no prior read exists ("blind"
586
+ * write), we fall back to the value observed in this batch fetch (weak
587
+ * OCC, sufficient for writes that don't depend on prior state).
588
+ *
589
+ * `prevData` always comes from this batch fetch (SELECT * per table) so
590
+ * the invalidator has the full row regardless of which columns the
591
+ * handler's read selected.
592
+ *
593
+ * If the target row no longer exists at fetch time, `expectedCommitTs`
594
+ * is left undefined and the per-row CAS will match nothing — surfaced
595
+ * as OccConflictError.
596
+ */
597
+ attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;
598
+ }
599
+ interface TxDatabase extends Database {
600
+ begin(): Promise<void>;
601
+ commit(): Promise<void>;
602
+ rollback(): Promise<void>;
603
+ release(): void;
604
+ }
605
+ interface JsonOpOptions$1 {
606
+ /**
607
+ * When true, the bound `value` parameter is treated as already prepared
608
+ * for the underlying SQL (e.g. a literal JSON path string for
609
+ * jsonHasKey, a JSON-encoded literal for the contains family). When
610
+ * false/omitted, the value was prepared client-side from a JS value.
611
+ */
612
+ raw?: boolean;
613
+ /**
614
+ * 1-based positional index of an extra bound parameter holding a
615
+ * jsonpath that scopes the contains-family check to a sub-document of
616
+ * the target column. When omitted, the check runs against the whole
617
+ * column value.
618
+ */
619
+ pathIndex?: number;
620
+ /**
621
+ * jsonHasKey only: when set, multiple path parameters are bound starting
622
+ * at `paramIndex`, and the predicate evaluates whether any (`one`) or
623
+ * every (`all`) path exists in the column.
624
+ */
625
+ mode?: "one" | "all";
626
+ /** Number of bound path parameters in multi-path mode. */
627
+ pathCount?: number;
628
+ }
629
+ interface SqlBuilder {
630
+ placeholder(index: number): string;
631
+ like(col: string, paramIndex: number): string;
632
+ ilike(col: string, paramIndex: number): string;
633
+ icontains(col: string, paramIndex: number): string;
634
+ /** PG @> ; MySQL JSON_CONTAINS */
635
+ jsonContains(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
636
+ /** PG <@ ; MySQL JSON_CONTAINS(candidate, target) */
637
+ jsonContainedBy(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
638
+ /**
639
+ * Key/path existence. With `opts.raw === true`, the bound param is a JSON
640
+ * path expression (PG `jsonb_path_exists`, MySQL `JSON_CONTAINS_PATH`).
641
+ * Otherwise the bound param is a literal top-level key (PG `?`, MySQL
642
+ * `JSON_CONTAINS_PATH($."<key>")` with server-side quoting).
643
+ * With `opts.pathCount` set, emits the multi-path form keyed by `mode`.
644
+ */
645
+ jsonHasKey(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
646
+ /** Array membership: target array contains the given element. */
647
+ jsonArrayContains(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
648
+ }
649
+ declare class LazyCommitTsParam {
650
+ value: unknown;
651
+ constructor(value: unknown);
652
+ toPostgres(prepareValue: (value: any) => any): any;
653
+ toString(): any;
654
+ validate(): void;
655
+ }
656
+ //#endregion
657
+ //#region src/db/table-id.d.ts
658
+ /**
659
+ * Canonical table identifier: a fixed **16-byte** digest of the table name
660
+ * (UUID v3, which is MD5-based). A `tableId` is fully derived from the table
661
+ * name, so it is never stored redundantly — the query-cache `readSet` persists
662
+ * only `table` (the name) and reconstructs the bytes on read via
663
+ * {@link tableIdOf}. The physical `commit_logs.table_id` column (MySQL
664
+ * `BINARY(16)`, Postgres `BYTEA`) and its indexes hold these same bytes.
665
+ *
666
+ * A fixed 16 bytes (rather than the raw UTF-8 of the name) is required for
667
+ * MySQL: `BINARY(16)` would overflow on a table name longer than 16 bytes and
668
+ * zero-pad shorter ones (breaking byte-exact id matching). MD5 sidesteps both.
669
+ * Only used for equality (never decoded back to a name), so a non-cryptographic
670
+ * digest is fine. Browser-safe and synchronous (via the `uuid` package), which
671
+ * matters because this module is reachable from the client bundle.
672
+ */
673
+ declare function tableNameToId(tableName: string): Uint8Array;
674
+ //#endregion
675
+ //#region src/db/schema.d.ts
676
+ interface ColumnCodec<TData = unknown, TDriver = unknown> {
677
+ encode?: (value: TData) => TDriver;
678
+ decode?: (value: TDriver) => TData;
679
+ }
680
+ type SchemaCodecField<TSchema extends ZodRawShape, K extends PropertyKey> = K extends keyof TSchema ? TSchema[K] extends z$1.ZodTypeAny ? z$1.infer<TSchema[K]> : unknown : K extends keyof BaseSchema ? BaseSchema[K] extends z$1.ZodTypeAny ? z$1.infer<BaseSchema[K]> : unknown : unknown;
681
+ type SchemaCodecs<TSchema extends ZodRawShape> = Partial<{ [K in keyof (TSchema & BaseSchema)]: ColumnCodec<SchemaCodecField<TSchema, K>, any> }>;
682
+ interface SchemaColumnsOptions<TSchema extends ZodRawShape = ZodRawShape> {
683
+ codecs?: SchemaCodecs<TSchema>;
684
+ }
685
+ interface SchemaColumnMapping {
686
+ [key: string]: string;
687
+ }
688
+ interface DeclarativeIndex {
689
+ name: string;
690
+ columns: string[];
691
+ unique?: boolean;
692
+ type?: "btree" | "hash" | "gin" | "gist" | "spgist" | "brin";
693
+ where?: string;
694
+ using?: string;
695
+ options?: string;
696
+ tablespace?: string;
697
+ }
698
+ type IndexDefinition = string | DeclarativeIndex;
699
+ interface DefineSchemaConfig<TSchema extends ZodRawShape> {
700
+ name: string;
701
+ schema: TSchema;
702
+ options?: SchemaColumnsOptions<TSchema>;
703
+ columns?: SchemaColumnMapping;
704
+ indexes?: IndexDefinition[];
705
+ }
706
+ type CodecDataType<TCodec, TFallback> = [TCodec] extends [undefined] ? TFallback : TCodec extends {
707
+ decode: (...args: any[]) => infer TDecoded;
708
+ } ? TDecoded : TCodec extends ColumnCodec<infer TData, unknown> ? TData : TFallback;
709
+ type ZodOutput<TZod> = [TZod] extends [undefined] ? unknown : TZod extends z$1.ZodTypeAny ? z$1.infer<TZod> : unknown;
710
+ type ComputedDataType<TCodec, TZod> = CodecDataType<TCodec, ZodOutput<TZod>>;
711
+ type ComputedCodec<TData, TDriver> = ColumnCodec<TData, TDriver>;
712
+ type OverrideField<TObj, TKey extends PropertyKey, TValue> = Omit<TObj, TKey> & { [K in TKey]: TValue };
713
+ interface ComputedFieldConfig<TField extends string, TDecoded = unknown, TDriver = unknown, TZodType extends z$1.ZodTypeAny | undefined = undefined> {
714
+ field: TField;
715
+ sql: string;
716
+ alias?: string;
717
+ type?: TZodType;
718
+ codec?: {
719
+ decode: (value: TDriver) => TDecoded;
720
+ encode?: (value: TDecoded) => TDriver;
721
+ };
722
+ }
723
+ type ComputedField = {
724
+ field: string;
725
+ sql: string;
726
+ alias: string;
727
+ codec?: ColumnCodec<any, any>;
728
+ };
729
+ declare function defineComputedField<TField extends string, TDecoded = unknown, TDriver = unknown, TZodType extends z$1.ZodTypeAny | undefined = undefined>(config: ComputedFieldConfig<TField, TDecoded, TDriver, TZodType>): ComputedFieldConfig<TField, TDecoded, TDriver, TZodType>;
730
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
731
+ type ApplySchemaCodecs<TBase, TCodecs> = { [K in keyof TBase]: K extends keyof TCodecs ? CodecDataType<TCodecs[K], TBase[K]> : TBase[K] };
732
+ type ResolveSchemaType<TSchema extends ZodRawShape, TOptions extends SchemaColumnsOptions<TSchema>> = TOptions extends {
733
+ codecs: infer TCodecs;
734
+ } ? Prettify<ApplySchemaCodecs<z$1.infer<z$1.ZodObject<TSchema & BaseSchema>>, TCodecs>> : Prettify<z$1.infer<z$1.ZodObject<TSchema & BaseSchema>>>;
735
+ type IsOptionalField<T> = T extends z$1.ZodOptional<any> ? true : T extends z$1.ZodNullable<any> ? true : T extends z$1.ZodDefault<any> ? true : false;
736
+ type OptionalKeys<TZod extends ZodRawShape> = { [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? K : never }[keyof TZod];
737
+ type RequiredKeys<TZod extends ZodRawShape> = { [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? never : K }[keyof TZod];
738
+ type BaseSchema = {
739
+ id: z$1.ZodString;
740
+ commitTs: z$1.ZodCoercedBigInt;
741
+ };
742
+ declare const schemaRegistry: Map<string, SchemaDefinition<string, any, any>>;
743
+ declare const shouldTrackSchema: boolean;
744
+ declare function defineSchema<TSchema extends ZodRawShape, TName extends string, TOptions extends SchemaColumnsOptions<TSchema> = SchemaColumnsOptions<TSchema>>(config: DefineSchemaConfig<TSchema> & {
745
+ name: TName;
746
+ options?: TOptions;
747
+ }): SchemaDefinition<TName, Prettify<TSchema & BaseSchema>, ResolveSchemaType<TSchema, TOptions>>;
748
+ interface StoredSchemaColumnsOptions {
749
+ codecs?: Record<string, ColumnCodec<any, any>>;
750
+ }
751
+ interface SchemaDefinition<TTable extends string, TZod extends ZodRawShape, TData = z$1.infer<z$1.ZodObject<TZod>>> {
752
+ tableId: Uint8Array;
753
+ table: TTable;
754
+ schema: z$1.ZodObject<TZod>;
755
+ columnsOptions: StoredSchemaColumnsOptions;
756
+ columns: Record<string, string>;
757
+ indexes: IndexDefinition[];
758
+ _dataType?: TData;
759
+ }
760
+ type InferSchema<T extends SchemaDefinition<string, ZodRawShape, any>> = T extends SchemaDefinition<string, ZodRawShape, infer TData> ? TData : never;
761
+ type InsertData<T extends SchemaDefinition<string, ZodRawShape, any>> = T extends SchemaDefinition<string, infer TZod, infer TData> ? { [K in RequiredKeys<TZod> as K extends "id" | "commitTs" ? never : K]: Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never } & { [K in OptionalKeys<TZod> as K extends "id" | "commitTs" ? never : K]?: Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never } : never;
762
+ interface Model {
763
+ table: string;
764
+ tableId: Uint8Array;
765
+ columns: Record<string, string>;
766
+ reverseColumns: Record<string, string>;
767
+ types: Record<string, string>;
768
+ codecs: Record<string, ColumnCodec<any, any>>;
769
+ }
770
+ type MaybePromise<T> = T | Promise<T>;
771
+ type ReturnLiveQuery<TLiveQueryFn extends (...args: any[]) => MaybePromise<LiveQueryHandle<any>>> = Awaited<ReturnType<TLiveQueryFn>> extends LiveQueryHandle<infer T> ? T : never;
772
+ type ReturnQuery<TQueryFn extends (...args: any[]) => any> = Awaited<ReturnType<TQueryFn>>;
773
+ type QueryArgs<TQueryFn extends (...args: any[]) => any> = Parameters<TQueryFn>[0];
774
+ type MutationArgs<TMutationFn extends (...args: any[]) => any> = Parameters<TMutationFn>[0];
775
+ type ActionArgs<TActionFn extends (...args: any[]) => any> = Parameters<TActionFn>[0];
776
+ //#endregion
777
+ //#region src/db/query.d.ts
778
+ type FieldValue<S extends SchemaDefinition<string, ZodRawShape>, K> = K extends keyof InferSchema<S> ? InferSchema<S>[K] : never;
779
+ type OrderableValue = number | bigint | string | Date;
780
+ type StringFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = { [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends string ? K : never }[keyof InferSchema<S>];
781
+ type OrderableFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = { [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends OrderableValue ? K : never }[keyof InferSchema<S>];
782
+ type JsonFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = { [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends OrderableValue ? never : NonNullable<InferSchema<S>[K]> extends boolean ? never : NonNullable<InferSchema<S>[K]> extends (object | unknown[]) ? K : unknown extends NonNullable<InferSchema<S>[K]> ? K : never }[keyof InferSchema<S>];
783
+ interface JsonOpOptions {
784
+ /**
785
+ * Skip client-side preparation of the value (no JSON-stringify, no key
786
+ * escaping). The caller is responsible for the exact form the dialect
787
+ * expects: a JSON path string for jsonHasKey, a JSON-encoded string for
788
+ * the contains family.
789
+ */
790
+ raw?: true;
791
+ }
792
+ interface JsonContainsOptions extends JsonOpOptions {
793
+ /**
794
+ * Sub-path into the target JSON to scope the check to. `string` is a
795
+ * single literal top-level key; `string[]` is a nested literal-key path
796
+ * compiled to `$."a"."b"`. Mutually exclusive with `pathRaw`.
797
+ */
798
+ path?: string | string[];
799
+ /**
800
+ * Raw jsonpath expression used verbatim by the dialect (PG `jsonpath`,
801
+ * MySQL JSON path). Mutually exclusive with `path`.
802
+ */
803
+ pathRaw?: string;
804
+ }
805
+ interface JsonHasKeyMultiOptions extends JsonOpOptions {
806
+ /** Required for the multi-path overload — chooses any vs every. */
807
+ mode: "one" | "all";
808
+ }
809
+ declare class QueryBuilder<S extends SchemaDefinition<string, ZodRawShape>> {
810
+ protected ctx: TxContext;
811
+ protected model: Model;
812
+ constructor(ctx: TxContext, model: Model);
813
+ protected getColumnName(key: string): string;
814
+ select(): SelectQueryBuilder<S, keyof InferSchema<S>>;
815
+ select<K extends keyof InferSchema<S>>(...columns: K[]): SelectQueryBuilder<S, K>;
816
+ }
817
+ type IdAndCommitTs = {
818
+ id: string;
819
+ commitTs: bigint;
820
+ };
821
+ type SelectRow<S extends SchemaDefinition<string, ZodRawShape>, K extends keyof InferSchema<S>, C extends Record<string, unknown>> = Prettify<Pick<InferSchema<S>, Extract<K | "id" | "commitTs", keyof InferSchema<S>>> & C>;
822
+ type OrderDirection = "ASC" | "DESC";
823
+ interface OrderByOptions {
824
+ direction?: OrderDirection;
825
+ nulls?: "first" | "last";
826
+ collate?: string;
827
+ }
828
+ /**
829
+ * Cursor-based pagination using a timestamp column and a unique ID column.
830
+ *
831
+ * Generates a stable cursor predicate:
832
+ *
833
+ * DESC (default):
834
+ * ```sql
835
+ * WHERE (timeCol < ? OR (timeCol = ? AND idCol < ?))
836
+ * ORDER BY timeCol DESC, idCol DESC
837
+ * ```
838
+ *
839
+ * ASC:
840
+ * ```sql
841
+ * WHERE (timeCol > ? OR (timeCol = ? AND idCol > ?))
842
+ * ORDER BY timeCol ASC, idCol ASC
843
+ * ```
844
+ */
845
+ interface PaginationClause<S extends SchemaDefinition<string, ZodRawShape>, Time extends OrderableFieldKeys<S>, Id extends OrderableFieldKeys<S>> {
846
+ /** Timestamp column used for cursor pagination. */
847
+ timeCol: Time;
848
+ /**
849
+ * Unique tie-breaker column.
850
+ *
851
+ * @default "id"
852
+ */
853
+ idCol?: Id;
854
+ /**
855
+ * Pagination direction.
856
+ *
857
+ * - `"desc"` (default): Newest → oldest.
858
+ * - `"asc"`: Oldest → newest.
859
+ *
860
+ * @default "desc"
861
+ */
862
+ direction?: OrderDirection;
863
+ /**
864
+ * Maximum number of rows to return.
865
+ */
866
+ limit?: number;
867
+ /**
868
+ * Cursor returned from the previous page.
869
+ *
870
+ * Omit or set to `null` to fetch the first page.
871
+ */
872
+ cursor?: {
873
+ time: FieldValue<S, Time>;
874
+ id: FieldValue<S, Id>;
875
+ } | null;
876
+ }
877
+ declare class SelectQueryBuilder<S extends SchemaDefinition<string, ZodRawShape>, K extends keyof InferSchema<S> = never, C extends Record<string, unknown> = {}> {
878
+ private ctx;
879
+ private model;
880
+ private filters;
881
+ private paginationClause;
882
+ private orderByClause;
883
+ private limitVal;
884
+ private offsetVal;
885
+ private selectedProps;
886
+ private computedFields;
887
+ private commentStr;
888
+ constructor(ctx: TxContext, model: Model, filters?: ((fb: FilterBuilder<S>) => void)[], orderByClause?: string[] | null, limitVal?: number | null, offsetVal?: number | null, selectedProps?: (keyof InferSchema<S>)[], computedFields?: ComputedField[], commentStr?: string);
889
+ private getColumnName;
890
+ private getPropertyName;
891
+ private mapRowToSchema;
892
+ where(filterFn: (fb: FilterBuilder<S>) => void): SelectQueryBuilder<S, K, C>;
893
+ paginate<Time extends OrderableFieldKeys<S>, Id extends OrderableFieldKeys<S>>(clause: PaginationClause<S, Time, Id>): SelectQueryBuilder<S, K, C>;
894
+ orderBy(column: keyof InferSchema<S> | keyof C, direction?: OrderDirection): SelectQueryBuilder<S, K, C>;
895
+ orderBy(column: keyof InferSchema<S> | keyof C, options?: OrderByOptions): SelectQueryBuilder<S, K, C>;
896
+ private buildOrderBySql;
897
+ orderByRaw(sql: string): SelectQueryBuilder<S, K, C>;
898
+ limit(n: number): SelectQueryBuilder<S, K, C>;
899
+ offset(n: number): SelectQueryBuilder<S, K, C>;
900
+ computed<TField extends string, TZodType extends z$1.ZodTypeAny | undefined = undefined, TDecode extends (value: any) => any = (value: unknown) => unknown>(config: ComputedFieldConfig<TField, ReturnType<TDecode>, Parameters<TDecode>[0], TZodType> & {
901
+ codec: {
902
+ decode: TDecode;
903
+ encode?: (value: ReturnType<TDecode>) => Parameters<TDecode>[0];
904
+ };
905
+ }): SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<ComputedCodec<ReturnType<TDecode>, Parameters<TDecode>[0]>, TZodType>>>;
906
+ computed<TField extends string, TZodType extends z$1.ZodTypeAny | undefined = undefined>(config: ComputedFieldConfig<TField, unknown, unknown, TZodType> & {
907
+ codec?: undefined;
908
+ }): SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<undefined, TZodType>>>;
909
+ comment(input: string | Record<string, string>): SelectQueryBuilder<S, K, C>;
910
+ first(): Promise<SelectRow<S, K, C> | null>;
911
+ exists(): Promise<boolean>;
912
+ private static defaultCountType;
913
+ count(): Promise<number>;
914
+ count<T extends z$1.ZodType>(parser: T): Promise<z$1.output<T>>;
915
+ find(id: string): Promise<SelectRow<S, K, C> | null>;
916
+ get(): Promise<SelectRow<S, K, C>[]>;
917
+ private buildPredicate;
918
+ }
919
+ declare class FilterBuilder<S extends SchemaDefinition<string, ZodRawShape>> {
920
+ private columns;
921
+ private codecs;
922
+ predicates: Predicate[];
923
+ constructor(columns: Record<string, string>, codecs: Record<string, ColumnCodec<unknown, unknown>>);
924
+ private add;
925
+ private addJsonContains;
926
+ private getColumnName;
927
+ private encode;
928
+ private encodeJson;
929
+ eq<K extends keyof InferSchema<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
930
+ neq<K extends keyof InferSchema<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
931
+ gt<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
932
+ gte<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
933
+ lt<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
934
+ lte<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
935
+ like<K extends StringFieldKeys<S>>(key: K, pattern: string): FilterBuilder<S>;
936
+ ilike<K extends StringFieldKeys<S>>(key: K, pattern: string): FilterBuilder<S>;
937
+ contains<K extends StringFieldKeys<S>>(key: K, value: string): FilterBuilder<S>;
938
+ icontains<K extends StringFieldKeys<S>>(key: K, value: string): FilterBuilder<S>;
939
+ /**
940
+ * JSON containment. Targets a JSON/JSONB column and asserts the document
941
+ * contains the given candidate (object-key subset for objects,
942
+ * element-subset for arrays — see dialect-specific docs for edge cases).
943
+ * Pass `{ raw: true }` if `value` is already a JSON-encoded string.
944
+ * Pass `{ path: ... }` to scope the check to a sub-document of the
945
+ * target (jsonb_path_query_first on PG, JSON_CONTAINS path arg on MySQL).
946
+ */
947
+ jsonContains<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S>;
948
+ /** Inverse of {@link jsonContains}: column is contained in the given value. */
949
+ jsonContainedBy<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S>;
950
+ /**
951
+ * Key/path existence check on a JSON column.
952
+ *
953
+ * - String form (top-level key): `jsonHasKey("meta", "color")`. On PG
954
+ * also matches when the column is a string array and `value` is one of
955
+ * its elements (PG `?` semantics); MySQL stays strict to object keys.
956
+ * - Array form (nested path): `jsonHasKey("meta", ["a", "b"])` compiles
957
+ * to a path expression `$."a"."b"` on both dialects.
958
+ * - Raw form: `jsonHasKey("meta", "$.foo[*]", { raw: true })` passes the
959
+ * string through as a dialect path expression (PG `jsonb_path_exists`
960
+ * jsonpath, MySQL `JSON_CONTAINS_PATH`). Caller owns the syntax.
961
+ * - Multi-path form: `jsonHasKey("meta", [["a","b"], "color"], { mode: "all" })`
962
+ * compiles each entry to a jsonpath and emits PG OR/AND of
963
+ * `jsonb_path_exists` or MySQL `JSON_CONTAINS_PATH('all', ...)`.
964
+ */
965
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string): FilterBuilder<S>;
966
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string[]): FilterBuilder<S>;
967
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string, opts: {
968
+ raw: true;
969
+ }): FilterBuilder<S>;
970
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, paths: (string | string[])[], opts: JsonHasKeyMultiOptions): FilterBuilder<S>;
971
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, paths: string[], opts: JsonHasKeyMultiOptions & {
972
+ raw: true;
973
+ }): FilterBuilder<S>;
974
+ /**
975
+ * Array element containment: target column is a JSON array; the given
976
+ * `value` (any JSON-encodable type) must appear as one of its elements.
977
+ * Pass `{ raw: true }` if `value` is already a JSON-encoded string.
978
+ * Pass `{ path: ... }` to scope the check to a sub-array of the column.
979
+ */
980
+ jsonArrayContains<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S>;
981
+ between<K extends OrderableFieldKeys<S>>(key: K, lo: FieldValue<S, K>, hi: FieldValue<S, K>): FilterBuilder<S>;
982
+ /**
983
+ * Set membership: `key` equals any of `values` (SQL `IN`). Each value is
984
+ * codec-encoded like `eq`. An empty `values` matches no rows. Bound as one
985
+ * parameter per element, so keep the list within the driver's parameter
986
+ * limit (chunk very large sets at the call site).
987
+ */
988
+ in<K extends keyof InferSchema<S>>(key: K, values: readonly FieldValue<S, K>[]): FilterBuilder<S>;
989
+ isNull<K extends keyof InferSchema<S>>(key: K): FilterBuilder<S>;
990
+ notNull<K extends keyof InferSchema<S>>(key: K): FilterBuilder<S>;
991
+ /**
992
+ * Compose an OR clause. Each callback fills a fresh sub-FilterBuilder
993
+ * with predicates that are AND-ed together within that branch; the
994
+ * branches themselves are OR-ed. Example:
995
+ * f.or([
996
+ * b => b.eq("tag", "a"),
997
+ * b => b.eq("tag", "b").gt("qty", 3), // (tag=b AND qty>3)
998
+ * ])
999
+ * produces (tag=a) OR (tag=b AND qty>3).
1000
+ */
1001
+ or(branches: ((fb: FilterBuilder<S>) => void)[]): FilterBuilder<S>;
1002
+ }
1003
+ declare function buildPredicateSql(predicate: Predicate, params: unknown[], sql: SqlBuilder): string;
1004
+ declare function matchesPredicate(row: Record<string, unknown>, predicate: Predicate): boolean;
1005
+ declare function jsonContains(target: unknown, candidate: unknown): boolean;
1006
+ declare function jsonPathExtract(val: unknown, path: string): unknown;
1007
+ declare function jsonPathExists(val: unknown, path: string): boolean;
1008
+ //#endregion
1009
+ //#region src/db/context.d.ts
1010
+ declare class TxContext {
1011
+ beginTs: bigint;
1012
+ db: Database;
1013
+ protected readSet: ReadEntry[];
1014
+ protected writeSet: WriteEntry[];
1015
+ private models;
1016
+ protected getOrCreateModel(schema: SchemaDefinition<string, ZodRawShape>): Model;
1017
+ constructor(db: Database, beginTs: bigint);
1018
+ /**
1019
+ * Rebind the read connection (and its snapshot ts). Used by the replica
1020
+ * router when a query handler calls `ctx.usePrimaryConn()`/`useReplicaConn()`.
1021
+ * Must be called BEFORE any read — the readSet/beginTs would otherwise mix
1022
+ * snapshots — so this throws if a read or write has already happened.
1023
+ */
1024
+ useConnection(db: Database, beginTs: bigint): void;
1025
+ internalGetReadSet(): ReadEntry[];
1026
+ internalGetWriteSet(): WriteEntry[];
1027
+ /**
1028
+ * Merge a parent procedure's reads into this context's readSet. Used when a
1029
+ * `runMutation` sub-transaction inherits the reads of the procedure that
1030
+ * invoked it, so the sub-tx's OCC validation also fences on those rows.
1031
+ * Entries are shallow-cloned so the two readSets don't alias.
1032
+ */
1033
+ appendInternalReadSet(parentEntries: ReadEntry[]): void;
1034
+ protected findPendingWrite(table: string, id: string): WriteEntry | undefined;
1035
+ protected findPendingInsert(table: string, id: string): WriteEntry | undefined;
1036
+ protected encodeWithCodec(model: Model, property: string, value: unknown): unknown;
1037
+ }
1038
+ declare class DbReader extends TxContext {
1039
+ query<S extends SchemaDefinition<string, ZodRawShape>>(schema: S): QueryBuilder<S>;
1040
+ }
1041
+ declare class DbWriter extends DbReader {
1042
+ insert<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(schema: S, id: ID, data: InsertData<S>): Promise<void>;
1043
+ update<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(schema: S, id: ID, data: Partial<Omit<InferSchema<S>, "id" | "commitTs">>): Promise<void>;
1044
+ delete<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(schema: S, id: ID): Promise<void>;
1045
+ }
1046
+ //#endregion
1047
+ //#region src/db/query_definition.d.ts
1048
+ /**
1049
+ * A named, typed query definition produced by defineQuery().
1050
+ * Carries the query function at runtime and the name/params/result types
1051
+ * at compile time — making it the single source of truth for both the
1052
+ * server-side registry and the client-side RPC.
1053
+ */
1054
+ interface QueryDefinition<TName extends string, TParams, TResult> {
1055
+ readonly _type: "QueryDefinition";
1056
+ readonly name: TName;
1057
+ readonly fn: (ctx: DbReader, params: TParams) => Promise<TResult>;
1058
+ }
1059
+ type AnyQueryDef = QueryDefinition<string, any, any>;
1060
+ /** Extract the params type from a QueryDefinition. */
1061
+ type ParamsOf<D extends AnyQueryDef> = D extends QueryDefinition<any, infer P, any> ? P : never;
1062
+ /** Extract the result type from a QueryDefinition. */
1063
+ type ResultOf<D extends AnyQueryDef> = D extends QueryDefinition<any, any, infer R> ? R : never;
1064
+ /**
1065
+ * Convert a readonly tuple of QueryDefinitions into a Record keyed by their
1066
+ * name literals. This is what makes ClientRpc fully type-safe: each key in
1067
+ * the map carries its own TParams and TResult rather than collapsing to `any`.
1068
+ *
1069
+ * Example:
1070
+ * const defs = [projectBoardQuery, teamMembersQuery] as const;
1071
+ * type Map = DefsToMap<typeof defs>;
1072
+ * // → { projectBoard: typeof projectBoardQuery; teamMembers: typeof teamMembersQuery }
1073
+ */
1074
+ type DefsToMap<T extends readonly AnyQueryDef[]> = { [D in T[number] as D["name"]]: D };
1075
+ /** For test teardown only — clears the global map between suites. */
1076
+ declare function _resetGlobalDefs(): void;
1077
+ /**
1078
+ * Create a named, typed query definition.
1079
+ *
1080
+ * The definition is automatically registered in a module-level global so
1081
+ * the server can call registry.defineAll() instead of listing every query
1082
+ * explicitly. On the client, pass the definition to createClientRpc() to
1083
+ * get a fully typed subscribe() call.
1084
+ *
1085
+ * Usage:
1086
+ * export const projectBoardQuery = defineQuery(
1087
+ * "projectBoard",
1088
+ * async (ctx, params: { projectId: string }) => {
1089
+ * return ctx.query(Tasks)
1090
+ * .select()
1091
+ * .where(f => f.eq("projectId", params.projectId))
1092
+ * .get();
1093
+ * }
1094
+ * );
1095
+ */
1096
+ declare function defineQuery<TName extends string, TParams, TResult>(name: TName, fn: (ctx: DbReader, params: TParams) => Promise<TResult>): QueryDefinition<TName, TParams, TResult>;
1097
+ //#endregion
1098
+ //#region src/db/realtime_db.d.ts
1099
+ declare class SupaliveDb {
1100
+ readonly impl: Database;
1101
+ readonly replica?: SupaliveDb | undefined;
1102
+ /**
1103
+ * @param impl the PRIMARY (writer) connection — all mutations, the OCC
1104
+ * commit-ts source, and cache-freshness commit-log scans run here.
1105
+ * @param replica optional read replica for query/action reads (see the
1106
+ * routing in one-shot-query.ts). Undefined → reads use primary.
1107
+ */
1108
+ constructor(impl: Database, replica?: SupaliveDb | undefined);
1109
+ static create(config: {
1110
+ db: Database;
1111
+ replica?: Database;
1112
+ }): SupaliveDb;
1113
+ /** True when a distinct read replica is configured. */
1114
+ get hasReplica(): boolean;
1115
+ protected onAfterCommit?: (writeSet: WriteEntry[], commitTs: CommitTs) => void;
1116
+ /**
1117
+ * Register a hook fired once after every successful `mutation()` commit
1118
+ * (never on an OCC conflict/rollback), with the committed writeSet and its
1119
+ * commitTs. The server uses this to drive subscription invalidation for ALL
1120
+ * mutation sources — client WS calls, actions, jobs, and the internal caller —
1121
+ * so a server-side write pushes live updates just like a client write does.
1122
+ * Non-server consumers (migration tooling, tests) leave it unset (no-op).
1123
+ */
1124
+ setOnAfterCommit(cb: (writeSet: WriteEntry[], commitTs: CommitTs) => void): void;
1125
+ /**
1126
+ * One-shot read against an EXPLICIT connection + snapshot ts (rather than this
1127
+ * db's own latest). Used by the replica router: the caller pre-resolves the
1128
+ * default read connection (replica for queries) and hands the handler a
1129
+ * `DbReader` it can rebind via `useConnection` (ctx.usePrimaryConn/…). The
1130
+ * returned `ts` is the FINAL bound connection's snapshot, so the cache entry is
1131
+ * stamped with the ts actually read at.
1132
+ */
1133
+ queryInternalOn<T>(read: {
1134
+ impl: Database;
1135
+ beginTs: bigint;
1136
+ }, fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>>;
1137
+ query<T>(fn: (ctx: DbReader) => Promise<T>): Promise<T>;
1138
+ /**
1139
+ * Compute a query once at the latest snapshot, returning the result together
1140
+ * with the snapshot `ts` and the tracked `readSet`. This is a plain one-shot
1141
+ * evaluation — it registers NO live subscription; the `readSet`/`ts` are
1142
+ * returned purely so the caller (e.g. the one-shot query cache) can store
1143
+ * freshness metadata. Use this for cached one-shot query calls (WS `call`,
1144
+ * HTTP RPC). `liveQuery` is the same computation under the subscription path's
1145
+ * name and simply delegates here.
1146
+ */
1147
+ queryInternal<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>>;
1148
+ liveQuery<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>>;
1149
+ mutation<T>(fn: (ctx: DbWriter) => Promise<T>, retryPolicy?: RetryPolicy): Promise<MutationResult<T>>;
1150
+ }
1151
+ declare const sleep: (ms: number) => Promise<void>;
1152
+ //#endregion
1153
+ //#region src/jobs/scheduler.d.ts
1154
+ /** A recurring job to keep synced on the scheduler side. */
1155
+ interface ScheduledJobDef {
1156
+ /** Job procedure name (also the last path segment of its endpoint). */
1157
+ name: string;
1158
+ /** Cron expression, e.g. `"0 3 * * *"`. */
1159
+ cron: string;
1160
+ }
1161
+ /** Options for a precise, one-shot job run. */
1162
+ interface EnqueueOptions {
1163
+ /** Run after this many seconds from now. */
1164
+ delaySeconds?: number;
1165
+ /** Run at this absolute time. Overrides `delaySeconds`. */
1166
+ runAt?: Date;
1167
+ /**
1168
+ * Idempotency key. If two enqueues share the same id within the provider's
1169
+ * dedup window, only the first is delivered. Use it to make "schedule the
1170
+ * expiry of X" safe to call more than once.
1171
+ */
1172
+ dedupeId?: string;
1173
+ }
1174
+ /** Handle returned by {@link JobScheduler.enqueue}; pass its `id` to `cancel`. */
1175
+ interface ScheduleHandle {
1176
+ id: string;
1177
+ }
1178
+ /** The pieces of an inbound webhook the scheduler needs to authenticate it. */
1179
+ interface IncomingJobRequest {
1180
+ /** Job name parsed from the request path. */
1181
+ name: string;
1182
+ /** Raw (unparsed) request body — signatures are computed over these bytes. */
1183
+ rawBody: string;
1184
+ /** Request headers, keys lowercased. */
1185
+ headers: Record<string, string | undefined>;
1186
+ /** Full request URL the webhook was delivered to. */
1187
+ url: string;
1188
+ }
1189
+ /**
1190
+ * Pluggable scheduler. The server owns exactly one instance and uses it for
1191
+ * both directions:
1192
+ * • inbound — `verify` authenticates a webhook before the job runs.
1193
+ * • outbound — `syncSchedules` (recurring, at startup) and `enqueue`/`cancel`
1194
+ * (precise one-shots, at runtime) drive the provider.
1195
+ *
1196
+ * Both dev and production implementations POST to the same HTTP job endpoint,
1197
+ * so the server's dispatch path is exercised identically in every environment.
1198
+ */
1199
+ interface JobScheduler {
1200
+ /** Authenticate an inbound webhook. Return false (or throw) to reject. */
1201
+ verify(req: IncomingJobRequest): Promise<boolean>;
1202
+ /**
1203
+ * Make the provider's recurring schedules match `jobs` exactly (create,
1204
+ * update, and remove stale ones). Called once at server startup.
1205
+ * `endpointFor(name)` yields the absolute URL the provider should POST to.
1206
+ */
1207
+ syncSchedules(jobs: ScheduledJobDef[], endpointFor: (name: string) => string): Promise<void>;
1208
+ /** Enqueue a precise one-shot run of `name` with `body` at `endpoint`. */
1209
+ enqueue(name: string, body: unknown, endpoint: string, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1210
+ /** Cancel a previously enqueued one-shot by its handle id. */
1211
+ cancel(handleId: string): Promise<void>;
1212
+ }
1213
+ interface DevSchedulerOptions {
1214
+ /**
1215
+ * How often, in ms, to fire each recurring job in dev. Dev intentionally
1216
+ * ignores exact cron timing (that is the production scheduler's job); it
1217
+ * just fires often enough to exercise the handler. Default 60_000.
1218
+ */
1219
+ recurringIntervalMs?: number;
1220
+ /**
1221
+ * Override the HTTP client (for tests). Defaults to the global `fetch`.
1222
+ */
1223
+ fetchImpl?: typeof fetch;
1224
+ }
1225
+ /**
1226
+ * In-process scheduler for local development and tests. Recurring jobs fire on
1227
+ * a fixed interval; one-shots fire on an exact `setTimeout` (so precise timing
1228
+ * is faithfully testable). Every fire POSTs to the real HTTP job endpoint, and
1229
+ * `verify` accepts everything — there is no signing in dev.
1230
+ */
1231
+ declare class DevScheduler implements JobScheduler {
1232
+ private readonly intervalMs;
1233
+ private readonly fetchImpl;
1234
+ private intervals;
1235
+ private timeouts;
1236
+ constructor(opts?: DevSchedulerOptions);
1237
+ verify(_req: IncomingJobRequest): Promise<boolean>;
1238
+ syncSchedules(jobs: ScheduledJobDef[], endpointFor: (name: string) => string): Promise<void>;
1239
+ enqueue(name: string, body: unknown, endpoint: string, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1240
+ cancel(handleId: string): Promise<void>;
1241
+ /** Stop every dev timer (call on server shutdown / in test teardown). */
1242
+ stop(): void;
1243
+ private post;
1244
+ }
1245
+ interface QStashSchedulerOptions {
1246
+ /** QStash Base url (`QSTASH_BASE_URL`). */
1247
+ baseUrl: string;
1248
+ /** QStash REST token (`QSTASH_TOKEN`). */
1249
+ token: string;
1250
+ /** Current signing key for webhook verification (`QSTASH_CURRENT_SIGNING_KEY`). */
1251
+ currentSigningKey: string;
1252
+ /** Next signing key, for zero-downtime key rotation (`QSTASH_NEXT_SIGNING_KEY`). */
1253
+ nextSigningKey: string;
1254
+ devMode: boolean;
1255
+ }
1256
+ /**
1257
+ * Production scheduler backed by Upstash QStash. Externalizes the timer so a
1258
+ * horizontally-scaled deployment fires each cron tick exactly once (QStash
1259
+ * calls one HTTP endpoint), with at-least-once retries and signed webhooks.
1260
+ */
1261
+ declare class QStashScheduler implements JobScheduler {
1262
+ private readonly client;
1263
+ private readonly receiver;
1264
+ constructor(opts: QStashSchedulerOptions);
1265
+ verify(req: IncomingJobRequest): Promise<boolean>;
1266
+ syncSchedules(jobs: ScheduledJobDef[], endpointFor: (name: string) => string): Promise<void>;
1267
+ enqueue(name: string, body: unknown, endpoint: string, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1268
+ cancel(handleId: string): Promise<void>;
1269
+ }
1270
+ /**
1271
+ * Thin app-facing handle for scheduling precise one-shots from inside
1272
+ * procedures. The server builds one (via `getJobClient()`) that already knows
1273
+ * how to turn a job name into its endpoint, so callers just say
1274
+ * `jobs.enqueue("expireSpendAuth", { id }, { runAt })`.
1275
+ */
1276
+ declare class JobClient {
1277
+ private readonly scheduler;
1278
+ private readonly endpointFor;
1279
+ constructor(scheduler: JobScheduler, endpointFor: (name: string) => string);
1280
+ enqueue(name: string, body: unknown, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1281
+ cancel(handleId: string): Promise<void>;
1282
+ }
1283
+ //#endregion
1284
+ //#region src/router/procedure.d.ts
1285
+ /**
1286
+ * Minimal request-scoped logger exposed as `ctx.log`. Structurally satisfied by
1287
+ * a pino logger, so the server hands its own child logger straight through; the
1288
+ * interface keeps handler code decoupled from pino. Bound with `reqId`, the
1289
+ * procedure name, and (when tracing is enabled) the `traceId`, so every line a
1290
+ * handler writes correlates to its request and trace.
1291
+ */
1292
+ interface HandlerLogger {
1293
+ debug(...args: any[]): void;
1294
+ info(...args: any[]): void;
1295
+ warn(...args: any[]): void;
1296
+ error(...args: any[]): void;
1297
+ }
1298
+ /**
1299
+ * Observability handles present on a handler context. `log` is ALWAYS present
1300
+ * (the server binds a request-correlated logger; direct internal-caller
1301
+ * invocations get {@link noopLogger}), so handlers never null-check it.
1302
+ */
1303
+ interface HandlerObservability {
1304
+ /** Request-scoped logger, correlated to this operation (reqId + trace id). */
1305
+ log: HandlerLogger;
1306
+ /** The active OpenTelemetry span for this operation. Add attributes/events or
1307
+ * parent child spans off it. A non-recording no-op span when tracing is off. */
1308
+ span?: Span;
1309
+ }
1310
+ /**
1311
+ * Query context passed to query handlers.
1312
+ * Contains database reader and user-defined server context.
1313
+ */
1314
+ /** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */
1315
+ interface ConnOpts {
1316
+ /**
1317
+ * Force the PRIMARY (writer) connection even inside a query/action —
1318
+ * read-your-writes. On `useReplicaConn` this overrides the replica choice.
1319
+ */
1320
+ readOwnWrite?: boolean;
1321
+ }
1322
+ interface QueryCtx<TContext = unknown> extends HandlerObservability {
1323
+ /** Database reader for queries */
1324
+ db: DbReader;
1325
+ /** User-defined server context (auth, requestId, etc.) */
1326
+ serverCtx?: TContext;
1327
+ /**
1328
+ * Route this query's reads to the PRIMARY (writer) connection. Must be called
1329
+ * BEFORE any read (throws otherwise). A no-op when reads already run on primary
1330
+ * (no replica configured, or a primary-only path like a live query).
1331
+ */
1332
+ usePrimaryConn(opts?: ConnOpts): void;
1333
+ /**
1334
+ * Route this query's reads to the read REPLICA, if one is configured. Must be
1335
+ * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.
1336
+ */
1337
+ useReplicaConn(opts?: ConnOpts): void;
1338
+ }
1339
+ /**
1340
+ * Mutation context passed to mutation handlers.
1341
+ * Contains database writer and user-defined server context.
1342
+ */
1343
+ interface MutationCtx<TContext = unknown> extends HandlerObservability {
1344
+ /** Database writer for mutations (includes insert/update/delete) */
1345
+ db: DbWriter;
1346
+ /** User-defined server context (auth, requestId, etc.) */
1347
+ serverCtx?: TContext;
1348
+ /**
1349
+ * No-op on a mutation — writes (and their reads) always run on the primary.
1350
+ * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.
1351
+ * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.
1352
+ */
1353
+ usePrimaryConn(opts?: ConnOpts): void;
1354
+ /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */
1355
+ useReplicaConn(opts?: ConnOpts): void;
1356
+ }
1357
+ /**
1358
+ * Action context passed to action handlers.
1359
+ *
1360
+ * Actions are the "external I/O" tier: they hold the full {@link SupaliveDb}
1361
+ * (queries + mutations) and are the ONLY context that also carries side-effect
1362
+ * services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}
1363
+ * for scheduling precise one-shots. Queries/mutations stay pure (db only) so
1364
+ * they remain cacheable and transaction-scoped.
1365
+ */
1366
+ interface ActionCtx<TContext = unknown> extends HandlerObservability {
1367
+ /** Full database interface for queries and mutations */
1368
+ db: SupaliveDb;
1369
+ /** Object storage, when the server was configured with one (see
1370
+ * `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home
1371
+ * for upload/download presigning. */
1372
+ storage: ObjectStorage;
1373
+ /** Job scheduler client for enqueueing precise one-shots, when the server
1374
+ * was configured with a `scheduler`; `undefined` otherwise. Scheduling is
1375
+ * network I/O, so it belongs in actions, never inside a DB transaction. */
1376
+ scheduler: JobClient;
1377
+ /** User-defined server context (auth, requestId, etc.) */
1378
+ serverCtx?: TContext;
1379
+ }
1380
+ /**
1381
+ * Job context passed to job handlers. Structurally identical to
1382
+ * {@link ActionCtx}: a job is a server-only procedure that runs
1383
+ * non-transactionally against the full {@link SupaliveDb} and may perform
1384
+ * external work, but it is triggered by the scheduler over HTTP (a cron tick
1385
+ * or a precise one-shot) rather than by a connected client. `serverCtx` is
1386
+ * the system context built by the server's `jobContext` factory.
1387
+ */
1388
+ interface JobCtx<TContext = unknown> extends HandlerObservability {
1389
+ /** Full database interface for queries and mutations */
1390
+ db: SupaliveDb;
1391
+ /** System server context built by the server for scheduler-triggered runs */
1392
+ serverCtx?: TContext;
1393
+ }
1394
+ /**
1395
+ * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one
1396
+ * procedure from inside another. Pass the caller handler's own `ctx` — its `db`
1397
+ * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,
1398
+ * inside an action, the full {@link SupaliveDb}. The caller uses this to decide
1399
+ * whether the nested call joins the parent's snapshot (queries) or runs as an
1400
+ * independent sub-transaction (mutations).
1401
+ */
1402
+ interface ParentCtx<TContext = unknown> {
1403
+ db: DbReader | DbWriter | SupaliveDb;
1404
+ serverCtx?: TContext | undefined;
1405
+ /**
1406
+ * The parent handler's request logger, the caller handler's
1407
+ * own `ctx` carries it through, so a nested `runQuery`/`runMutation` logs
1408
+ * under the SAME request logger (reqId/trace correlation preserved).
1409
+ */
1410
+ log: HandlerLogger;
1411
+ }
1412
+ type QueryFn<TInput, TResult, TContext = unknown> = (ctx: QueryCtx<TContext>, input: TInput) => Promise<TResult>;
1413
+ type MutationFn<TInput, TResult, TContext = unknown> = (ctx: MutationCtx<TContext>, input: TInput) => Promise<TResult>;
1414
+ type ActionFn<TInput, TResult, TContext = unknown> = (ctx: ActionCtx<TContext>, input: TInput) => Promise<TResult>;
1415
+ type JobFn<TInput, TResult, TContext = unknown> = (ctx: JobCtx<TContext>, input: TInput) => Promise<TResult>;
1416
+ /**
1417
+ * Per-procedure override for the cache/subscription segmentation key.
1418
+ *
1419
+ * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)
1420
+ * false → no identity in hash; cache/sub shared across all users
1421
+ * string → a static identity literal (e.g. "public" or a tenant id)
1422
+ * function → compute from serverCtx + input (sync)
1423
+ *
1424
+ * When the result of a query is identical regardless of who calls it, set
1425
+ * this to a literal (or `false`) so a single cache entry serves everyone.
1426
+ *
1427
+ * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)
1428
+ * because identity is resolved before any DB read is issued.
1429
+ */
1430
+ type QueryIdentitySpec<TInput, TContext> = false | string | ((serverCtx: TContext, input: TInput) => string | null | undefined);
1431
+ interface BaseProcedure<TInput, TResult, TType extends "query" | "mutation" | "action" | "job", TContext = unknown, TInternal extends boolean = boolean> {
1432
+ readonly _type: "procedure";
1433
+ readonly procedureType: TType;
1434
+ readonly inputSchema: ZodType<TInput>;
1435
+ readonly outputSchema?: ZodType<any>;
1436
+ readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;
1437
+ readonly internal: TInternal;
1438
+ }
1439
+ interface QueryProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "query", TContext, TInternal> {
1440
+ readonly procedureType: "query";
1441
+ readonly fn: QueryFn<TInput, TResult, TContext>;
1442
+ readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;
1443
+ }
1444
+ interface MutationProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "mutation", TContext, TInternal> {
1445
+ readonly procedureType: "mutation";
1446
+ readonly fn: MutationFn<TInput, TResult, TContext>;
1447
+ }
1448
+ interface ActionProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "action", TContext, TInternal> {
1449
+ readonly procedureType: "action";
1450
+ readonly fn: ActionFn<TInput, TResult, TContext>;
1451
+ }
1452
+ /**
1453
+ * A scheduler-triggered, server-only procedure. Runs like an action (full
1454
+ * db, non-transactional, may do external work) but is dispatched by the
1455
+ * server's HTTP job endpoint on a cron tick or a precise one-shot rather
1456
+ * than over the client WebSocket. Always {@link internal}: true, so it is
1457
+ * never reachable via `call`/`subscribe`.
1458
+ */
1459
+ interface JobProcedure<TInput, TResult, TContext = unknown> extends BaseProcedure<TInput, TResult, "job", TContext, true> {
1460
+ readonly procedureType: "job";
1461
+ readonly fn: JobFn<TInput, TResult, TContext>;
1462
+ /**
1463
+ * Cron expression for a recurring job (e.g. `"0 3 * * *"`). Declared crons
1464
+ * are synced to the scheduler at server startup. Omit for a job that is
1465
+ * only ever invoked as a precise one-shot via the scheduler API.
1466
+ */
1467
+ readonly cron?: string;
1468
+ }
1469
+ type AnyProcedure<TContext = unknown> = QueryProcedure<any, any, TContext> | MutationProcedure<any, any, TContext> | ActionProcedure<any, any, TContext> | JobProcedure<any, any, TContext>;
1470
+ interface QueryConfig<TInput, TResult, TContext = unknown> {
1471
+ /** Zod schema for input validation */
1472
+ args: ZodType<TInput>;
1473
+ /** The query handler function */
1474
+ handler: QueryFn<TInput, TResult, TContext>;
1475
+ /** Mark as internal (server-only). Default: false */
1476
+ internal?: boolean;
1477
+ /**
1478
+ * Optional Zod schema describing return-type overrides for codegen.
1479
+ * Only the fields you specify are overridden; everything else is inferred
1480
+ * from the handler's TypeScript return type. Use `.modelName("Name")`
1481
+ * on a Zod object to rename the generated model class.
1482
+ */
1483
+ returns?: ZodType<any>;
1484
+ /**
1485
+ * Override the cache/subscription segmentation key for this procedure.
1486
+ * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.
1487
+ */
1488
+ queryIdentity?: QueryIdentitySpec<TInput, TContext>;
1489
+ }
1490
+ interface MutationConfig<TInput, TResult, TContext = unknown> {
1491
+ /** Zod schema for input validation */
1492
+ args: ZodType<TInput>;
1493
+ /** The mutation handler function */
1494
+ handler: MutationFn<TInput, TResult, TContext>;
1495
+ /** Mark as internal (server-only). Default: false */
1496
+ internal?: boolean;
1497
+ /**
1498
+ * Optional Zod schema describing return-type overrides for codegen.
1499
+ * Only the fields you specify are overridden; everything else is inferred
1500
+ * from the handler's TypeScript return type.
1501
+ */
1502
+ returns?: ZodType<any>;
1503
+ }
1504
+ interface ActionConfig<TInput, TResult, TContext = unknown> {
1505
+ /** Zod schema for input validation */
1506
+ args: ZodType<TInput>;
1507
+ /** The action handler function */
1508
+ handler: ActionFn<TInput, TResult, TContext>;
1509
+ /** Mark as internal (server-only). Default: false */
1510
+ internal?: boolean;
1511
+ /**
1512
+ * Optional Zod schema describing return-type overrides for codegen.
1513
+ * Only the fields you specify are overridden; everything else is inferred
1514
+ * from the handler's TypeScript return type.
1515
+ */
1516
+ returns?: ZodType<any>;
1517
+ }
1518
+ interface JobConfig<TInput, TResult, TContext = unknown> {
1519
+ /** Zod schema for the job payload */
1520
+ args: ZodType<TInput>;
1521
+ /** The job handler function */
1522
+ handler: JobFn<TInput, TResult, TContext>;
1523
+ /**
1524
+ * Cron expression for a recurring schedule (e.g. `"0 3 * * *"`). Omit for a
1525
+ * job that is only invoked as a precise one-shot.
1526
+ */
1527
+ cron?: string;
1528
+ }
1529
+ /** Extract input type from a procedure */
1530
+ type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;
1531
+ /** Extract output type from a procedure */
1532
+ type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;
1533
+ /** Extract procedure type (query/mutation) */
1534
+ type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;
1535
+ /** Extract server context type from a procedure */
1536
+ type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;
1537
+ /**
1538
+ * Create a query builder with a pre-defined context type.
1539
+ * This allows you to define the context type once and have it inferred
1540
+ * automatically in all your query handlers.
1541
+ *
1542
+ * @example
1543
+ * // Define your server context
1544
+ * interface ServerContext {
1545
+ * auth: { userId: string };
1546
+ * requestId: string;
1547
+ * }
1548
+ *
1549
+ * // Create a typed query builder
1550
+ * const query = createQueryBuilder<ServerContext>();
1551
+ *
1552
+ * // Use it - context type is automatically inferred!
1553
+ * const getUser = query({
1554
+ * args: z.object({ id: z.string() }),
1555
+ * handler: async (ctx, { id }) => {
1556
+ * // ctx.db for database queries
1557
+ * const user = await ctx.db.query(UsersSchema).find(id);
1558
+ * // ctx.context for server context
1559
+ * console.log(ctx.context.requestId);
1560
+ * return user;
1561
+ * }
1562
+ * });
1563
+ */
1564
+ declare function createQueryBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: QueryConfig<TInput, TResult, TContext> & {
1565
+ internal?: TInternal;
1566
+ }) => QueryProcedure<TInput, TResult, TContext, TInternal>;
1567
+ /**
1568
+ * Create a mutation builder with a pre-defined context type.
1569
+ * This allows you to define the context type once and have it inferred
1570
+ * automatically in all your mutation handlers.
1571
+ *
1572
+ * @example
1573
+ * // Define your server context
1574
+ * interface ServerContext {
1575
+ * auth: { userId: string };
1576
+ * requestId: string;
1577
+ * }
1578
+ *
1579
+ * // Create a typed mutation builder
1580
+ * const mutation = createMutationBuilder<ServerContext>();
1581
+ *
1582
+ * // Use it - context type is automatically inferred!
1583
+ * const createUser = mutation({
1584
+ * args: z.object({ name: z.string() }),
1585
+ * handler: async (ctx, { name }) => {
1586
+ * // ctx.db for mutations
1587
+ * await ctx.db.insert(UsersSchema, id, { name });
1588
+ * // ctx.context for server context
1589
+ * console.log(ctx.context.requestId);
1590
+ * return { success: true };
1591
+ * }
1592
+ * });
1593
+ */
1594
+ declare function createMutationBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: MutationConfig<TInput, TResult, TContext> & {
1595
+ internal?: TInternal;
1596
+ }) => MutationProcedure<TInput, TResult, TContext, TInternal>;
1597
+ /**
1598
+ * Create an action builder with a pre-defined context type.
1599
+ * Actions have access to the full SupaliveDb for both queries and mutations.
1600
+ *
1601
+ * @example
1602
+ * // Define your server context
1603
+ * interface ServerContext {
1604
+ * auth: { userId: string };
1605
+ * requestId: string;
1606
+ * }
1607
+ *
1608
+ * // Create a typed action builder
1609
+ * const action = createActionBuilder<ServerContext>();
1610
+ *
1611
+ * // Use it - context type is automatically inferred!
1612
+ * const processOrder = action({
1613
+ * args: z.object({ orderId: z.string() }),
1614
+ * handler: async (ctx, { orderId }) => {
1615
+ * // ctx.db for full database access
1616
+ * const order = await ctx.db.query(async (db) => {
1617
+ * return db.query(OrdersSchema).find(orderId);
1618
+ * });
1619
+ * await ctx.db.mutation(async (db) => {
1620
+ * await db.update(OrdersSchema, orderId, { status: "processed" });
1621
+ * });
1622
+ * // ctx.context for server context
1623
+ * console.log(ctx.context.requestId);
1624
+ * return { success: true };
1625
+ * }
1626
+ * });
1627
+ */
1628
+ declare function createActionBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: ActionConfig<TInput, TResult, TContext> & {
1629
+ internal?: TInternal;
1630
+ }) => ActionProcedure<TInput, TResult, TContext, TInternal>;
1631
+ /**
1632
+ * Create a job builder with a pre-defined context type. A job is a
1633
+ * server-only procedure invoked by the scheduler over HTTP — either on its
1634
+ * declared `cron` schedule or as a precise one-shot enqueued via the
1635
+ * server's job API. Jobs run like actions (full db, non-transactional) and
1636
+ * are always internal, so they are never reachable from a client.
1637
+ *
1638
+ * @example
1639
+ * const job = createJobBuilder<ServerContext>();
1640
+ *
1641
+ * export const cleanupOtps = job({
1642
+ * cron: "0 * * * *", // hourly
1643
+ * args: z.object({}),
1644
+ * handler: async (ctx) => {
1645
+ * await ctx.db.mutation(async (db) => { ... });
1646
+ * return { ok: true };
1647
+ * },
1648
+ * });
1649
+ */
1650
+ declare function createJobBuilder<TContext = unknown>(): <TInput, TResult>(config: JobConfig<TInput, TResult, TContext>) => JobProcedure<TInput, TResult, TContext>;
1651
+ //#endregion
1652
+ //#region src/router/router.d.ts
1653
+ /**
1654
+ * A router maps procedure names (keys) to their definitions.
1655
+ * This is the type that's exported from your app and used by the client.
1656
+ */
1657
+ type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {
1658
+ _type: "router";
1659
+ procedures: TProcedures;
1660
+ contextName: string;
1661
+ };
1662
+ /**
1663
+ * Inferred AppRouter type from router() call.
1664
+ * Captures the full procedure map for client type inference.
1665
+ */
1666
+ type AppRouter<TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>, TContext = unknown> = Router<TProcedures, TContext>;
1667
+ /** Get query procedures only from a router */
1668
+ type QueryProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1669
+ procedureType: "query";
1670
+ } ? K : never]: T[K] };
1671
+ /** Get mutation procedures only from a router */
1672
+ type MutationProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1673
+ procedureType: "mutation";
1674
+ } ? K : never]: T[K] };
1675
+ /** Get action procedures only from a router */
1676
+ type ActionProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1677
+ procedureType: "action";
1678
+ } ? K : never]: T[K] };
1679
+ /** Get job procedures only from a router */
1680
+ type JobProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1681
+ procedureType: "job";
1682
+ } ? K : never]: T[K] };
1683
+ /** Get public (non-internal) procedures - for client type safety */
1684
+ type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<T, { [K in keyof T]: T[K] extends {
1685
+ internal: true;
1686
+ } ? never : K }[keyof T]>;
1687
+ /** Extract procedure names from a router */
1688
+ type ProcedureNames<T extends Router<any>> = T extends Router<infer P> ? keyof P : never;
1689
+ type RouterConfig<T> = {
1690
+ procedures: T;
1691
+ contextName?: string;
1692
+ };
1693
+ /**
1694
+ * Create a router from procedure definitions.
1695
+ * Procedure names are inferred from the object keys.
1696
+ *
1697
+ * @example
1698
+ * const appRouter = router({
1699
+ * procedures: {
1700
+ * getUser,
1701
+ * createUser,
1702
+ * internalGetAll,
1703
+ * },
1704
+ * });
1705
+ *
1706
+ * export type AppRouter = typeof appRouter;
1707
+ */
1708
+ declare function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(config: RouterConfig<TProcedures>): Router<TProcedures, TContext>;
1709
+ interface RegisteredProcedure<TContext = unknown> {
1710
+ name: string;
1711
+ type: "query" | "mutation" | "action" | "job";
1712
+ internal: boolean;
1713
+ inputSchema: AnyProcedure<TContext>["inputSchema"];
1714
+ fn: AnyProcedure<TContext>["fn"];
1715
+ /** Only present for `type === "query"`. See `QueryIdentitySpec`. */
1716
+ queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);
1717
+ /** Only present for `type === "job"`. Cron expression for recurring jobs. */
1718
+ cron?: string;
1719
+ }
1720
+ declare function getContextRegistry(inContext: string): ContextRegistry;
1721
+ declare class ContextRegistry {
1722
+ procedureRegistry: Map<string, RegisteredProcedure<any>>;
1723
+ internalProcedureNames: Set<string>;
1724
+ registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void;
1725
+ /** Get a registered procedure by name (runtime lookup) */
1726
+ getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined;
1727
+ /** Get all registered procedure names */
1728
+ getProcedureNames(): string[];
1729
+ /** Get all registered procedures */
1730
+ getAllProcedures(): Map<string, RegisteredProcedure>;
1731
+ /** Get all registered job procedures (server-only, scheduler-triggered). */
1732
+ getJobProcedures(): RegisteredProcedure[];
1733
+ /** Clear the registry (for testing only) */
1734
+ clearRegistry(): void;
1735
+ markInternalProcedure(name: string): void;
1736
+ isInternalProcedure(name: string): boolean;
1737
+ clearInternalProcedures(): void;
1738
+ }
1739
+ //#endregion
1740
+ //#region src/client/ws_client_manager.d.ts
1741
+ declare class RPCError extends Error {
1742
+ code?: string;
1743
+ constructor(message: string, code?: string);
1744
+ }
1745
+ type ClientLogLevel = "debug" | "info" | "warn" | "error" | "silent";
1746
+ /** Minimal logger sink the client writes lifecycle/diagnostic lines to. Pass a
1747
+ * custom implementation via {@link WSClientOptions.logger} to route logs into
1748
+ * your app's logger; otherwise a console sink gated by
1749
+ * {@link WSClientOptions.logLevel} is used. */
1750
+ interface ClientLogger {
1751
+ debug(message: string, ...args: unknown[]): void;
1752
+ info(message: string, ...args: unknown[]): void;
1753
+ warn(message: string, ...args: unknown[]): void;
1754
+ error(message: string, ...args: unknown[]): void;
1755
+ }
1756
+ /** A structured lifecycle event, for feeding client metrics without parsing logs. */
1757
+ interface ClientEvent {
1758
+ type: "connecting" | "connected" | "disconnected" | "reconnecting" | "error";
1759
+ /** Reason/detail (e.g. reconnect trigger, close reason). */
1760
+ detail?: string;
1761
+ /** Reconnect attempt number, when `type === "reconnecting"`. */
1762
+ attempt?: number;
1763
+ }
1764
+ /** Console-backed logger that drops anything below `level`. `"silent"` mutes all. */
1765
+ declare function createConsoleLogger(level?: ClientLogLevel): ClientLogger;
1766
+ interface HeartbeatOptions {
1767
+ /**
1768
+ * Close + reconnect when no server message arrives for this long. The
1769
+ * server emits `{type:"ping"}` every ~15s of channel idle, so anything
1770
+ * larger than ~30s leaves comfortable headroom. Default 60_000.
1771
+ */
1772
+ serverInactivityMs?: number;
1773
+ }
1774
+ interface SendThrottleOptions {
1775
+ /** Yield the event loop every N `call()` invocations. 0 disables. Default 100. */
1776
+ everyN?: number;
1777
+ /** Length of the yield in ms. Default 10. */
1778
+ delayMs?: number;
1779
+ }
1780
+ interface WSClientOptions {
1781
+ /** WebSocket URL (e.g. ws://localhost:3000/ws) */
1782
+ url: string;
1783
+ /** Auth token to send after connection */
1784
+ token?: () => Promise<string | undefined>;
1785
+ /** Optional: reconnection timeout in ms (default: 180000 = 3 minutes) */
1786
+ reconnectionTimeout?: number;
1787
+ /** Reconnection options */
1788
+ reconnect?: {
1789
+ /** Enable automatic reconnection (default: true) */enabled?: boolean; /** Max reconnection attempts (default: 5) */
1790
+ maxAttempts?: number; /** Delay between attempts in ms (default: 1000) */
1791
+ delay?: number; /** Exponential backoff multiplier (default: 1.5) */
1792
+ backoff?: number;
1793
+ };
1794
+ /** Server-inactivity watchdog. See {@link HeartbeatOptions.serverInactivityMs}. */
1795
+ heartbeat?: HeartbeatOptions;
1796
+ /**
1797
+ * Yields the event loop for `delayMs` ms after every `everyN`
1798
+ * `call()` invocations. Useful for keeping React renders / GC tasks
1799
+ * scheduled during long synchronous bursts of mutations/actions; the
1800
+ * heartbeat does not depend on this (the server drives it).
1801
+ * Default `{ everyN: 100, delayMs: 10 }`. Set `everyN: 0` to disable.
1802
+ */
1803
+ throttle?: SendThrottleOptions;
1804
+ /** Called when connection is established */
1805
+ onConnect?: () => void;
1806
+ /** Called when connection is lost */
1807
+ onDisconnect?: () => void;
1808
+ /** Called on connection error */
1809
+ onError?: (error: Error) => void;
1810
+ /**
1811
+ * Custom log sink. When set, it receives all lifecycle/diagnostic lines and
1812
+ * `logLevel` is ignored (filtering is the sink's responsibility). When unset,
1813
+ * a console sink gated by {@link logLevel} is used.
1814
+ */
1815
+ logger?: ClientLogger;
1816
+ /** Level for the default console logger. Default `"warn"` (quiet). */
1817
+ logLevel?: ClientLogLevel;
1818
+ /** Optional structured lifecycle events, for client-side metrics. */
1819
+ onEvent?: (event: ClientEvent) => void;
1820
+ /**
1821
+ * OpenTelemetry-agnostic trace propagation. Return the current W3C
1822
+ * `traceparent` for the active client span (e.g. from `@opentelemetry/api`'s
1823
+ * propagation) and it is sent on every `call`/`subscribe`; the server
1824
+ * continues the trace. Return `undefined` (the default — no hook) to send
1825
+ * nothing. Called per outbound request.
1826
+ */
1827
+ getTraceparent?: () => string | undefined | null;
1828
+ }
1829
+ /**
1830
+ * Public state of the client, surfaced to consumers (React provider, etc.).
1831
+ * - "connecting" — initial connect or reconnect handshake in flight
1832
+ * - "authenticating" — connected, waiting for auth result
1833
+ * - "ready" — connected and auth resolved (authenticated, anonymous, or
1834
+ * explicitly failed — i.e. ready to send calls)
1835
+ * - "disconnected" — currently offline (may auto-retry)
1836
+ */
1837
+ type ClientPublicState = "disconnected" | "connecting" | "authenticating" | "ready";
1838
+ declare class WsClientManager {
1839
+ private ws;
1840
+ private options;
1841
+ private lastSuccessfulConnectionTime;
1842
+ private reconnectionTimeout;
1843
+ private requestId;
1844
+ private pendingRequests;
1845
+ /**
1846
+ * Single source of truth for live subscriptions.
1847
+ *
1848
+ * Keying:
1849
+ * - In-flight subscribe (no subId yet): `_pending:<requestId>`.
1850
+ * - Established: the server-returned canonical `subId`.
1851
+ *
1852
+ * Routing `sub:update` / `sub:gone` is O(1) (`get(subId)`). Subscribe-time
1853
+ * dedup scans `values()` for a matching `localKey` (O(N)), which is cheap
1854
+ * since subscribes happen on component mounts, not in the hot path.
1855
+ */
1856
+ private subscriptions;
1857
+ private queuedCalls;
1858
+ private reconnectAttempts;
1859
+ private reconnectTimer;
1860
+ private connectionState;
1861
+ private authState;
1862
+ /**
1863
+ * Authenticated user id from `auth:success`. Distinct from `queryIdentity`
1864
+ * (server-side cache/sub segmentation key); this is just "who am I logged
1865
+ * in as" for app display purposes. Null while unauthenticated / anonymous.
1866
+ */
1867
+ private authUserId;
1868
+ private explicitlyClosed;
1869
+ private stateListeners;
1870
+ private lastPublicState;
1871
+ private highWaterTs;
1872
+ private serverInactivityMs;
1873
+ private lastServerMessageAt;
1874
+ private inactivityTimer;
1875
+ private pendingConnectResolve;
1876
+ private pendingConnectReject;
1877
+ private throttleEveryN;
1878
+ private throttleDelayMs;
1879
+ private throttleCounter;
1880
+ private throttling;
1881
+ private visibilityListener;
1882
+ private onlineListener;
1883
+ private readonly log;
1884
+ constructor(options: WSClientOptions);
1885
+ /**
1886
+ * Subscribe to client state transitions. Returns an unsubscribe fn.
1887
+ * The listener is called immediately with the current state.
1888
+ */
1889
+ onState(listener: (s: ClientPublicState) => void): () => void;
1890
+ /** Current public state. */
1891
+ getPublicState(): ClientPublicState;
1892
+ /**
1893
+ * Connect to the WebSocket server.
1894
+ * Returns a promise that resolves when connected and authenticated.
1895
+ */
1896
+ connect(): Promise<void>;
1897
+ /**
1898
+ * Disconnect from the server.
1899
+ */
1900
+ disconnect(): void;
1901
+ /**
1902
+ * Check if connected and authenticated.
1903
+ */
1904
+ isReady(): boolean;
1905
+ /**
1906
+ * Check if authenticated.
1907
+ */
1908
+ isAuthenticated(): boolean;
1909
+ /**
1910
+ * Check if anonymouse.
1911
+ */
1912
+ isAnonymouse(): boolean;
1913
+ /**
1914
+ * The authenticated user's id (from `auth:success`), or null when
1915
+ * unauthenticated / anonymous. Useful for "Logged in as …" display.
1916
+ *
1917
+ * Not to be confused with server-side `queryIdentity`, which is the
1918
+ * cache/subscription segmentation key (resolved entirely on the server).
1919
+ */
1920
+ getAuthUserId(): string | null;
1921
+ /**
1922
+ * Call a procedure (query, mutation, or action).
1923
+ *
1924
+ * If the client is not ready (disconnected or still authenticating), the
1925
+ * call is FIFO-queued and dispatched on the next ready state. The promise
1926
+ * still resolves with the eventual server response.
1927
+ *
1928
+ * Pass `onSend` to be notified when the call actually leaves the queue
1929
+ * (used by `useMutation` to flip `state` from "queued" → "loading").
1930
+ */
1931
+ call(procedure: string, input: unknown, options?: {
1932
+ onSend?: () => void;
1933
+ }): Promise<unknown>;
1934
+ /**
1935
+ * Throttle drain loop. Each iteration: sleep `throttleDelayMs`, then
1936
+ * dispatch up to `throttleEveryN` queued items. Exits as soon as the
1937
+ * queue drains inside a single batch (burst over, back to direct
1938
+ * dispatch on the next `call()`) or the connection goes away
1939
+ * (reconnect path will restart us via `flushQueuedCalls`).
1940
+ */
1941
+ private runThrottleLoop;
1942
+ /**
1943
+ * Issue the call against an established connection. Caller must ensure
1944
+ * `isReady()` before invoking.
1945
+ */
1946
+ private dispatchCall;
1947
+ /** Advance the read high-water from a server-returned `ts` (monotonic). */
1948
+ private advanceHighWater;
1949
+ /**
1950
+ * Flush queued calls in FIFO order. Called once `isReady()` becomes
1951
+ * true. With the throttle enabled, dispatch the first batch
1952
+ * synchronously then hand off to the drain loop so a large
1953
+ * post-reconnect flush respects backpressure instead of dumping 10k
1954
+ * frames in one tick.
1955
+ */
1956
+ private flushQueuedCalls;
1957
+ /**
1958
+ * Re-send `subscribe` for every existing subscription. The subId for each
1959
+ * may legitimately change (e.g. `queryIdentity` was a function of user
1960
+ * identity and the user changed during the disconnect), so we re-key the
1961
+ * unified `subscriptions` Map: snapshot every record, drop them from the
1962
+ * Map, then reinsert under a fresh `_pending:<reqId>` key. Each pending
1963
+ * request's `resolve` rekeys the parked record under the new server-issued
1964
+ * subId so subsequent `sub:update` frames route to the existing
1965
+ * `onUpdate` callback (which the React handle is still holding).
1966
+ */
1967
+ private resubscribeAll;
1968
+ /**
1969
+ * Subscribe to a live query.
1970
+ *
1971
+ * The client does not compute the subId locally — it sends the
1972
+ * (procedure, input) pair and receives the canonical subId on the
1973
+ * subscribe response. This lets the server's per-procedure
1974
+ * `queryIdentity` override be authoritative without forcing the client
1975
+ * to mirror any of the resolution logic.
1976
+ *
1977
+ * Returns the server-assigned subId and an unsubscribe function.
1978
+ */
1979
+ subscribe(procedure: string, input: unknown, serializedInput: string, onUpdate: (data: unknown) => void, onGone?: (reason: string | undefined) => void): Promise<{
1980
+ subId: string;
1981
+ unsubscribe: () => void;
1982
+ }>;
1983
+ private findSubByLocalKey;
1984
+ /** Resolve every joiner waiting on this Subscription with the canonical subId. */
1985
+ private resolveJoiners;
1986
+ /** Reject every joiner waiting on this Subscription with the given error. */
1987
+ private rejectJoiners;
1988
+ private unsubscribeByLocalKey;
1989
+ private handleMessage;
1990
+ /**
1991
+ * Called once the client transitions to a "ready" state on a fresh
1992
+ * connection. Replays live-query subscriptions and flushes any queued
1993
+ * calls in FIFO order.
1994
+ */
1995
+ private afterReady;
1996
+ private handleResponse;
1997
+ private handleSubscriptionUpdate;
1998
+ /**
1999
+ * Handles a `sub:gone` message: the server no longer tracks this
2000
+ * subscription (e.g. it was fully unregistered while we were disconnected
2001
+ * from the sub-manager). Notify the handle and drop the local entry so a
2002
+ * re-subscribe is required to receive further updates.
2003
+ */
2004
+ private handleSubscriptionGone;
2005
+ private handleClose;
2006
+ private handleError;
2007
+ private startInactivityWatchdog;
2008
+ private stopInactivityWatchdog;
2009
+ /**
2010
+ * Close the current WebSocket and schedule a reconnect via `handleClose`.
2011
+ *
2012
+ * Atomically swaps the old socket's event handlers to no-ops BEFORE
2013
+ * `close()` so a frame in flight at the moment of close cannot fire
2014
+ * `handleMessage` into a half-cleaned state — that was the source of
2015
+ * the "browser says socket is alive but client says disconnected" race.
2016
+ */
2017
+ private closeAndReconnect;
2018
+ private installEnvironmentListeners;
2019
+ private removeEnvironmentListeners;
2020
+ private scheduleReconnect;
2021
+ private computePublicState;
2022
+ private emitState;
2023
+ /** Fire the optional structured lifecycle event; never lets a throwing hook
2024
+ * break the client. */
2025
+ private emitEvent;
2026
+ private ensureConnected;
2027
+ private send;
2028
+ /** Current W3C traceparent from the optional hook, or undefined. */
2029
+ private traceparent;
2030
+ private cleanup;
2031
+ private generateRequestId;
2032
+ }
2033
+ //#endregion
2034
+ //#region src/db/types_client_rpc.d.ts
2035
+ interface ErrorMessage {
2036
+ type: "error";
2037
+ id?: string;
2038
+ error: string;
2039
+ code?: string;
2040
+ }
2041
+ declare const AuthMessageSchema: z.ZodObject<{
2042
+ type: z.ZodLiteral<"auth">;
2043
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
2044
+ }, z.core.$strip>;
2045
+ declare const CallMessageSchema: z.ZodObject<{
2046
+ type: z.ZodLiteral<"call">;
2047
+ id: z.ZodString;
2048
+ procedure: z.ZodString;
2049
+ input: z.ZodUnknown;
2050
+ minTs: z.ZodOptional<z.ZodString>;
2051
+ trace: z.ZodOptional<z.ZodString>;
2052
+ }, z.core.$strip>;
2053
+ declare const SubscribeMessageSchema: z.ZodObject<{
2054
+ type: z.ZodLiteral<"subscribe">;
2055
+ id: z.ZodString;
2056
+ procedure: z.ZodString;
2057
+ input: z.ZodUnknown;
2058
+ trace: z.ZodOptional<z.ZodString>;
2059
+ }, z.core.$strip>;
2060
+ declare const UnsubscribeMessageSchema: z.ZodObject<{
2061
+ type: z.ZodLiteral<"unsubscribe">;
2062
+ subId: z.ZodString;
2063
+ }, z.core.$strip>;
2064
+ declare const ClientMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
2065
+ type: z.ZodLiteral<"auth">;
2066
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
2067
+ }, z.core.$strip>, z.ZodObject<{
2068
+ type: z.ZodLiteral<"call">;
2069
+ id: z.ZodString;
2070
+ procedure: z.ZodString;
2071
+ input: z.ZodUnknown;
2072
+ minTs: z.ZodOptional<z.ZodString>;
2073
+ trace: z.ZodOptional<z.ZodString>;
2074
+ }, z.core.$strip>, z.ZodObject<{
2075
+ type: z.ZodLiteral<"subscribe">;
2076
+ id: z.ZodString;
2077
+ procedure: z.ZodString;
2078
+ input: z.ZodUnknown;
2079
+ trace: z.ZodOptional<z.ZodString>;
2080
+ }, z.core.$strip>, z.ZodObject<{
2081
+ type: z.ZodLiteral<"unsubscribe">;
2082
+ subId: z.ZodString;
2083
+ }, z.core.$strip>]>;
2084
+ type AuthMessage = z.infer<typeof AuthMessageSchema>;
2085
+ type CallMessage = z.infer<typeof CallMessageSchema>;
2086
+ type SubscribeMessage = z.infer<typeof SubscribeMessageSchema>;
2087
+ type UnsubscribeMessage = z.infer<typeof UnsubscribeMessageSchema>;
2088
+ type ClientMessage = z.infer<typeof ClientMessageSchema>;
2089
+ declare const ConnectedMessageSchema: z.ZodObject<{
2090
+ type: z.ZodLiteral<"connected">;
2091
+ sessionId: z.ZodString;
2092
+ }, z.core.$strip>;
2093
+ declare const AuthSuccessMessageSchema: z.ZodObject<{
2094
+ type: z.ZodLiteral<"auth:success">;
2095
+ userId: z.ZodString;
2096
+ extra: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
2097
+ }, z.core.$strip>;
2098
+ declare const AuthFailedMessageSchema: z.ZodObject<{
2099
+ type: z.ZodLiteral<"auth:failed">;
2100
+ message: z.ZodString;
2101
+ extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2102
+ }, z.core.$strip>;
2103
+ declare const ResponseMessageSchema: z.ZodObject<{
2104
+ type: z.ZodLiteral<"response">;
2105
+ id: z.ZodString;
2106
+ success: z.ZodBoolean;
2107
+ data: z.ZodOptional<z.ZodUnknown>;
2108
+ error: z.ZodOptional<z.ZodString>;
2109
+ code: z.ZodOptional<z.ZodString>;
2110
+ subId: z.ZodOptional<z.ZodString>;
2111
+ ts: z.ZodOptional<z.ZodString>;
2112
+ }, z.core.$strip>;
2113
+ declare const SubscriptionUpdateMessageSchema: z.ZodObject<{
2114
+ type: z.ZodLiteral<"sub:update">;
2115
+ subId: z.ZodString;
2116
+ data: z.ZodUnknown;
2117
+ dataHash: z.ZodOptional<z.ZodString>;
2118
+ ts: z.ZodOptional<z.ZodString>;
2119
+ }, z.core.$strip>;
2120
+ /**
2121
+ * Notifies a client that a subscription is no longer tracked on the server
2122
+ * and will not receive further updates. Sent when, during a sub-manager
2123
+ * recovery cycle, the registration record could not be found (e.g. another
2124
+ * app-server instance fully unregistered the sub while we were disconnected).
2125
+ * The client may choose to re-subscribe or surface the state to the user.
2126
+ */
2127
+ declare const SubscriptionGoneMessageSchema: z.ZodObject<{
2128
+ type: z.ZodLiteral<"sub:gone">;
2129
+ subId: z.ZodString;
2130
+ reason: z.ZodOptional<z.ZodString>;
2131
+ }, z.core.$strip>;
2132
+ /**
2133
+ * Server-driven liveness signal. Sent when the channel has been idle for
2134
+ * the configured app-ping interval (default 15s) and again after every
2135
+ * outbound message. Pure no-op for the client: receiving any message
2136
+ * (including this one) resets the client's inactivity watchdog. The client
2137
+ * does NOT reply.
2138
+ */
2139
+ declare const ServerPingMessageSchema: z.ZodObject<{
2140
+ type: z.ZodLiteral<"ping">;
2141
+ }, z.core.$strip>;
2142
+ declare const ServerMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
2143
+ type: z.ZodLiteral<"connected">;
2144
+ sessionId: z.ZodString;
2145
+ }, z.core.$strip>, z.ZodObject<{
2146
+ type: z.ZodLiteral<"auth:success">;
2147
+ userId: z.ZodString;
2148
+ extra: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
2149
+ }, z.core.$strip>, z.ZodObject<{
2150
+ type: z.ZodLiteral<"auth:failed">;
2151
+ message: z.ZodString;
2152
+ extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2153
+ }, z.core.$strip>, z.ZodObject<{
2154
+ type: z.ZodLiteral<"response">;
2155
+ id: z.ZodString;
2156
+ success: z.ZodBoolean;
2157
+ data: z.ZodOptional<z.ZodUnknown>;
2158
+ error: z.ZodOptional<z.ZodString>;
2159
+ code: z.ZodOptional<z.ZodString>;
2160
+ subId: z.ZodOptional<z.ZodString>;
2161
+ ts: z.ZodOptional<z.ZodString>;
2162
+ }, z.core.$strip>, z.ZodObject<{
2163
+ type: z.ZodLiteral<"sub:update">;
2164
+ subId: z.ZodString;
2165
+ data: z.ZodUnknown;
2166
+ dataHash: z.ZodOptional<z.ZodString>;
2167
+ ts: z.ZodOptional<z.ZodString>;
2168
+ }, z.core.$strip>, z.ZodObject<{
2169
+ type: z.ZodLiteral<"sub:gone">;
2170
+ subId: z.ZodString;
2171
+ reason: z.ZodOptional<z.ZodString>;
2172
+ }, z.core.$strip>, z.ZodObject<{
2173
+ type: z.ZodLiteral<"ping">;
2174
+ }, z.core.$strip>]>;
2175
+ type ConnectedMessage = z.infer<typeof ConnectedMessageSchema>;
2176
+ type AuthSuccessMessage = z.infer<typeof AuthSuccessMessageSchema>;
2177
+ type AuthFailedMessage = z.infer<typeof AuthFailedMessageSchema>;
2178
+ type ResponseMessage = z.infer<typeof ResponseMessageSchema>;
2179
+ type SubscriptionUpdateMessage = z.infer<typeof SubscriptionUpdateMessageSchema>;
2180
+ type SubscriptionGoneMessage = z.infer<typeof SubscriptionGoneMessageSchema>;
2181
+ type ServerPingMessage = z.infer<typeof ServerPingMessageSchema>;
2182
+ type ServerMessage = z.infer<typeof ServerMessageSchema>;
2183
+ declare class AuthenticationError extends Error {
2184
+ extra: Record<string, unknown>;
2185
+ constructor(message: string, extra?: Record<string, unknown>);
2186
+ }
2187
+ /**
2188
+ * Helper type to check if a procedure is internal.
2189
+ */
2190
+ type IsInternal<T> = T extends {
2191
+ internal: infer I;
2192
+ } ? (I extends true ? true : false) : false;
2193
+ interface Context$1 {
2194
+ requestId: string;
2195
+ /** Authenticated user info */
2196
+ user: {
2197
+ userId: string;
2198
+ };
2199
+ }
2200
+ //#endregion
2201
+ //#region src/client/client.d.ts
2202
+ interface ClientOptions {
2203
+ /** WebSocket URL (e.g. ws://localhost:3000/ws) */
2204
+ url: string;
2205
+ /** Auth Info callback */
2206
+ token?: () => Promise<string>;
2207
+ /** Optional: reconnection timeout in ms (default: 180000 = 3 minutes) */
2208
+ reconnectionTimeout?: number;
2209
+ /** Reconnection options */
2210
+ reconnect?: WSClientOptions["reconnect"];
2211
+ /**
2212
+ * Inactivity watchdog. The client never sends a ping itself; the server
2213
+ * emits `{type:"ping"}` while idle and we close+reconnect if no inbound
2214
+ * message arrives within `serverInactivityMs` (default 60s).
2215
+ */
2216
+ heartbeat?: WSClientOptions["heartbeat"];
2217
+ /**
2218
+ * Yields the event loop for `delayMs` after every `everyN` `call()`
2219
+ * invocations. Useful for keeping React renders / GC tasks scheduled
2220
+ * during long synchronous bursts; not load-bearing for the heartbeat.
2221
+ * Default `{ everyN: 100, delayMs: 10 }`. Set `everyN: 0` to disable.
2222
+ */
2223
+ throttle?: WSClientOptions["throttle"];
2224
+ /** Custom log sink; when set, `logLevel` is ignored. See {@link WSClientOptions.logger}. */
2225
+ logger?: WSClientOptions["logger"];
2226
+ /** Level for the default console logger. Default `"warn"` (quiet). */
2227
+ logLevel?: WSClientOptions["logLevel"];
2228
+ /** Optional structured lifecycle events, for client-side metrics. */
2229
+ onEvent?: WSClientOptions["onEvent"];
2230
+ /** OpenTelemetry-agnostic W3C `traceparent` provider; see {@link WSClientOptions.getTraceparent}. */
2231
+ getTraceparent?: WSClientOptions["getTraceparent"];
2232
+ onConnect?: () => void;
2233
+ onDisConnect?: () => void;
2234
+ }
2235
+ /**
2236
+ * Public state of a live query subscription, exposed via `getState()` and
2237
+ * `onState()` on the handle so React (or any UI) can render a consistent
2238
+ * snapshot via `useSyncExternalStore`.
2239
+ *
2240
+ * - "connecting" — initial subscribe in flight
2241
+ * - "success" — subscribed, last server data is in `data`
2242
+ * - "stale" — was successful, transport dropped; keeping last `data`
2243
+ * until the resubscribe completes
2244
+ * - "loading" — `refetch()` triggered an explicit re-subscribe
2245
+ * - "error" — subscribe failed or server sent `sub:gone`
2246
+ */
2247
+ type LiveQueryStatus = "connecting" | "success" | "stale" | "loading" | "error";
2248
+ interface LiveQueryState<T> {
2249
+ data: T | undefined;
2250
+ status: LiveQueryStatus;
2251
+ error: Error | null;
2252
+ }
2253
+ interface LiveQueryHandle<T> {
2254
+ /** Get current cached data (legacy convenience getter). */
2255
+ get(): T | undefined;
2256
+ /** Snapshot of `{ data, status, error }`. Stable between updates. */
2257
+ getState(): LiveQueryState<T>;
2258
+ /**
2259
+ * Listen for state changes (data, status or error). Returns an
2260
+ * unsubscribe function that removes only this listener — the underlying
2261
+ * server subscription stays alive as long as any listener is attached.
2262
+ *
2263
+ * Suitable for `useSyncExternalStore`.
2264
+ */
2265
+ onState(listener: () => void): () => void;
2266
+ /** Listen for data-only changes. Returns listener-removal fn. */
2267
+ onData(callback: (data: T) => void): () => void;
2268
+ /** Force a re-subscribe round-trip. */
2269
+ refetch(): void;
2270
+ /** Unsubscribe from the server (drops listeners too). */
2271
+ unsubscribe(): void;
2272
+ }
2273
+ /**
2274
+ * Create a fully typed RPC client with WebSocket transport.
2275
+ */
2276
+ declare function createClient<AppRouter extends Router<Record<string, AnyProcedure<TContext>>, TContext>, TContext = unknown, TProcedures extends Record<string, AnyProcedure<TContext>> = AppRouter["procedures"]>(options: ClientOptions): ClientFromProcedures<TProcedures, TContext> & WSClientMethods;
2277
+ /**
2278
+ * WebSocket client methods.
2279
+ */
2280
+ interface WSClientMethods {
2281
+ /** Connect to the WebSocket server */
2282
+ connect(): Promise<void>;
2283
+ /** Disconnect from the server */
2284
+ disconnect(): void;
2285
+ /** Check if connected and authenticated */
2286
+ isReady(): boolean;
2287
+ /** Check if authenticated */
2288
+ isAuthenticated(): boolean;
2289
+ /** Check if anonymouse */
2290
+ isAnonymouse(): boolean;
2291
+ /**
2292
+ * The authenticated user id reported by the server on `auth:success`, or
2293
+ * null when anonymous/unauthenticated. This is the auth-tier identity,
2294
+ * NOT the server-side `queryIdentity` (which is the cache/subscription
2295
+ * segmentation key and is not exposed to the client).
2296
+ */
2297
+ getAuthUserId(): string | null;
2298
+ /** Subscribe to client connection state transitions. Returns unsubscribe fn. */
2299
+ onState(listener: (s: ClientPublicState) => void): () => void;
2300
+ /** Snapshot of the current public state. */
2301
+ getPublicState(): ClientPublicState;
2302
+ }
2303
+ /**
2304
+ * Client type from procedures.
2305
+ * Filters internal procedures and creates appropriate methods.
2306
+ * Query procedures get an additional liveQuery() method for real-time subscriptions.
2307
+ */
2308
+ type ClientFromProcedures<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = { [K in keyof TProcedures as IsInternal<TProcedures[K]> extends true ? never : K]: TProcedures[K] extends {
2309
+ procedureType: "query";
2310
+ } ? {
2311
+ query: (input: InputOf<TProcedures[K]>) => Promise<OutputOf<TProcedures[K]>>;
2312
+ liveQuery: (input: InputOf<TProcedures[K]>) => LiveQueryHandle<OutputOf<TProcedures[K]>>;
2313
+ } : TProcedures[K] extends {
2314
+ procedureType: "mutation";
2315
+ } ? {
2316
+ mutate: (input: InputOf<TProcedures[K]>, opts?: CallOptions) => Promise<OutputOf<TProcedures[K]>>;
2317
+ } : TProcedures[K] extends {
2318
+ procedureType: "action";
2319
+ } ? {
2320
+ action: (input: InputOf<TProcedures[K]>, opts?: CallOptions) => Promise<OutputOf<TProcedures[K]>>;
2321
+ } : never };
2322
+ /**
2323
+ * Optional call options forwarded to the transport layer.
2324
+ */
2325
+ interface CallOptions {
2326
+ /**
2327
+ * Fired the first time the request leaves the queue and is actually
2328
+ * sent on the wire. If the call was already sent immediately (client
2329
+ * was ready at call time), this is invoked synchronously.
2330
+ *
2331
+ * Used by `useMutation` to flip `state` from "queued" → "loading".
2332
+ */
2333
+ onSend?: () => void;
2334
+ }
2335
+ //#endregion
2336
+ //#region src/client/caller_client.d.ts
2337
+ interface CallerOptions<TContext = unknown> {
2338
+ isInternal?: boolean;
2339
+ inContext: string;
2340
+ }
2341
+ /**
2342
+ * Create a server-side caller that bypasses HTTP/WebSocket.
2343
+ *
2344
+ * For in-memory calls, input validation is skipped (data is already a JS object).
2345
+ * Query procedures also get a liveQuery() method for server-side use.
2346
+ */
2347
+ declare function createCaller<AppRouter extends Router<Record<string, AnyProcedure<TContext>>, TContext>, TContext = unknown, TProcedures extends Record<string, AnyProcedure<TContext>> = AppRouter["procedures"]>(options: CallerOptions<any>): CallerFromProcedures<TProcedures, TContext>;
2348
+ /**
2349
+ * Caller type from procedures (includes internal procedures).
2350
+ * Query procedures also have liveQuery() for server-side use.
2351
+ */
2352
+ type CallerFromProcedures<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = { [K in keyof TProcedures]: TProcedures[K] extends {
2353
+ procedureType: "query";
2354
+ } ? {
2355
+ query: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2356
+ liveQuery: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<LiveResult<OutputOf<TProcedures[K]>>>;
2357
+ runQuery: (input: InputOf<TProcedures[K]>, ctx: ParentCtx<TContext>) => Promise<OutputOf<TProcedures[K]>>;
2358
+ } : TProcedures[K] extends {
2359
+ procedureType: "mutation";
2360
+ } ? {
2361
+ mutate: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2362
+ runMutation: (input: InputOf<TProcedures[K]>, ctx: ParentCtx<TContext>) => Promise<OutputOf<TProcedures[K]>>;
2363
+ } : TProcedures[K] extends {
2364
+ procedureType: "action";
2365
+ } ? {
2366
+ action: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2367
+ } : TProcedures[K] extends {
2368
+ procedureType: "job";
2369
+ } ? {
2370
+ run: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2371
+ } : never } & {
2372
+ init: (config: {
2373
+ db: SupaliveDb;
2374
+ storage: ObjectStorage;
2375
+ scheduler: JobClient;
2376
+ }) => Promise<void>;
2377
+ };
2378
+ /**
2379
+ * Caller type from router.
2380
+ */
2381
+ type CallerFromRouter<TRouter extends Router<any, any>> = CallerFromProcedures<TRouter["procedures"]>;
2382
+ //#endregion
2383
+ export { AppRouter as $, SqlBuilder as $n, ReadEntry as $r, _resetGlobalDefs as $t, ResponseMessageSchema as A, OverrideField as An, MutationResult as Ar, QueryProcedure as At, SubscriptionUpdateMessageSchema as B, defineComputedField as Bn, QueryCacheEntry as Br, JobClient as Bt, ClientMessageSchema as C, DeclarativeIndex as Cn, CommitTs as Cr, MutationCtx as Ct, ErrorMessage as D, InsertData as Dn, LeafPredicate as Dr, QueryConfig as Dt, Context$1 as E, InferSchema as En, DEFAULT_RETRY as Er, OutputOf as Et, SubscribeMessage as F, SchemaCodecs as Fn, OrPredicateSchema as Fr, createQueryBuilder as Ft, ClientLogger as G, CoreInitLockCtx as Gn, RangeRead as Gr, ScheduledJobDef as Gt, UnsubscribeMessageSchema as H, schemaRegistry as Hn, QueryCacheMetadata as Hr, QStashScheduler as Ht, SubscribeMessageSchema as I, SchemaColumnMapping as In, PointRead as Ir, DevScheduler as It, RPCError as J, DbType as Jn, RawPointReadSchema as Jr, AnyQueryDef as Jt, ClientPublicState as K, Database as Kn, RangeReadSchema as Kr, SupaliveDb as Kt, SubscriptionGoneMessage as L, SchemaColumnsOptions as Ln, PointReadSchema as Lr, DevSchedulerOptions as Lt, ServerMessageSchema as M, QueryArgs as Mn, OccAbortError as Mr, createActionBuilder as Mt, ServerPingMessage as N, ReturnLiveQuery as Nn, OccConflictError as Nr, createJobBuilder as Nt, IsInternal as O, Model as On, LeafPredicateSchema as Or, QueryCtx as Ot, ServerPingMessageSchema as P, ReturnQuery as Pn, OrPredicate as Pr, createMutationBuilder as Pt, ActionProcedures as Q, RawClient as Qn, RawReadEntrySchema as Qr, ResultOf as Qt, SubscriptionGoneMessageSchema as R, SchemaDefinition as Rn, Predicate as Rr, EnqueueOptions as Rt, ClientMessage as S, ComputedFieldConfig as Sn, CommitLogEntry as Sr, MutationConfig as St, ConnectedMessageSchema as T, IndexDefinition as Tn, CompareOperatorSchema as Tr, MutationProcedure as Tt, ClientEvent as U, shouldTrackSchema as Un, QueryCacheMetadataSchema as Ur, QStashSchedulerOptions as Ut, UnsubscribeMessage as V, defineSchema as Vn, QueryCacheEntrySchema as Vr, JobScheduler as Vt, ClientLogLevel as W, tableNameToId as Wn, QuerySpec as Wr, ScheduleHandle as Wt, WsClientManager as X, PooledClient as Xn, RawRangeReadSchema as Xr, ParamsOf as Xt, WSClientOptions as Y, LazyCommitTsParam as Yn, RawRangeRead as Yr, DefsToMap as Yt, createConsoleLogger as Z, PreparedQueries as Zn, RawReadEntry as Zr, QueryDefinition as Zt, AuthSuccessMessage as _, ActionArgs as _n, AndPredicate as _r, HandlerObservability as _t, CallOptions as a, WriteOpSchema as ai, JsonContainsOptions as an, InvalidateWritesetResult as ar, QueryProcedures as at, CallMessage as b, ComputedDataType as bn, CachedPgMetadata as br, JobFn as bt, LiveQueryHandle as c, normalizeToBytes as ci, OrderByOptions as cn, RegisterSubscriptionResult as cr, getContextRegistry as ct, WSClientMethods as d, QueryBuilder as dn, UnregisterSubscriptionResult as dr, ActionCtx as dt, ReadEntrySchema as ei, defineQuery as en, TxDatabase as er, ContextRegistry as et, createClient as f, buildPredicateSql as fn, UnregisterSubscriptionsParams as fr, ActionFn as ft, AuthMessageSchema as g, matchesPredicate as gn, UpdateSubscriptionReadSetResult as gr, HandlerLogger as gt, AuthMessage as h, jsonPathExtract as hn, UpdateSubscriptionReadSetParamsSchema as hr, ContextOf as ht, createCaller as i, WriteOp as ii, IdAndCommitTs as in, InvalidateWritesetParamsSchema as ir, PublicProcedures as it, ServerMessage as j, Prettify as jn, NO_RETRY as jr, TypeOf as jt, ResponseMessage as k, MutationArgs as kn, LiveResult as kr, QueryFn as kt, LiveQueryState as l, OrderDirection as ln, UnregisterSubscriptionParams as lr, router as lt, AuthFailedMessageSchema as m, jsonPathExists as mn, UpdateSubscriptionReadSetParams as mr, AnyProcedure as mt, CallerFromRouter as n, WriteEntry as ni, DbWriter as nn, AffectedSubscription as nr, MutationProcedures as nt, ClientFromProcedures as o, bytesFromJson as oi, JsonHasKeyMultiOptions as on, RegisterSubscriptionParams as or, RegisteredProcedure as ot, AuthFailedMessage as p, jsonContains as pn, UnregisterSubscriptionsResult as pr, ActionProcedure as pt, HeartbeatOptions as q, DbQueryResult as qn, RawPointRead as qr, sleep as qt, CallerOptions as r, WriteEntrySchema as ri, TxContext as rn, InvalidateWritesetParams as rr, ProcedureNames as rt, ClientOptions as s, normalizeIdToBytes as si, JsonOpOptions as sn, RegisterSubscriptionParamsSchema as sr, Router as st, CallerFromProcedures as t, RetryConfig as ti, DbReader as tn, CacheLayer as tr, JobProcedures as tt, LiveQueryStatus as u, PaginationClause as un, UnregisterSubscriptionParamsSchema as ur, ActionConfig as ut, AuthSuccessMessageSchema as v, ColumnCodec as vn, AndPredicateSchema as vr, JobConfig as vt, ConnectedMessage as w, DefineSchemaConfig as wn, CompareOperator as wr, MutationFn as wt, CallMessageSchema as x, ComputedField as xn, CachedPgMetadataSchema as xr, JobProcedure as xt, AuthenticationError as y, ComputedCodec as yn, BigIntSchema as yr, JobCtx as yt, SubscriptionUpdateMessage as z, StoredSchemaColumnsOptions as zn, PredicateSchema as zr, IncomingJobRequest as zt };
2384
+ //# sourceMappingURL=index-B2nE1y9E.d.ts.map