@supalive/core 1.17.0 → 1.19.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.
- package/dist/index-B3i2G1gr.d.ts +2402 -0
- package/dist/index-B3i2G1gr.d.ts.map +1 -0
- package/dist/index-BHs0EtJk.d.ts +2402 -0
- package/dist/index-BHs0EtJk.d.ts.map +1 -0
- package/dist/index-BMz7jVbX.d.ts +2402 -0
- package/dist/index-BMz7jVbX.d.ts.map +1 -0
- package/dist/index-BuWa503L.d.ts +2445 -0
- package/dist/index-BuWa503L.d.ts.map +1 -0
- package/dist/index-CBIjmPUS.d.ts +2444 -0
- package/dist/index-CBIjmPUS.d.ts.map +1 -0
- package/dist/index-CKo6HvJc.d.ts +2455 -0
- package/dist/index-CKo6HvJc.d.ts.map +1 -0
- package/dist/index-CjkNEwSc.d.ts +2402 -0
- package/dist/index-CjkNEwSc.d.ts.map +1 -0
- package/dist/index-Cng74DL5.d.ts +2404 -0
- package/dist/index-Cng74DL5.d.ts.map +1 -0
- package/dist/index-DShKjpzF.d.ts +2453 -0
- package/dist/index-DShKjpzF.d.ts.map +1 -0
- package/dist/index-Dcxf_Gm-.d.ts +2454 -0
- package/dist/index-Dcxf_Gm-.d.ts.map +1 -0
- package/dist/index-yXV5AMh9.d.ts +2416 -0
- package/dist/index-yXV5AMh9.d.ts.map +1 -0
- package/dist/logger-DrXccWFZ.js +346 -0
- package/dist/logger-DrXccWFZ.js.map +1 -0
- package/dist/mysql-1ENHI0yX.d.ts +114 -0
- package/dist/mysql-1ENHI0yX.d.ts.map +1 -0
- package/dist/mysql-B2u0Ye4x.d.ts +114 -0
- package/dist/mysql-B2u0Ye4x.d.ts.map +1 -0
- package/dist/mysql-BHW-tAqt.d.ts +114 -0
- package/dist/mysql-BHW-tAqt.d.ts.map +1 -0
- package/dist/mysql-C6jg1Vpr.d.ts +114 -0
- package/dist/mysql-C6jg1Vpr.d.ts.map +1 -0
- package/dist/mysql-C_TTCZ8j.d.ts +114 -0
- package/dist/mysql-C_TTCZ8j.d.ts.map +1 -0
- package/dist/mysql-CyzJqrvO.d.ts +114 -0
- package/dist/mysql-CyzJqrvO.d.ts.map +1 -0
- package/dist/mysql-DKR33wfH.d.ts +114 -0
- package/dist/mysql-DKR33wfH.d.ts.map +1 -0
- package/dist/mysql-DcHgRk9f.d.ts +114 -0
- package/dist/mysql-DcHgRk9f.d.ts.map +1 -0
- package/dist/mysql-DnrIJoWL.d.ts +114 -0
- package/dist/mysql-DnrIJoWL.d.ts.map +1 -0
- package/dist/mysql-GsWYd6fG.d.ts +114 -0
- package/dist/mysql-GsWYd6fG.d.ts.map +1 -0
- package/dist/mysql-ygH2EMGn.js +622 -0
- package/dist/mysql-ygH2EMGn.js.map +1 -0
- package/dist/mysql-z9Jefhd6.d.ts +114 -0
- package/dist/mysql-z9Jefhd6.d.ts.map +1 -0
- package/dist/one-shot-query-9mCboWaB.js +565 -0
- package/dist/one-shot-query-9mCboWaB.js.map +1 -0
- package/dist/one-shot-query-B9SjfcCD.js +550 -0
- package/dist/one-shot-query-B9SjfcCD.js.map +1 -0
- package/dist/one-shot-query-BBiv9LGP.js +565 -0
- package/dist/one-shot-query-BBiv9LGP.js.map +1 -0
- package/dist/one-shot-query-Bxz_N-NE.js +563 -0
- package/dist/one-shot-query-Bxz_N-NE.js.map +1 -0
- package/dist/one-shot-query-DE9oQU40.js +550 -0
- package/dist/one-shot-query-DE9oQU40.js.map +1 -0
- package/dist/one-shot-query-adoWqGLs.js +565 -0
- package/dist/one-shot-query-adoWqGLs.js.map +1 -0
- package/dist/overlap-checker-CCgq_Tpa.js +284 -0
- package/dist/overlap-checker-CCgq_Tpa.js.map +1 -0
- package/dist/postgres-B2FLN1Kw.d.ts +118 -0
- package/dist/postgres-B2FLN1Kw.d.ts.map +1 -0
- package/dist/postgres-C7xHWbij.d.ts +118 -0
- package/dist/postgres-C7xHWbij.d.ts.map +1 -0
- package/dist/postgres-CFarR3cB.d.ts +118 -0
- package/dist/postgres-CFarR3cB.d.ts.map +1 -0
- package/dist/postgres-CWVM-KKP.d.ts +118 -0
- package/dist/postgres-CWVM-KKP.d.ts.map +1 -0
- package/dist/postgres-D50xpaQ-.d.ts +118 -0
- package/dist/postgres-D50xpaQ-.d.ts.map +1 -0
- package/dist/postgres-DBMAv_dq.d.ts +118 -0
- package/dist/postgres-DBMAv_dq.d.ts.map +1 -0
- package/dist/postgres-DBuP9ON_.d.ts +118 -0
- package/dist/postgres-DBuP9ON_.d.ts.map +1 -0
- package/dist/postgres-DwiUT_A6.js +867 -0
- package/dist/postgres-DwiUT_A6.js.map +1 -0
- package/dist/postgres-I4sgdBnG.d.ts +118 -0
- package/dist/postgres-I4sgdBnG.d.ts.map +1 -0
- package/dist/postgres-tVdgYJkj.d.ts +118 -0
- package/dist/postgres-tVdgYJkj.d.ts.map +1 -0
- package/dist/postgres-yAn2CF7j.d.ts +118 -0
- package/dist/postgres-yAn2CF7j.d.ts.map +1 -0
- package/dist/postgres-yTjQ-Nxk.d.ts +118 -0
- package/dist/postgres-yTjQ-Nxk.d.ts.map +1 -0
- package/dist/router-DP2ThAwh.js.map +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/index.js +46 -51
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/exports/mysql.d.ts +1 -1
- package/dist/src/exports/mysql.js +1 -1
- package/dist/src/exports/postgres.d.ts +1 -1
- package/dist/src/exports/postgres.js +1 -1
- package/dist/src/exports/procedure.d.ts +1 -1
- package/dist/src/exports/schema-sql.d.ts +1 -1
- package/dist/src/exports/server.d.ts +17 -7
- package/dist/src/exports/server.d.ts.map +1 -1
- package/dist/src/exports/server.js +42 -414
- package/dist/src/exports/server.js.map +1 -1
- package/dist/src/exports/sub-manager-worker-entry.js +1 -1
- package/dist/src/exports/types.d.ts +3 -3
- package/dist/src/exports/types.js +1 -1
- package/dist/sub-worker-dispatch-BLujn13f.js +792 -0
- package/dist/sub-worker-dispatch-BLujn13f.js.map +1 -0
- package/dist/sub-worker-dispatch-Cvqarej5.js +826 -0
- package/dist/sub-worker-dispatch-Cvqarej5.js.map +1 -0
- package/dist/sub-worker-dispatch-D-3VPkd4.js +826 -0
- package/dist/sub-worker-dispatch-D-3VPkd4.js.map +1 -0
- package/dist/sub-worker-dispatch-qiSs5Xkm.js.map +1 -1
- package/dist/types_client_rpc-B8jh6MKl.js +154 -0
- package/dist/types_client_rpc-B8jh6MKl.js.map +1 -0
- package/dist/types_client_rpc-BRCAgeyJ.js +155 -0
- package/dist/types_client_rpc-BRCAgeyJ.js.map +1 -0
- package/dist/types_server-B5KQ6PAO.d.ts +692 -0
- package/dist/types_server-B5KQ6PAO.d.ts.map +1 -0
- package/dist/types_server-BCst4TfZ.d.ts +703 -0
- package/dist/types_server-BCst4TfZ.d.ts.map +1 -0
- package/dist/types_server-BJBeSk6n.d.ts +691 -0
- package/dist/types_server-BJBeSk6n.d.ts.map +1 -0
- package/dist/types_server-BXeiSmd8.d.ts +691 -0
- package/dist/types_server-BXeiSmd8.d.ts.map +1 -0
- package/dist/types_server-BYwLkwbC.d.ts +691 -0
- package/dist/types_server-BYwLkwbC.d.ts.map +1 -0
- package/dist/types_server-BnRmctWG.d.ts +699 -0
- package/dist/types_server-BnRmctWG.d.ts.map +1 -0
- package/dist/types_server-Bvrohyc8.d.ts +691 -0
- package/dist/types_server-Bvrohyc8.d.ts.map +1 -0
- package/dist/types_server-C20ibVGu.d.ts +692 -0
- package/dist/types_server-C20ibVGu.d.ts.map +1 -0
- package/dist/types_server-C6oCm9oC.d.ts +691 -0
- package/dist/types_server-C6oCm9oC.d.ts.map +1 -0
- package/dist/types_server-CHJLfdxb.d.ts +691 -0
- package/dist/types_server-CHJLfdxb.d.ts.map +1 -0
- package/dist/types_server-CjjJIQps.d.ts +691 -0
- package/dist/types_server-CjjJIQps.d.ts.map +1 -0
- package/dist/types_server-CjzRPllt.d.ts +691 -0
- package/dist/types_server-CjzRPllt.d.ts.map +1 -0
- package/dist/types_server-Cy4bvdeN.d.ts +691 -0
- package/dist/types_server-Cy4bvdeN.d.ts.map +1 -0
- package/dist/types_server-DnO_fp-F.d.ts +691 -0
- package/dist/types_server-DnO_fp-F.d.ts.map +1 -0
- package/package.json +3 -2
|
@@ -0,0 +1,2402 @@
|
|
|
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 from "ioredis";
|
|
6
|
+
|
|
7
|
+
//#region src/db/types_db.d.ts
|
|
8
|
+
/** Monotonically increasing integer from global_commit_ts sequence in Postgres */
|
|
9
|
+
type CommitTs = bigint;
|
|
10
|
+
declare const BigIntSchema: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
|
|
11
|
+
declare const CompareOperatorSchema: z.ZodEnum<{
|
|
12
|
+
"=": "=";
|
|
13
|
+
"!=": "!=";
|
|
14
|
+
">": ">";
|
|
15
|
+
">=": ">=";
|
|
16
|
+
"<": "<";
|
|
17
|
+
"<=": "<=";
|
|
18
|
+
like: "like";
|
|
19
|
+
ilike: "ilike";
|
|
20
|
+
contains: "contains";
|
|
21
|
+
icontains: "icontains";
|
|
22
|
+
between: "between";
|
|
23
|
+
in: "in";
|
|
24
|
+
jsonContains: "jsonContains";
|
|
25
|
+
jsonContainedBy: "jsonContainedBy";
|
|
26
|
+
jsonHasKey: "jsonHasKey";
|
|
27
|
+
jsonArrayContains: "jsonArrayContains";
|
|
28
|
+
isNull: "isNull";
|
|
29
|
+
isNotNull: "isNotNull";
|
|
30
|
+
}>;
|
|
31
|
+
type CompareOperator = z.infer<typeof CompareOperatorSchema>;
|
|
32
|
+
type Predicate = LeafPredicate | {
|
|
33
|
+
kind: "and";
|
|
34
|
+
children: Predicate[];
|
|
35
|
+
} | {
|
|
36
|
+
kind: "or";
|
|
37
|
+
children: Predicate[];
|
|
38
|
+
};
|
|
39
|
+
declare const PredicateSchema: z.ZodType<Predicate>;
|
|
40
|
+
declare const LeafPredicateSchema: z.ZodObject<{
|
|
41
|
+
kind: z.ZodLiteral<"leaf">;
|
|
42
|
+
column: z.ZodString;
|
|
43
|
+
operator: z.ZodEnum<{
|
|
44
|
+
"=": "=";
|
|
45
|
+
"!=": "!=";
|
|
46
|
+
">": ">";
|
|
47
|
+
">=": ">=";
|
|
48
|
+
"<": "<";
|
|
49
|
+
"<=": "<=";
|
|
50
|
+
like: "like";
|
|
51
|
+
ilike: "ilike";
|
|
52
|
+
contains: "contains";
|
|
53
|
+
icontains: "icontains";
|
|
54
|
+
between: "between";
|
|
55
|
+
in: "in";
|
|
56
|
+
jsonContains: "jsonContains";
|
|
57
|
+
jsonContainedBy: "jsonContainedBy";
|
|
58
|
+
jsonHasKey: "jsonHasKey";
|
|
59
|
+
jsonArrayContains: "jsonArrayContains";
|
|
60
|
+
isNull: "isNull";
|
|
61
|
+
isNotNull: "isNotNull";
|
|
62
|
+
}>;
|
|
63
|
+
value: z.ZodUnknown;
|
|
64
|
+
value2: z.ZodOptional<z.ZodUnknown>;
|
|
65
|
+
raw: z.ZodOptional<z.ZodBoolean>;
|
|
66
|
+
path: z.ZodOptional<z.ZodString>;
|
|
67
|
+
mode: z.ZodOptional<z.ZodEnum<{
|
|
68
|
+
one: "one";
|
|
69
|
+
all: "all";
|
|
70
|
+
}>>;
|
|
71
|
+
}, z.core.$strip>;
|
|
72
|
+
type LeafPredicate = z.infer<typeof LeafPredicateSchema>;
|
|
73
|
+
declare const AndPredicateSchema: z.ZodObject<{
|
|
74
|
+
kind: z.ZodLiteral<"and">;
|
|
75
|
+
children: z.ZodArray<z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>>;
|
|
76
|
+
}, z.core.$strip>;
|
|
77
|
+
type AndPredicate = z.infer<typeof AndPredicateSchema>;
|
|
78
|
+
declare const OrPredicateSchema: z.ZodObject<{
|
|
79
|
+
kind: z.ZodLiteral<"or">;
|
|
80
|
+
children: z.ZodArray<z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>>;
|
|
81
|
+
}, z.core.$strip>;
|
|
82
|
+
type OrPredicate = z.infer<typeof OrPredicateSchema>;
|
|
83
|
+
/** Query specification - what was queried (used for cache key generation) */
|
|
84
|
+
type QuerySpec = ReadEntry;
|
|
85
|
+
declare function normalizeIdToBytes(id: string | number, fromHex?: boolean): Uint8Array;
|
|
86
|
+
declare function normalizeToBytes(value: Uint8Array | unknown): Uint8Array;
|
|
87
|
+
declare function bytesFromJson(value: Uint8Array | unknown): Uint8Array;
|
|
88
|
+
declare const PointReadSchema: z.ZodObject<{
|
|
89
|
+
kind: z.ZodLiteral<"point">;
|
|
90
|
+
table: z.ZodString;
|
|
91
|
+
id: z.ZodString;
|
|
92
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
93
|
+
}, z.core.$strip>;
|
|
94
|
+
type PointRead = z.infer<typeof PointReadSchema>;
|
|
95
|
+
declare const RawPointReadSchema: z.ZodObject<{
|
|
96
|
+
kind: z.ZodLiteral<"point">;
|
|
97
|
+
tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
98
|
+
id: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
99
|
+
table: z.ZodString;
|
|
100
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
101
|
+
}, z.core.$strip>;
|
|
102
|
+
type RawPointRead = z.infer<typeof RawPointReadSchema>;
|
|
103
|
+
/**
|
|
104
|
+
* Query specification for a range read (get with filters).
|
|
105
|
+
* This is the query definition, not the result.
|
|
106
|
+
*/
|
|
107
|
+
declare const RangeReadSchema: z.ZodObject<{
|
|
108
|
+
kind: z.ZodLiteral<"range">;
|
|
109
|
+
table: z.ZodString;
|
|
110
|
+
predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
|
|
111
|
+
columns: z.ZodArray<z.ZodString>;
|
|
112
|
+
orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
113
|
+
limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
114
|
+
offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
115
|
+
}, z.core.$strip>;
|
|
116
|
+
type RangeRead = z.infer<typeof RangeReadSchema>;
|
|
117
|
+
declare const RawRangeReadSchema: z.ZodObject<{
|
|
118
|
+
kind: z.ZodLiteral<"range">;
|
|
119
|
+
table: z.ZodString;
|
|
120
|
+
tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
121
|
+
predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
|
|
122
|
+
columns: z.ZodArray<z.ZodString>;
|
|
123
|
+
orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
124
|
+
limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
125
|
+
offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
126
|
+
}, z.core.$strip>;
|
|
127
|
+
type RawRangeRead = z.infer<typeof RawRangeReadSchema>;
|
|
128
|
+
declare const ReadEntrySchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
129
|
+
kind: z.ZodLiteral<"point">;
|
|
130
|
+
table: z.ZodString;
|
|
131
|
+
id: z.ZodString;
|
|
132
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
133
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
134
|
+
kind: z.ZodLiteral<"range">;
|
|
135
|
+
table: z.ZodString;
|
|
136
|
+
predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
|
|
137
|
+
columns: z.ZodArray<z.ZodString>;
|
|
138
|
+
orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
139
|
+
limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
140
|
+
offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
141
|
+
}, z.core.$strip>]>;
|
|
142
|
+
type ReadEntry = z.infer<typeof ReadEntrySchema>;
|
|
143
|
+
declare const RawReadEntrySchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
144
|
+
kind: z.ZodLiteral<"point">;
|
|
145
|
+
tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
146
|
+
id: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
147
|
+
table: z.ZodString;
|
|
148
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
149
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
150
|
+
kind: z.ZodLiteral<"range">;
|
|
151
|
+
table: z.ZodString;
|
|
152
|
+
tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
153
|
+
predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
|
|
154
|
+
columns: z.ZodArray<z.ZodString>;
|
|
155
|
+
orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
156
|
+
limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
157
|
+
offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
158
|
+
}, z.core.$strip>]>;
|
|
159
|
+
type RawReadEntry = z.infer<typeof RawReadEntrySchema>;
|
|
160
|
+
declare const WriteOpSchema: z.ZodEnum<{
|
|
161
|
+
insert: "insert";
|
|
162
|
+
update: "update";
|
|
163
|
+
delete: "delete";
|
|
164
|
+
}>;
|
|
165
|
+
type WriteOp = z.infer<typeof WriteOpSchema>;
|
|
166
|
+
declare const WriteEntrySchema: z.ZodObject<{
|
|
167
|
+
table: z.ZodString;
|
|
168
|
+
tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
169
|
+
id: z.ZodString;
|
|
170
|
+
op: z.ZodEnum<{
|
|
171
|
+
insert: "insert";
|
|
172
|
+
update: "update";
|
|
173
|
+
delete: "delete";
|
|
174
|
+
}>;
|
|
175
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
176
|
+
prevData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
177
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
178
|
+
}, z.core.$strip>;
|
|
179
|
+
type WriteEntry = z.infer<typeof WriteEntrySchema>;
|
|
180
|
+
interface CommitLogEntry {
|
|
181
|
+
id: Uint8Array;
|
|
182
|
+
ts: bigint;
|
|
183
|
+
tableId: Uint8Array;
|
|
184
|
+
data: Uint8Array;
|
|
185
|
+
_parsedData?: Record<string, unknown> | null;
|
|
186
|
+
}
|
|
187
|
+
interface MutationResult<T> {
|
|
188
|
+
result: T;
|
|
189
|
+
writeSet: WriteEntry[];
|
|
190
|
+
commitTs: CommitTs;
|
|
191
|
+
}
|
|
192
|
+
interface LiveResult<T> {
|
|
193
|
+
ts: bigint;
|
|
194
|
+
data: T;
|
|
195
|
+
readSet: ReadEntry[];
|
|
196
|
+
}
|
|
197
|
+
declare const QueryCacheMetadataSchema: z.ZodObject<{
|
|
198
|
+
lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
|
|
199
|
+
version: z.ZodString;
|
|
200
|
+
readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
201
|
+
kind: z.ZodLiteral<"point">;
|
|
202
|
+
table: z.ZodString;
|
|
203
|
+
id: z.ZodString;
|
|
204
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
205
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
206
|
+
kind: z.ZodLiteral<"range">;
|
|
207
|
+
table: z.ZodString;
|
|
208
|
+
predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
|
|
209
|
+
columns: z.ZodArray<z.ZodString>;
|
|
210
|
+
orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
211
|
+
limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
212
|
+
offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
213
|
+
}, z.core.$strip>]>>;
|
|
214
|
+
}, z.core.$strip>;
|
|
215
|
+
type QueryCacheMetadata = z.infer<typeof QueryCacheMetadataSchema>;
|
|
216
|
+
declare const QueryCacheEntrySchema: z.ZodObject<{
|
|
217
|
+
lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
|
|
218
|
+
data: z.ZodUnknown;
|
|
219
|
+
version: z.ZodString;
|
|
220
|
+
}, z.core.$strip>;
|
|
221
|
+
type QueryCacheEntry = z.infer<typeof QueryCacheEntrySchema>;
|
|
222
|
+
declare const CachedPgMetadataSchema: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
223
|
+
type CachedPgMetadata = z.infer<typeof CachedPgMetadataSchema>;
|
|
224
|
+
interface RetryConfig {
|
|
225
|
+
maxAttempts: number;
|
|
226
|
+
backoff: "none" | "linear" | "exponential";
|
|
227
|
+
delayMs?: number;
|
|
228
|
+
onConflict?: (attempt: number, error: OccConflictError) => void;
|
|
229
|
+
}
|
|
230
|
+
declare const NO_RETRY: RetryConfig;
|
|
231
|
+
declare const DEFAULT_RETRY: RetryConfig;
|
|
232
|
+
declare class OccConflictError extends Error {
|
|
233
|
+
readonly reason: string;
|
|
234
|
+
readonly conflictDetail?: unknown | undefined;
|
|
235
|
+
constructor(reason: string, conflictDetail?: unknown | undefined);
|
|
236
|
+
static isOccConflictError(err: unknown): boolean;
|
|
237
|
+
}
|
|
238
|
+
declare class OccAbortError extends Error {
|
|
239
|
+
constructor(message: string);
|
|
240
|
+
}
|
|
241
|
+
//#endregion
|
|
242
|
+
//#region src/server/sub-manager-types.d.ts
|
|
243
|
+
declare const RegisterSubscriptionParamsSchema: z.ZodObject<{
|
|
244
|
+
subId: z.ZodString;
|
|
245
|
+
cacheKey: z.ZodString;
|
|
246
|
+
queryName: z.ZodString;
|
|
247
|
+
args: z.ZodUnknown;
|
|
248
|
+
queryIdentity: z.ZodString;
|
|
249
|
+
instanceName: z.ZodString;
|
|
250
|
+
lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
|
|
251
|
+
}, z.core.$strip>;
|
|
252
|
+
type RegisterSubscriptionParams = z.infer<typeof RegisterSubscriptionParamsSchema>;
|
|
253
|
+
declare const RegisterSubscriptionResultSchema: z.ZodObject<{
|
|
254
|
+
cacheKey: z.ZodString;
|
|
255
|
+
recompute: z.ZodBoolean;
|
|
256
|
+
readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
257
|
+
kind: z.ZodLiteral<"point">;
|
|
258
|
+
table: z.ZodString;
|
|
259
|
+
id: z.ZodString;
|
|
260
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
261
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
262
|
+
kind: z.ZodLiteral<"range">;
|
|
263
|
+
table: z.ZodString;
|
|
264
|
+
predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
|
|
265
|
+
columns: z.ZodArray<z.ZodString>;
|
|
266
|
+
orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
267
|
+
limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
268
|
+
offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
269
|
+
}, z.core.$strip>]>>;
|
|
270
|
+
version: z.ZodOptional<z.ZodString>;
|
|
271
|
+
}, z.core.$strip>;
|
|
272
|
+
type RegisterSubscriptionResult = z.infer<typeof RegisterSubscriptionResultSchema>;
|
|
273
|
+
declare const UpdateSubscriptionReadSetParamsSchema: z.ZodObject<{
|
|
274
|
+
cacheKey: z.ZodString;
|
|
275
|
+
subId: z.ZodString;
|
|
276
|
+
instanceName: z.ZodString;
|
|
277
|
+
lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
|
|
278
|
+
readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
279
|
+
kind: z.ZodLiteral<"point">;
|
|
280
|
+
table: z.ZodString;
|
|
281
|
+
id: z.ZodString;
|
|
282
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
283
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
284
|
+
kind: z.ZodLiteral<"range">;
|
|
285
|
+
table: z.ZodString;
|
|
286
|
+
predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
|
|
287
|
+
columns: z.ZodArray<z.ZodString>;
|
|
288
|
+
orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
289
|
+
limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
290
|
+
offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
291
|
+
}, z.core.$strip>]>>;
|
|
292
|
+
}, z.core.$strip>;
|
|
293
|
+
type UpdateSubscriptionReadSetParams = z.infer<typeof UpdateSubscriptionReadSetParamsSchema>;
|
|
294
|
+
/**
|
|
295
|
+
* `tracked: false` means the sub-manager has no record of this subId (e.g.
|
|
296
|
+
* a restart wiped state and the caller hasn't re-registered yet). The app
|
|
297
|
+
* server should treat this as a signal to register the sub before retrying.
|
|
298
|
+
*/
|
|
299
|
+
declare const UpdateSubscriptionReadSetResultSchema: z.ZodObject<{
|
|
300
|
+
tracked: z.ZodBoolean;
|
|
301
|
+
}, z.core.$strip>;
|
|
302
|
+
type UpdateSubscriptionReadSetResult = z.infer<typeof UpdateSubscriptionReadSetResultSchema>;
|
|
303
|
+
declare const UnregisterSubscriptionParamsSchema: z.ZodObject<{
|
|
304
|
+
subId: z.ZodString;
|
|
305
|
+
instanceName: z.ZodString;
|
|
306
|
+
}, z.core.$strip>;
|
|
307
|
+
type UnregisterSubscriptionParams = z.infer<typeof UnregisterSubscriptionParamsSchema>;
|
|
308
|
+
declare const UnregisterSubscriptionsParamsSchema: z.ZodArray<z.ZodObject<{
|
|
309
|
+
subId: z.ZodString;
|
|
310
|
+
instanceName: z.ZodString;
|
|
311
|
+
}, z.core.$strip>>;
|
|
312
|
+
type UnregisterSubscriptionsParams = z.infer<typeof UnregisterSubscriptionsParamsSchema>;
|
|
313
|
+
declare const UnregisterSubscriptionResultSchema: z.ZodObject<{
|
|
314
|
+
ok: z.ZodBoolean;
|
|
315
|
+
}, z.core.$strip>;
|
|
316
|
+
type UnregisterSubscriptionResult = z.infer<typeof UnregisterSubscriptionResultSchema>;
|
|
317
|
+
declare const UnregisterSubscriptionsResultSchema: z.ZodArray<z.ZodObject<{
|
|
318
|
+
ok: z.ZodBoolean;
|
|
319
|
+
}, z.core.$strip>>;
|
|
320
|
+
type UnregisterSubscriptionsResult = z.infer<typeof UnregisterSubscriptionsResultSchema>;
|
|
321
|
+
declare const InvalidateWritesetParamsSchema: z.ZodObject<{
|
|
322
|
+
writeSet: z.ZodArray<z.ZodObject<{
|
|
323
|
+
table: z.ZodString;
|
|
324
|
+
tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
|
|
325
|
+
id: z.ZodString;
|
|
326
|
+
op: z.ZodEnum<{
|
|
327
|
+
insert: "insert";
|
|
328
|
+
update: "update";
|
|
329
|
+
delete: "delete";
|
|
330
|
+
}>;
|
|
331
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
332
|
+
prevData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
333
|
+
expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
|
|
334
|
+
}, z.core.$strip>>;
|
|
335
|
+
}, z.core.$strip>;
|
|
336
|
+
type InvalidateWritesetParams = z.infer<typeof InvalidateWritesetParamsSchema>;
|
|
337
|
+
declare const AffectedSubscriptionSchema: z.ZodObject<{
|
|
338
|
+
subId: z.ZodString;
|
|
339
|
+
queryName: z.ZodString;
|
|
340
|
+
args: z.ZodUnknown;
|
|
341
|
+
cacheKey: z.ZodString;
|
|
342
|
+
notifyInstances: z.ZodArray<z.ZodString>;
|
|
343
|
+
}, z.core.$strip>;
|
|
344
|
+
type AffectedSubscription = z.infer<typeof AffectedSubscriptionSchema>;
|
|
345
|
+
declare const InvalidateWritesetResultSchema: z.ZodObject<{
|
|
346
|
+
affected: z.ZodArray<z.ZodObject<{
|
|
347
|
+
subId: z.ZodString;
|
|
348
|
+
queryName: z.ZodString;
|
|
349
|
+
args: z.ZodUnknown;
|
|
350
|
+
cacheKey: z.ZodString;
|
|
351
|
+
notifyInstances: z.ZodArray<z.ZodString>;
|
|
352
|
+
}, z.core.$strip>>;
|
|
353
|
+
}, z.core.$strip>;
|
|
354
|
+
type InvalidateWritesetResult = z.infer<typeof InvalidateWritesetResultSchema>;
|
|
355
|
+
declare const RegistrationRecordSchema: z.ZodObject<{
|
|
356
|
+
queryName: z.ZodString;
|
|
357
|
+
args: z.ZodUnknown;
|
|
358
|
+
queryIdentity: z.ZodString;
|
|
359
|
+
cacheKey: z.ZodString;
|
|
360
|
+
}, z.core.$strip>;
|
|
361
|
+
type RegistrationRecord = z.infer<typeof RegistrationRecordSchema>;
|
|
362
|
+
//#endregion
|
|
363
|
+
//#region src/db/cache.d.ts
|
|
364
|
+
declare class CacheLayer {
|
|
365
|
+
redis: Redis;
|
|
366
|
+
private readonly ttlSeconds;
|
|
367
|
+
/** Cached EVALSHA digests keyed by Lua source (see evalScript). */
|
|
368
|
+
private readonly scriptShaCache;
|
|
369
|
+
constructor(redis: Redis, ttlSeconds?: number);
|
|
370
|
+
/**
|
|
371
|
+
* Run a Lua script via EVALSHA using the script's SHA1 (computed locally — the
|
|
372
|
+
* same digest Redis keys scripts by, so no SCRIPT LOAD round-trip is needed on
|
|
373
|
+
* the hot path). On NOSCRIPT (the script isn't in Redis's cache yet, e.g. first
|
|
374
|
+
* use or after a Redis restart/failover) load it explicitly via SCRIPT LOAD and
|
|
375
|
+
* re-run via EVALSHA — so the script ends up cached server-side and subsequent
|
|
376
|
+
* EVALSHA calls hit. The runtime client is always ioredis (see initCacheLayer).
|
|
377
|
+
*/
|
|
378
|
+
private evalScript;
|
|
379
|
+
/** One-shot recompute: atomically write data + metadata (CAS on version). */
|
|
380
|
+
setQueryCacheAndMetadataFor(cacheKey: string, data: unknown, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
|
|
381
|
+
/** Subscribe path: write the data blob only (CAS against the metadata's
|
|
382
|
+
* version). The metadata is written separately by the sub-worker; the
|
|
383
|
+
* `version` links the two so a divergent pair is detected on read. Takes the
|
|
384
|
+
* snapshot ts directly (rather than a pre-stringified version) so the entry
|
|
385
|
+
* can carry `lastSnapshotTs` as its own field; `version` is derived from it,
|
|
386
|
+
* preserving the `version === String(ts)` convention the CAS relies on. */
|
|
387
|
+
setQueryCacheFor(cacheKey: string, data: unknown, lastSnapshotTs: bigint, ttlSeconds?: number): Promise<void>;
|
|
388
|
+
getQueryCacheFor(cacheKey: string): Promise<QueryCacheEntry | null>;
|
|
389
|
+
/** Subscription recompute: replace the whole metadata (CAS on version). */
|
|
390
|
+
replaceQueryCacheMetadata(cacheKey: string, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
|
|
391
|
+
/** Still-fresh subscription: advance `lastSnapshotTs` only, preserving the
|
|
392
|
+
* data's `version` + `readSet` (no recompute). Monotonic and non-clobbering
|
|
393
|
+
* — see ADVANCE_META. `metaData` carries the new horizon plus the version +
|
|
394
|
+
* readSet the caller read, which the script keeps unless a newer computation
|
|
395
|
+
* has since landed. */
|
|
396
|
+
advanceQueryCacheMetadata(cacheKey: string, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
|
|
397
|
+
getQueryCacheMetaData(cacheKey: string): Promise<QueryCacheMetadata | null>;
|
|
398
|
+
persistRegistrationRecord(subId: string, record: RegistrationRecord): Promise<void>;
|
|
399
|
+
deleteRegistrationRecord(subId: string): Promise<void>;
|
|
400
|
+
deleteRegistrationsRecord(subIds: string[]): Promise<void>;
|
|
401
|
+
fetchRegistrationRecordsBatch(subIds: string[]): Promise<Map<string, RegistrationRecord | null>>;
|
|
402
|
+
getCachedTableColumnTypes(key: string): Promise<CachedPgMetadata | null>;
|
|
403
|
+
setCachedTableColumnsTypes(key: string, value: CachedPgMetadata): Promise<void>;
|
|
404
|
+
/**
|
|
405
|
+
* Race participant: try to claim `lock:recompute:<subId>:<commitTs>`
|
|
406
|
+
* with `SET NX EX`. The single Redis round-trip both arbitrates and
|
|
407
|
+
* sets a TTL fallback in case the winner crashes mid-recompute.
|
|
408
|
+
*/
|
|
409
|
+
tryAcquireRecomputeLock(instanceId: string, subId: string, commitTs: string, ttl: number): Promise<boolean>;
|
|
410
|
+
private getRegistrationKey;
|
|
411
|
+
private getQueryCacheDataKey;
|
|
412
|
+
private getQeruyCacheMetaKey;
|
|
413
|
+
}
|
|
414
|
+
type RedisClient = Redis;
|
|
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, and direct internal-caller
|
|
1301
|
+
* invocations build a per-procedure child logger from the caller's observability —
|
|
1302
|
+
* handlers never null-check it.
|
|
1303
|
+
*/
|
|
1304
|
+
interface HandlerObservability {
|
|
1305
|
+
/** Logger correlated to this operation — request-scoped (reqId + trace id) on
|
|
1306
|
+
* the server path, a per-procedure child logger on internal-caller paths. */
|
|
1307
|
+
log: HandlerLogger;
|
|
1308
|
+
/** The active OpenTelemetry span for this operation. Add attributes/events or
|
|
1309
|
+
* parent child spans off it. A non-recording no-op span when tracing is off. */
|
|
1310
|
+
span?: Span;
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* Query context passed to query handlers.
|
|
1314
|
+
* Contains database reader and user-defined server context.
|
|
1315
|
+
*/
|
|
1316
|
+
/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */
|
|
1317
|
+
interface ConnOpts {
|
|
1318
|
+
/**
|
|
1319
|
+
* Force the PRIMARY (writer) connection even inside a query/action —
|
|
1320
|
+
* read-your-writes. On `useReplicaConn` this overrides the replica choice.
|
|
1321
|
+
*/
|
|
1322
|
+
readOwnWrite?: boolean;
|
|
1323
|
+
}
|
|
1324
|
+
interface QueryCtx<TContext = unknown> extends HandlerObservability {
|
|
1325
|
+
/** Database reader for queries */
|
|
1326
|
+
db: DbReader;
|
|
1327
|
+
/** User-defined server context (auth, requestId, etc.) */
|
|
1328
|
+
serverCtx?: TContext;
|
|
1329
|
+
/**
|
|
1330
|
+
* Route this query's reads to the PRIMARY (writer) connection. Must be called
|
|
1331
|
+
* BEFORE any read (throws otherwise). A no-op when reads already run on primary
|
|
1332
|
+
* (no replica configured, or a primary-only path like a live query).
|
|
1333
|
+
*/
|
|
1334
|
+
usePrimaryConn(opts?: ConnOpts): void;
|
|
1335
|
+
/**
|
|
1336
|
+
* Route this query's reads to the read REPLICA, if one is configured. Must be
|
|
1337
|
+
* called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.
|
|
1338
|
+
*/
|
|
1339
|
+
useReplicaConn(opts?: ConnOpts): void;
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Mutation context passed to mutation handlers.
|
|
1343
|
+
* Contains database writer and user-defined server context.
|
|
1344
|
+
*/
|
|
1345
|
+
interface MutationCtx<TContext = unknown> extends HandlerObservability {
|
|
1346
|
+
/** Database writer for mutations (includes insert/update/delete) */
|
|
1347
|
+
db: DbWriter;
|
|
1348
|
+
/** User-defined server context (auth, requestId, etc.) */
|
|
1349
|
+
serverCtx?: TContext;
|
|
1350
|
+
/**
|
|
1351
|
+
* No-op on a mutation — writes (and their reads) always run on the primary.
|
|
1352
|
+
* Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.
|
|
1353
|
+
* a mutation can reuse a `(ctx: QueryCtx) => …` read helper.
|
|
1354
|
+
*/
|
|
1355
|
+
usePrimaryConn(opts?: ConnOpts): void;
|
|
1356
|
+
/** No-op on a mutation (always primary). See {@link usePrimaryConn}. */
|
|
1357
|
+
useReplicaConn(opts?: ConnOpts): void;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Action context passed to action handlers.
|
|
1361
|
+
*
|
|
1362
|
+
* Actions are the "external I/O" tier: they hold the full {@link SupaliveDb}
|
|
1363
|
+
* (queries + mutations) and are the ONLY context that also carries side-effect
|
|
1364
|
+
* services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}
|
|
1365
|
+
* for scheduling precise one-shots. Queries/mutations stay pure (db only) so
|
|
1366
|
+
* they remain cacheable and transaction-scoped.
|
|
1367
|
+
*/
|
|
1368
|
+
interface ActionCtx<TContext = unknown> extends HandlerObservability {
|
|
1369
|
+
/** Full database interface for queries and mutations */
|
|
1370
|
+
db: SupaliveDb;
|
|
1371
|
+
/** Object storage, when the server was configured with one (see
|
|
1372
|
+
* `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home
|
|
1373
|
+
* for upload/download presigning. */
|
|
1374
|
+
storage: ObjectStorage;
|
|
1375
|
+
/** Job scheduler client for enqueueing precise one-shots, when the server
|
|
1376
|
+
* was configured with a `scheduler`; `undefined` otherwise. Scheduling is
|
|
1377
|
+
* network I/O, so it belongs in actions, never inside a DB transaction. */
|
|
1378
|
+
scheduler: JobClient;
|
|
1379
|
+
/** User-defined server context (auth, requestId, etc.) */
|
|
1380
|
+
serverCtx?: TContext;
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* Job context passed to job handlers. Structurally identical to
|
|
1384
|
+
* {@link ActionCtx}: a job is a server-only procedure that runs
|
|
1385
|
+
* non-transactionally against the full {@link SupaliveDb} and may perform
|
|
1386
|
+
* external work, but it is triggered by the scheduler over HTTP (a cron tick
|
|
1387
|
+
* or a precise one-shot) rather than by a connected client. `serverCtx` is
|
|
1388
|
+
* the system context built by the server's `jobContext` factory.
|
|
1389
|
+
*/
|
|
1390
|
+
interface JobCtx<TContext = unknown> extends HandlerObservability {
|
|
1391
|
+
/** Full database interface for queries and mutations */
|
|
1392
|
+
db: SupaliveDb;
|
|
1393
|
+
/** System server context built by the server for scheduler-triggered runs */
|
|
1394
|
+
serverCtx?: TContext;
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one
|
|
1398
|
+
* procedure from inside another. Pass the caller handler's own `ctx` — its `db`
|
|
1399
|
+
* carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,
|
|
1400
|
+
* inside an action, the full {@link SupaliveDb}. The caller uses this to decide
|
|
1401
|
+
* whether the nested call joins the parent's snapshot (queries) or runs as an
|
|
1402
|
+
* independent sub-transaction (mutations).
|
|
1403
|
+
*/
|
|
1404
|
+
interface ParentCtx<TContext = unknown> {
|
|
1405
|
+
db: DbReader | DbWriter | SupaliveDb;
|
|
1406
|
+
serverCtx?: TContext | undefined;
|
|
1407
|
+
/**
|
|
1408
|
+
* The parent handler's own logger, carried through to a nested
|
|
1409
|
+
* `runQuery`/`runMutation` so the nested call logs under the SAME logger as
|
|
1410
|
+
* its parent (reqId/trace correlation preserved).
|
|
1411
|
+
*/
|
|
1412
|
+
log: HandlerLogger;
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* The slice of the server's {@link Observability} an internal caller needs to
|
|
1416
|
+
* build per-call loggers (see `createCaller().init({ obs })`). Structural, so an
|
|
1417
|
+
* `Observability` instance satisfies it without the caller depending on it.
|
|
1418
|
+
*/
|
|
1419
|
+
interface CallerObservability {
|
|
1420
|
+
lazyChildLogger(fields: Record<string, unknown>): HandlerLogger;
|
|
1421
|
+
}
|
|
1422
|
+
type QueryFn<TInput, TResult, TContext = unknown> = (ctx: QueryCtx<TContext>, input: TInput) => Promise<TResult>;
|
|
1423
|
+
type MutationFn<TInput, TResult, TContext = unknown> = (ctx: MutationCtx<TContext>, input: TInput) => Promise<TResult>;
|
|
1424
|
+
type ActionFn<TInput, TResult, TContext = unknown> = (ctx: ActionCtx<TContext>, input: TInput) => Promise<TResult>;
|
|
1425
|
+
type JobFn<TInput, TResult, TContext = unknown> = (ctx: JobCtx<TContext>, input: TInput) => Promise<TResult>;
|
|
1426
|
+
/**
|
|
1427
|
+
* Per-procedure override for the cache/subscription segmentation key.
|
|
1428
|
+
*
|
|
1429
|
+
* omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)
|
|
1430
|
+
* false → no identity in hash; cache/sub shared across all users
|
|
1431
|
+
* string → a static identity literal (e.g. "public" or a tenant id)
|
|
1432
|
+
* function → compute from serverCtx + input (sync)
|
|
1433
|
+
*
|
|
1434
|
+
* When the result of a query is identical regardless of who calls it, set
|
|
1435
|
+
* this to a literal (or `false`) so a single cache entry serves everyone.
|
|
1436
|
+
*
|
|
1437
|
+
* The function form intentionally takes `serverCtx` (not the full `QueryCtx`)
|
|
1438
|
+
* because identity is resolved before any DB read is issued.
|
|
1439
|
+
*/
|
|
1440
|
+
type QueryIdentitySpec<TInput, TContext> = false | string | ((serverCtx: TContext, input: TInput) => string | null | undefined);
|
|
1441
|
+
interface BaseProcedure<TInput, TResult, TType extends "query" | "mutation" | "action" | "job", TContext = unknown, TInternal extends boolean = boolean> {
|
|
1442
|
+
readonly _type: "procedure";
|
|
1443
|
+
readonly procedureType: TType;
|
|
1444
|
+
readonly inputSchema: ZodType<TInput>;
|
|
1445
|
+
readonly outputSchema?: ZodType<any>;
|
|
1446
|
+
readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;
|
|
1447
|
+
readonly internal: TInternal;
|
|
1448
|
+
}
|
|
1449
|
+
interface QueryProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "query", TContext, TInternal> {
|
|
1450
|
+
readonly procedureType: "query";
|
|
1451
|
+
readonly fn: QueryFn<TInput, TResult, TContext>;
|
|
1452
|
+
readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;
|
|
1453
|
+
}
|
|
1454
|
+
interface MutationProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "mutation", TContext, TInternal> {
|
|
1455
|
+
readonly procedureType: "mutation";
|
|
1456
|
+
readonly fn: MutationFn<TInput, TResult, TContext>;
|
|
1457
|
+
}
|
|
1458
|
+
interface ActionProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "action", TContext, TInternal> {
|
|
1459
|
+
readonly procedureType: "action";
|
|
1460
|
+
readonly fn: ActionFn<TInput, TResult, TContext>;
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* A scheduler-triggered, server-only procedure. Runs like an action (full
|
|
1464
|
+
* db, non-transactional, may do external work) but is dispatched by the
|
|
1465
|
+
* server's HTTP job endpoint on a cron tick or a precise one-shot rather
|
|
1466
|
+
* than over the client WebSocket. Always {@link internal}: true, so it is
|
|
1467
|
+
* never reachable via `call`/`subscribe`.
|
|
1468
|
+
*/
|
|
1469
|
+
interface JobProcedure<TInput, TResult, TContext = unknown> extends BaseProcedure<TInput, TResult, "job", TContext, true> {
|
|
1470
|
+
readonly procedureType: "job";
|
|
1471
|
+
readonly fn: JobFn<TInput, TResult, TContext>;
|
|
1472
|
+
/**
|
|
1473
|
+
* Cron expression for a recurring job (e.g. `"0 3 * * *"`). Declared crons
|
|
1474
|
+
* are synced to the scheduler at server startup. Omit for a job that is
|
|
1475
|
+
* only ever invoked as a precise one-shot via the scheduler API.
|
|
1476
|
+
*/
|
|
1477
|
+
readonly cron?: string;
|
|
1478
|
+
}
|
|
1479
|
+
type AnyProcedure<TContext = unknown> = QueryProcedure<any, any, TContext> | MutationProcedure<any, any, TContext> | ActionProcedure<any, any, TContext> | JobProcedure<any, any, TContext>;
|
|
1480
|
+
interface QueryConfig<TInput, TResult, TContext = unknown> {
|
|
1481
|
+
/** Zod schema for input validation */
|
|
1482
|
+
args: ZodType<TInput>;
|
|
1483
|
+
/** The query handler function */
|
|
1484
|
+
handler: QueryFn<TInput, TResult, TContext>;
|
|
1485
|
+
/** Mark as internal (server-only). Default: false */
|
|
1486
|
+
internal?: boolean;
|
|
1487
|
+
/**
|
|
1488
|
+
* Optional Zod schema describing return-type overrides for codegen.
|
|
1489
|
+
* Only the fields you specify are overridden; everything else is inferred
|
|
1490
|
+
* from the handler's TypeScript return type. Use `.modelName("Name")`
|
|
1491
|
+
* on a Zod object to rename the generated model class.
|
|
1492
|
+
*/
|
|
1493
|
+
returns?: ZodType<any>;
|
|
1494
|
+
/**
|
|
1495
|
+
* Override the cache/subscription segmentation key for this procedure.
|
|
1496
|
+
* See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.
|
|
1497
|
+
*/
|
|
1498
|
+
queryIdentity?: QueryIdentitySpec<TInput, TContext>;
|
|
1499
|
+
}
|
|
1500
|
+
interface MutationConfig<TInput, TResult, TContext = unknown> {
|
|
1501
|
+
/** Zod schema for input validation */
|
|
1502
|
+
args: ZodType<TInput>;
|
|
1503
|
+
/** The mutation handler function */
|
|
1504
|
+
handler: MutationFn<TInput, TResult, TContext>;
|
|
1505
|
+
/** Mark as internal (server-only). Default: false */
|
|
1506
|
+
internal?: boolean;
|
|
1507
|
+
/**
|
|
1508
|
+
* Optional Zod schema describing return-type overrides for codegen.
|
|
1509
|
+
* Only the fields you specify are overridden; everything else is inferred
|
|
1510
|
+
* from the handler's TypeScript return type.
|
|
1511
|
+
*/
|
|
1512
|
+
returns?: ZodType<any>;
|
|
1513
|
+
}
|
|
1514
|
+
interface ActionConfig<TInput, TResult, TContext = unknown> {
|
|
1515
|
+
/** Zod schema for input validation */
|
|
1516
|
+
args: ZodType<TInput>;
|
|
1517
|
+
/** The action handler function */
|
|
1518
|
+
handler: ActionFn<TInput, TResult, TContext>;
|
|
1519
|
+
/** Mark as internal (server-only). Default: false */
|
|
1520
|
+
internal?: boolean;
|
|
1521
|
+
/**
|
|
1522
|
+
* Optional Zod schema describing return-type overrides for codegen.
|
|
1523
|
+
* Only the fields you specify are overridden; everything else is inferred
|
|
1524
|
+
* from the handler's TypeScript return type.
|
|
1525
|
+
*/
|
|
1526
|
+
returns?: ZodType<any>;
|
|
1527
|
+
}
|
|
1528
|
+
interface JobConfig<TInput, TResult, TContext = unknown> {
|
|
1529
|
+
/** Zod schema for the job payload */
|
|
1530
|
+
args: ZodType<TInput>;
|
|
1531
|
+
/** The job handler function */
|
|
1532
|
+
handler: JobFn<TInput, TResult, TContext>;
|
|
1533
|
+
/**
|
|
1534
|
+
* Cron expression for a recurring schedule (e.g. `"0 3 * * *"`). Omit for a
|
|
1535
|
+
* job that is only invoked as a precise one-shot.
|
|
1536
|
+
*/
|
|
1537
|
+
cron?: string;
|
|
1538
|
+
}
|
|
1539
|
+
/** Extract input type from a procedure */
|
|
1540
|
+
type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;
|
|
1541
|
+
/** Extract output type from a procedure */
|
|
1542
|
+
type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;
|
|
1543
|
+
/** Extract procedure type (query/mutation) */
|
|
1544
|
+
type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;
|
|
1545
|
+
/** Extract server context type from a procedure */
|
|
1546
|
+
type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;
|
|
1547
|
+
/**
|
|
1548
|
+
* Create a query builder with a pre-defined context type.
|
|
1549
|
+
* This allows you to define the context type once and have it inferred
|
|
1550
|
+
* automatically in all your query handlers.
|
|
1551
|
+
*
|
|
1552
|
+
* @example
|
|
1553
|
+
* // Define your server context
|
|
1554
|
+
* interface ServerContext {
|
|
1555
|
+
* auth: { userId: string };
|
|
1556
|
+
* requestId: string;
|
|
1557
|
+
* }
|
|
1558
|
+
*
|
|
1559
|
+
* // Create a typed query builder
|
|
1560
|
+
* const query = createQueryBuilder<ServerContext>();
|
|
1561
|
+
*
|
|
1562
|
+
* // Use it - context type is automatically inferred!
|
|
1563
|
+
* const getUser = query({
|
|
1564
|
+
* args: z.object({ id: z.string() }),
|
|
1565
|
+
* handler: async (ctx, { id }) => {
|
|
1566
|
+
* // ctx.db for database queries
|
|
1567
|
+
* const user = await ctx.db.query(UsersSchema).find(id);
|
|
1568
|
+
* // ctx.context for server context
|
|
1569
|
+
* console.log(ctx.context.requestId);
|
|
1570
|
+
* return user;
|
|
1571
|
+
* }
|
|
1572
|
+
* });
|
|
1573
|
+
*/
|
|
1574
|
+
declare function createQueryBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: QueryConfig<TInput, TResult, TContext> & {
|
|
1575
|
+
internal?: TInternal;
|
|
1576
|
+
}) => QueryProcedure<TInput, TResult, TContext, TInternal>;
|
|
1577
|
+
/**
|
|
1578
|
+
* Create a mutation builder with a pre-defined context type.
|
|
1579
|
+
* This allows you to define the context type once and have it inferred
|
|
1580
|
+
* automatically in all your mutation handlers.
|
|
1581
|
+
*
|
|
1582
|
+
* @example
|
|
1583
|
+
* // Define your server context
|
|
1584
|
+
* interface ServerContext {
|
|
1585
|
+
* auth: { userId: string };
|
|
1586
|
+
* requestId: string;
|
|
1587
|
+
* }
|
|
1588
|
+
*
|
|
1589
|
+
* // Create a typed mutation builder
|
|
1590
|
+
* const mutation = createMutationBuilder<ServerContext>();
|
|
1591
|
+
*
|
|
1592
|
+
* // Use it - context type is automatically inferred!
|
|
1593
|
+
* const createUser = mutation({
|
|
1594
|
+
* args: z.object({ name: z.string() }),
|
|
1595
|
+
* handler: async (ctx, { name }) => {
|
|
1596
|
+
* // ctx.db for mutations
|
|
1597
|
+
* await ctx.db.insert(UsersSchema, id, { name });
|
|
1598
|
+
* // ctx.context for server context
|
|
1599
|
+
* console.log(ctx.context.requestId);
|
|
1600
|
+
* return { success: true };
|
|
1601
|
+
* }
|
|
1602
|
+
* });
|
|
1603
|
+
*/
|
|
1604
|
+
declare function createMutationBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: MutationConfig<TInput, TResult, TContext> & {
|
|
1605
|
+
internal?: TInternal;
|
|
1606
|
+
}) => MutationProcedure<TInput, TResult, TContext, TInternal>;
|
|
1607
|
+
/**
|
|
1608
|
+
* Create an action builder with a pre-defined context type.
|
|
1609
|
+
* Actions have access to the full SupaliveDb for both queries and mutations.
|
|
1610
|
+
*
|
|
1611
|
+
* @example
|
|
1612
|
+
* // Define your server context
|
|
1613
|
+
* interface ServerContext {
|
|
1614
|
+
* auth: { userId: string };
|
|
1615
|
+
* requestId: string;
|
|
1616
|
+
* }
|
|
1617
|
+
*
|
|
1618
|
+
* // Create a typed action builder
|
|
1619
|
+
* const action = createActionBuilder<ServerContext>();
|
|
1620
|
+
*
|
|
1621
|
+
* // Use it - context type is automatically inferred!
|
|
1622
|
+
* const processOrder = action({
|
|
1623
|
+
* args: z.object({ orderId: z.string() }),
|
|
1624
|
+
* handler: async (ctx, { orderId }) => {
|
|
1625
|
+
* // ctx.db for full database access
|
|
1626
|
+
* const order = await ctx.db.query(async (db) => {
|
|
1627
|
+
* return db.query(OrdersSchema).find(orderId);
|
|
1628
|
+
* });
|
|
1629
|
+
* await ctx.db.mutation(async (db) => {
|
|
1630
|
+
* await db.update(OrdersSchema, orderId, { status: "processed" });
|
|
1631
|
+
* });
|
|
1632
|
+
* // ctx.context for server context
|
|
1633
|
+
* console.log(ctx.context.requestId);
|
|
1634
|
+
* return { success: true };
|
|
1635
|
+
* }
|
|
1636
|
+
* });
|
|
1637
|
+
*/
|
|
1638
|
+
declare function createActionBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: ActionConfig<TInput, TResult, TContext> & {
|
|
1639
|
+
internal?: TInternal;
|
|
1640
|
+
}) => ActionProcedure<TInput, TResult, TContext, TInternal>;
|
|
1641
|
+
/**
|
|
1642
|
+
* Create a job builder with a pre-defined context type. A job is a
|
|
1643
|
+
* server-only procedure invoked by the scheduler over HTTP — either on its
|
|
1644
|
+
* declared `cron` schedule or as a precise one-shot enqueued via the
|
|
1645
|
+
* server's job API. Jobs run like actions (full db, non-transactional) and
|
|
1646
|
+
* are always internal, so they are never reachable from a client.
|
|
1647
|
+
*
|
|
1648
|
+
* @example
|
|
1649
|
+
* const job = createJobBuilder<ServerContext>();
|
|
1650
|
+
*
|
|
1651
|
+
* export const cleanupOtps = job({
|
|
1652
|
+
* cron: "0 * * * *", // hourly
|
|
1653
|
+
* args: z.object({}),
|
|
1654
|
+
* handler: async (ctx) => {
|
|
1655
|
+
* await ctx.db.mutation(async (db) => { ... });
|
|
1656
|
+
* return { ok: true };
|
|
1657
|
+
* },
|
|
1658
|
+
* });
|
|
1659
|
+
*/
|
|
1660
|
+
declare function createJobBuilder<TContext = unknown>(): <TInput, TResult>(config: JobConfig<TInput, TResult, TContext>) => JobProcedure<TInput, TResult, TContext>;
|
|
1661
|
+
//#endregion
|
|
1662
|
+
//#region src/router/router.d.ts
|
|
1663
|
+
/**
|
|
1664
|
+
* A router maps procedure names (keys) to their definitions.
|
|
1665
|
+
* This is the type that's exported from your app and used by the client.
|
|
1666
|
+
*/
|
|
1667
|
+
type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {
|
|
1668
|
+
_type: "router";
|
|
1669
|
+
procedures: TProcedures;
|
|
1670
|
+
contextName: string;
|
|
1671
|
+
};
|
|
1672
|
+
/**
|
|
1673
|
+
* Inferred AppRouter type from router() call.
|
|
1674
|
+
* Captures the full procedure map for client type inference.
|
|
1675
|
+
*/
|
|
1676
|
+
type AppRouter<TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>, TContext = unknown> = Router<TProcedures, TContext>;
|
|
1677
|
+
/** Get query procedures only from a router */
|
|
1678
|
+
type QueryProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
|
|
1679
|
+
procedureType: "query";
|
|
1680
|
+
} ? K : never]: T[K] };
|
|
1681
|
+
/** Get mutation procedures only from a router */
|
|
1682
|
+
type MutationProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
|
|
1683
|
+
procedureType: "mutation";
|
|
1684
|
+
} ? K : never]: T[K] };
|
|
1685
|
+
/** Get action procedures only from a router */
|
|
1686
|
+
type ActionProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
|
|
1687
|
+
procedureType: "action";
|
|
1688
|
+
} ? K : never]: T[K] };
|
|
1689
|
+
/** Get job procedures only from a router */
|
|
1690
|
+
type JobProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
|
|
1691
|
+
procedureType: "job";
|
|
1692
|
+
} ? K : never]: T[K] };
|
|
1693
|
+
/** Get public (non-internal) procedures - for client type safety */
|
|
1694
|
+
type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<T, { [K in keyof T]: T[K] extends {
|
|
1695
|
+
internal: true;
|
|
1696
|
+
} ? never : K }[keyof T]>;
|
|
1697
|
+
/** Extract procedure names from a router */
|
|
1698
|
+
type ProcedureNames<T extends Router<any>> = T extends Router<infer P> ? keyof P : never;
|
|
1699
|
+
type RouterConfig<T> = {
|
|
1700
|
+
procedures: T;
|
|
1701
|
+
contextName?: string;
|
|
1702
|
+
};
|
|
1703
|
+
/**
|
|
1704
|
+
* Create a router from procedure definitions.
|
|
1705
|
+
* Procedure names are inferred from the object keys.
|
|
1706
|
+
*
|
|
1707
|
+
* @example
|
|
1708
|
+
* const appRouter = router({
|
|
1709
|
+
* procedures: {
|
|
1710
|
+
* getUser,
|
|
1711
|
+
* createUser,
|
|
1712
|
+
* internalGetAll,
|
|
1713
|
+
* },
|
|
1714
|
+
* });
|
|
1715
|
+
*
|
|
1716
|
+
* export type AppRouter = typeof appRouter;
|
|
1717
|
+
*/
|
|
1718
|
+
declare function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(config: RouterConfig<TProcedures>): Router<TProcedures, TContext>;
|
|
1719
|
+
interface RegisteredProcedure<TContext = unknown> {
|
|
1720
|
+
name: string;
|
|
1721
|
+
type: "query" | "mutation" | "action" | "job";
|
|
1722
|
+
internal: boolean;
|
|
1723
|
+
inputSchema: AnyProcedure<TContext>["inputSchema"];
|
|
1724
|
+
fn: AnyProcedure<TContext>["fn"];
|
|
1725
|
+
/** Only present for `type === "query"`. See `QueryIdentitySpec`. */
|
|
1726
|
+
queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);
|
|
1727
|
+
/** Only present for `type === "job"`. Cron expression for recurring jobs. */
|
|
1728
|
+
cron?: string;
|
|
1729
|
+
}
|
|
1730
|
+
declare function getContextRegistry(inContext: string): ContextRegistry;
|
|
1731
|
+
declare class ContextRegistry {
|
|
1732
|
+
procedureRegistry: Map<string, RegisteredProcedure<any>>;
|
|
1733
|
+
internalProcedureNames: Set<string>;
|
|
1734
|
+
registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void;
|
|
1735
|
+
/** Get a registered procedure by name (runtime lookup) */
|
|
1736
|
+
getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined;
|
|
1737
|
+
/** Get all registered procedure names */
|
|
1738
|
+
getProcedureNames(): string[];
|
|
1739
|
+
/** Get all registered procedures */
|
|
1740
|
+
getAllProcedures(): Map<string, RegisteredProcedure>;
|
|
1741
|
+
/** Get all registered job procedures (server-only, scheduler-triggered). */
|
|
1742
|
+
getJobProcedures(): RegisteredProcedure[];
|
|
1743
|
+
/** Clear the registry (for testing only) */
|
|
1744
|
+
clearRegistry(): void;
|
|
1745
|
+
markInternalProcedure(name: string): void;
|
|
1746
|
+
isInternalProcedure(name: string): boolean;
|
|
1747
|
+
clearInternalProcedures(): void;
|
|
1748
|
+
}
|
|
1749
|
+
//#endregion
|
|
1750
|
+
//#region src/client/ws_client_manager.d.ts
|
|
1751
|
+
declare class RPCError extends Error {
|
|
1752
|
+
code?: string;
|
|
1753
|
+
constructor(message: string, code?: string);
|
|
1754
|
+
}
|
|
1755
|
+
type ClientLogLevel = "debug" | "info" | "warn" | "error" | "silent";
|
|
1756
|
+
/** Minimal logger sink the client writes lifecycle/diagnostic lines to. Pass a
|
|
1757
|
+
* custom implementation via {@link WSClientOptions.logger} to route logs into
|
|
1758
|
+
* your app's logger; otherwise a console sink gated by
|
|
1759
|
+
* {@link WSClientOptions.logLevel} is used. */
|
|
1760
|
+
interface ClientLogger {
|
|
1761
|
+
debug(message: string, ...args: unknown[]): void;
|
|
1762
|
+
info(message: string, ...args: unknown[]): void;
|
|
1763
|
+
warn(message: string, ...args: unknown[]): void;
|
|
1764
|
+
error(message: string, ...args: unknown[]): void;
|
|
1765
|
+
}
|
|
1766
|
+
/** A structured lifecycle event, for feeding client metrics without parsing logs. */
|
|
1767
|
+
interface ClientEvent {
|
|
1768
|
+
type: "connecting" | "connected" | "disconnected" | "reconnecting" | "error";
|
|
1769
|
+
/** Reason/detail (e.g. reconnect trigger, close reason). */
|
|
1770
|
+
detail?: string;
|
|
1771
|
+
/** Reconnect attempt number, when `type === "reconnecting"`. */
|
|
1772
|
+
attempt?: number;
|
|
1773
|
+
}
|
|
1774
|
+
/** Console-backed logger that drops anything below `level`. `"silent"` mutes all. */
|
|
1775
|
+
declare function createConsoleLogger(level?: ClientLogLevel): ClientLogger;
|
|
1776
|
+
interface HeartbeatOptions {
|
|
1777
|
+
/**
|
|
1778
|
+
* Close + reconnect when no server message arrives for this long. The
|
|
1779
|
+
* server emits `{type:"ping"}` every ~15s of channel idle, so anything
|
|
1780
|
+
* larger than ~30s leaves comfortable headroom. Default 60_000.
|
|
1781
|
+
*/
|
|
1782
|
+
serverInactivityMs?: number;
|
|
1783
|
+
}
|
|
1784
|
+
interface SendThrottleOptions {
|
|
1785
|
+
/** Yield the event loop every N `call()` invocations. 0 disables. Default 100. */
|
|
1786
|
+
everyN?: number;
|
|
1787
|
+
/** Length of the yield in ms. Default 10. */
|
|
1788
|
+
delayMs?: number;
|
|
1789
|
+
}
|
|
1790
|
+
interface WSClientOptions {
|
|
1791
|
+
/** WebSocket URL (e.g. ws://localhost:3000/ws) */
|
|
1792
|
+
url: string;
|
|
1793
|
+
/** Auth token to send after connection */
|
|
1794
|
+
token?: () => Promise<string | undefined>;
|
|
1795
|
+
/** Optional: reconnection timeout in ms (default: 180000 = 3 minutes) */
|
|
1796
|
+
reconnectionTimeout?: number;
|
|
1797
|
+
/** Reconnection options */
|
|
1798
|
+
reconnect?: {
|
|
1799
|
+
/** Enable automatic reconnection (default: true) */enabled?: boolean; /** Max reconnection attempts (default: 5) */
|
|
1800
|
+
maxAttempts?: number; /** Delay between attempts in ms (default: 1000) */
|
|
1801
|
+
delay?: number; /** Exponential backoff multiplier (default: 1.5) */
|
|
1802
|
+
backoff?: number;
|
|
1803
|
+
};
|
|
1804
|
+
/** Server-inactivity watchdog. See {@link HeartbeatOptions.serverInactivityMs}. */
|
|
1805
|
+
heartbeat?: HeartbeatOptions;
|
|
1806
|
+
/**
|
|
1807
|
+
* Yields the event loop for `delayMs` ms after every `everyN`
|
|
1808
|
+
* `call()` invocations. Useful for keeping React renders / GC tasks
|
|
1809
|
+
* scheduled during long synchronous bursts of mutations/actions; the
|
|
1810
|
+
* heartbeat does not depend on this (the server drives it).
|
|
1811
|
+
* Default `{ everyN: 100, delayMs: 10 }`. Set `everyN: 0` to disable.
|
|
1812
|
+
*/
|
|
1813
|
+
throttle?: SendThrottleOptions;
|
|
1814
|
+
/** Called when connection is established */
|
|
1815
|
+
onConnect?: () => void;
|
|
1816
|
+
/** Called when connection is lost */
|
|
1817
|
+
onDisconnect?: () => void;
|
|
1818
|
+
/** Called on connection error */
|
|
1819
|
+
onError?: (error: Error) => void;
|
|
1820
|
+
/**
|
|
1821
|
+
* Custom log sink. When set, it receives all lifecycle/diagnostic lines and
|
|
1822
|
+
* `logLevel` is ignored (filtering is the sink's responsibility). When unset,
|
|
1823
|
+
* a console sink gated by {@link logLevel} is used.
|
|
1824
|
+
*/
|
|
1825
|
+
logger?: ClientLogger;
|
|
1826
|
+
/** Level for the default console logger. Default `"warn"` (quiet). */
|
|
1827
|
+
logLevel?: ClientLogLevel;
|
|
1828
|
+
/** Optional structured lifecycle events, for client-side metrics. */
|
|
1829
|
+
onEvent?: (event: ClientEvent) => void;
|
|
1830
|
+
/**
|
|
1831
|
+
* OpenTelemetry-agnostic trace propagation. Return the current W3C
|
|
1832
|
+
* `traceparent` for the active client span (e.g. from `@opentelemetry/api`'s
|
|
1833
|
+
* propagation) and it is sent on every `call`/`subscribe`; the server
|
|
1834
|
+
* continues the trace. Return `undefined` (the default — no hook) to send
|
|
1835
|
+
* nothing. Called per outbound request.
|
|
1836
|
+
*/
|
|
1837
|
+
getTraceparent?: () => string | undefined | null;
|
|
1838
|
+
}
|
|
1839
|
+
/**
|
|
1840
|
+
* Public state of the client, surfaced to consumers (React provider, etc.).
|
|
1841
|
+
* - "connecting" — initial connect or reconnect handshake in flight
|
|
1842
|
+
* - "authenticating" — connected, waiting for auth result
|
|
1843
|
+
* - "ready" — connected and auth resolved (authenticated, anonymous, or
|
|
1844
|
+
* explicitly failed — i.e. ready to send calls)
|
|
1845
|
+
* - "disconnected" — currently offline (may auto-retry)
|
|
1846
|
+
*/
|
|
1847
|
+
type ClientPublicState = "disconnected" | "connecting" | "authenticating" | "ready";
|
|
1848
|
+
declare class WsClientManager {
|
|
1849
|
+
private ws;
|
|
1850
|
+
private options;
|
|
1851
|
+
private lastSuccessfulConnectionTime;
|
|
1852
|
+
private reconnectionTimeout;
|
|
1853
|
+
private requestId;
|
|
1854
|
+
private pendingRequests;
|
|
1855
|
+
/**
|
|
1856
|
+
* Single source of truth for live subscriptions.
|
|
1857
|
+
*
|
|
1858
|
+
* Keying:
|
|
1859
|
+
* - In-flight subscribe (no subId yet): `_pending:<requestId>`.
|
|
1860
|
+
* - Established: the server-returned canonical `subId`.
|
|
1861
|
+
*
|
|
1862
|
+
* Routing `sub:update` / `sub:gone` is O(1) (`get(subId)`). Subscribe-time
|
|
1863
|
+
* dedup scans `values()` for a matching `localKey` (O(N)), which is cheap
|
|
1864
|
+
* since subscribes happen on component mounts, not in the hot path.
|
|
1865
|
+
*/
|
|
1866
|
+
private subscriptions;
|
|
1867
|
+
private queuedCalls;
|
|
1868
|
+
private reconnectAttempts;
|
|
1869
|
+
private reconnectTimer;
|
|
1870
|
+
private connectionState;
|
|
1871
|
+
private authState;
|
|
1872
|
+
/**
|
|
1873
|
+
* Authenticated user id from `auth:success`. Distinct from `queryIdentity`
|
|
1874
|
+
* (server-side cache/sub segmentation key); this is just "who am I logged
|
|
1875
|
+
* in as" for app display purposes. Null while unauthenticated / anonymous.
|
|
1876
|
+
*/
|
|
1877
|
+
private authUserId;
|
|
1878
|
+
private explicitlyClosed;
|
|
1879
|
+
private stateListeners;
|
|
1880
|
+
private lastPublicState;
|
|
1881
|
+
private highWaterTs;
|
|
1882
|
+
private serverInactivityMs;
|
|
1883
|
+
private lastServerMessageAt;
|
|
1884
|
+
private inactivityTimer;
|
|
1885
|
+
private pendingConnectResolve;
|
|
1886
|
+
private pendingConnectReject;
|
|
1887
|
+
private throttleEveryN;
|
|
1888
|
+
private throttleDelayMs;
|
|
1889
|
+
private throttleCounter;
|
|
1890
|
+
private throttling;
|
|
1891
|
+
private visibilityListener;
|
|
1892
|
+
private onlineListener;
|
|
1893
|
+
private readonly log;
|
|
1894
|
+
constructor(options: WSClientOptions);
|
|
1895
|
+
/**
|
|
1896
|
+
* Subscribe to client state transitions. Returns an unsubscribe fn.
|
|
1897
|
+
* The listener is called immediately with the current state.
|
|
1898
|
+
*/
|
|
1899
|
+
onState(listener: (s: ClientPublicState) => void): () => void;
|
|
1900
|
+
/** Current public state. */
|
|
1901
|
+
getPublicState(): ClientPublicState;
|
|
1902
|
+
/**
|
|
1903
|
+
* Connect to the WebSocket server.
|
|
1904
|
+
* Returns a promise that resolves when connected and authenticated.
|
|
1905
|
+
*/
|
|
1906
|
+
connect(): Promise<void>;
|
|
1907
|
+
/**
|
|
1908
|
+
* Disconnect from the server.
|
|
1909
|
+
*/
|
|
1910
|
+
disconnect(): void;
|
|
1911
|
+
/**
|
|
1912
|
+
* Check if connected and authenticated.
|
|
1913
|
+
*/
|
|
1914
|
+
isReady(): boolean;
|
|
1915
|
+
/**
|
|
1916
|
+
* Check if authenticated.
|
|
1917
|
+
*/
|
|
1918
|
+
isAuthenticated(): boolean;
|
|
1919
|
+
/**
|
|
1920
|
+
* Check if anonymouse.
|
|
1921
|
+
*/
|
|
1922
|
+
isAnonymouse(): boolean;
|
|
1923
|
+
/**
|
|
1924
|
+
* The authenticated user's id (from `auth:success`), or null when
|
|
1925
|
+
* unauthenticated / anonymous. Useful for "Logged in as …" display.
|
|
1926
|
+
*
|
|
1927
|
+
* Not to be confused with server-side `queryIdentity`, which is the
|
|
1928
|
+
* cache/subscription segmentation key (resolved entirely on the server).
|
|
1929
|
+
*/
|
|
1930
|
+
getAuthUserId(): string | null;
|
|
1931
|
+
/**
|
|
1932
|
+
* Call a procedure (query, mutation, or action).
|
|
1933
|
+
*
|
|
1934
|
+
* If the client is not ready (disconnected or still authenticating), the
|
|
1935
|
+
* call is FIFO-queued and dispatched on the next ready state. The promise
|
|
1936
|
+
* still resolves with the eventual server response.
|
|
1937
|
+
*
|
|
1938
|
+
* Pass `onSend` to be notified when the call actually leaves the queue
|
|
1939
|
+
* (used by `useMutation` to flip `state` from "queued" → "loading").
|
|
1940
|
+
*/
|
|
1941
|
+
call(procedure: string, input: unknown, options?: {
|
|
1942
|
+
onSend?: () => void;
|
|
1943
|
+
}): Promise<unknown>;
|
|
1944
|
+
/**
|
|
1945
|
+
* Throttle drain loop. Each iteration: sleep `throttleDelayMs`, then
|
|
1946
|
+
* dispatch up to `throttleEveryN` queued items. Exits as soon as the
|
|
1947
|
+
* queue drains inside a single batch (burst over, back to direct
|
|
1948
|
+
* dispatch on the next `call()`) or the connection goes away
|
|
1949
|
+
* (reconnect path will restart us via `flushQueuedCalls`).
|
|
1950
|
+
*/
|
|
1951
|
+
private runThrottleLoop;
|
|
1952
|
+
/**
|
|
1953
|
+
* Issue the call against an established connection. Caller must ensure
|
|
1954
|
+
* `isReady()` before invoking.
|
|
1955
|
+
*/
|
|
1956
|
+
private dispatchCall;
|
|
1957
|
+
/** Advance the read high-water from a server-returned `ts` (monotonic). */
|
|
1958
|
+
private advanceHighWater;
|
|
1959
|
+
/**
|
|
1960
|
+
* Flush queued calls in FIFO order. Called once `isReady()` becomes
|
|
1961
|
+
* true. With the throttle enabled, dispatch the first batch
|
|
1962
|
+
* synchronously then hand off to the drain loop so a large
|
|
1963
|
+
* post-reconnect flush respects backpressure instead of dumping 10k
|
|
1964
|
+
* frames in one tick.
|
|
1965
|
+
*/
|
|
1966
|
+
private flushQueuedCalls;
|
|
1967
|
+
/**
|
|
1968
|
+
* Re-send `subscribe` for every existing subscription. The subId for each
|
|
1969
|
+
* may legitimately change (e.g. `queryIdentity` was a function of user
|
|
1970
|
+
* identity and the user changed during the disconnect), so we re-key the
|
|
1971
|
+
* unified `subscriptions` Map: snapshot every record, drop them from the
|
|
1972
|
+
* Map, then reinsert under a fresh `_pending:<reqId>` key. Each pending
|
|
1973
|
+
* request's `resolve` rekeys the parked record under the new server-issued
|
|
1974
|
+
* subId so subsequent `sub:update` frames route to the existing
|
|
1975
|
+
* `onUpdate` callback (which the React handle is still holding).
|
|
1976
|
+
*/
|
|
1977
|
+
private resubscribeAll;
|
|
1978
|
+
/**
|
|
1979
|
+
* Subscribe to a live query.
|
|
1980
|
+
*
|
|
1981
|
+
* The client does not compute the subId locally — it sends the
|
|
1982
|
+
* (procedure, input) pair and receives the canonical subId on the
|
|
1983
|
+
* subscribe response. This lets the server's per-procedure
|
|
1984
|
+
* `queryIdentity` override be authoritative without forcing the client
|
|
1985
|
+
* to mirror any of the resolution logic.
|
|
1986
|
+
*
|
|
1987
|
+
* Returns the server-assigned subId and an unsubscribe function.
|
|
1988
|
+
*/
|
|
1989
|
+
subscribe(procedure: string, input: unknown, serializedInput: string, onUpdate: (data: unknown) => void, onGone?: (reason: string | undefined) => void): Promise<{
|
|
1990
|
+
subId: string;
|
|
1991
|
+
unsubscribe: () => void;
|
|
1992
|
+
}>;
|
|
1993
|
+
private findSubByLocalKey;
|
|
1994
|
+
/** Resolve every joiner waiting on this Subscription with the canonical subId. */
|
|
1995
|
+
private resolveJoiners;
|
|
1996
|
+
/** Reject every joiner waiting on this Subscription with the given error. */
|
|
1997
|
+
private rejectJoiners;
|
|
1998
|
+
private unsubscribeByLocalKey;
|
|
1999
|
+
private handleMessage;
|
|
2000
|
+
/**
|
|
2001
|
+
* Called once the client transitions to a "ready" state on a fresh
|
|
2002
|
+
* connection. Replays live-query subscriptions and flushes any queued
|
|
2003
|
+
* calls in FIFO order.
|
|
2004
|
+
*/
|
|
2005
|
+
private afterReady;
|
|
2006
|
+
private handleResponse;
|
|
2007
|
+
private handleSubscriptionUpdate;
|
|
2008
|
+
/**
|
|
2009
|
+
* Handles a `sub:gone` message: the server no longer tracks this
|
|
2010
|
+
* subscription (e.g. it was fully unregistered while we were disconnected
|
|
2011
|
+
* from the sub-manager). Notify the handle and drop the local entry so a
|
|
2012
|
+
* re-subscribe is required to receive further updates.
|
|
2013
|
+
*/
|
|
2014
|
+
private handleSubscriptionGone;
|
|
2015
|
+
private handleClose;
|
|
2016
|
+
private handleError;
|
|
2017
|
+
private startInactivityWatchdog;
|
|
2018
|
+
private stopInactivityWatchdog;
|
|
2019
|
+
/**
|
|
2020
|
+
* Close the current WebSocket and schedule a reconnect via `handleClose`.
|
|
2021
|
+
*
|
|
2022
|
+
* Atomically swaps the old socket's event handlers to no-ops BEFORE
|
|
2023
|
+
* `close()` so a frame in flight at the moment of close cannot fire
|
|
2024
|
+
* `handleMessage` into a half-cleaned state — that was the source of
|
|
2025
|
+
* the "browser says socket is alive but client says disconnected" race.
|
|
2026
|
+
*/
|
|
2027
|
+
private closeAndReconnect;
|
|
2028
|
+
private installEnvironmentListeners;
|
|
2029
|
+
private removeEnvironmentListeners;
|
|
2030
|
+
private scheduleReconnect;
|
|
2031
|
+
private computePublicState;
|
|
2032
|
+
private emitState;
|
|
2033
|
+
/** Fire the optional structured lifecycle event; never lets a throwing hook
|
|
2034
|
+
* break the client. */
|
|
2035
|
+
private emitEvent;
|
|
2036
|
+
private ensureConnected;
|
|
2037
|
+
private send;
|
|
2038
|
+
/** Current W3C traceparent from the optional hook, or undefined. */
|
|
2039
|
+
private traceparent;
|
|
2040
|
+
private cleanup;
|
|
2041
|
+
private generateRequestId;
|
|
2042
|
+
}
|
|
2043
|
+
//#endregion
|
|
2044
|
+
//#region src/db/types_client_rpc.d.ts
|
|
2045
|
+
interface ErrorMessage {
|
|
2046
|
+
type: "error";
|
|
2047
|
+
id?: string;
|
|
2048
|
+
error: string;
|
|
2049
|
+
code?: string;
|
|
2050
|
+
}
|
|
2051
|
+
declare const AuthMessageSchema: z.ZodObject<{
|
|
2052
|
+
type: z.ZodLiteral<"auth">;
|
|
2053
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
2054
|
+
}, z.core.$strip>;
|
|
2055
|
+
declare const CallMessageSchema: z.ZodObject<{
|
|
2056
|
+
type: z.ZodLiteral<"call">;
|
|
2057
|
+
id: z.ZodString;
|
|
2058
|
+
procedure: z.ZodString;
|
|
2059
|
+
input: z.ZodUnknown;
|
|
2060
|
+
minTs: z.ZodOptional<z.ZodString>;
|
|
2061
|
+
trace: z.ZodOptional<z.ZodString>;
|
|
2062
|
+
}, z.core.$strip>;
|
|
2063
|
+
declare const SubscribeMessageSchema: z.ZodObject<{
|
|
2064
|
+
type: z.ZodLiteral<"subscribe">;
|
|
2065
|
+
id: z.ZodString;
|
|
2066
|
+
procedure: z.ZodString;
|
|
2067
|
+
input: z.ZodUnknown;
|
|
2068
|
+
trace: z.ZodOptional<z.ZodString>;
|
|
2069
|
+
}, z.core.$strip>;
|
|
2070
|
+
declare const UnsubscribeMessageSchema: z.ZodObject<{
|
|
2071
|
+
type: z.ZodLiteral<"unsubscribe">;
|
|
2072
|
+
subId: z.ZodString;
|
|
2073
|
+
}, z.core.$strip>;
|
|
2074
|
+
declare const ClientMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
2075
|
+
type: z.ZodLiteral<"auth">;
|
|
2076
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
2077
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2078
|
+
type: z.ZodLiteral<"call">;
|
|
2079
|
+
id: z.ZodString;
|
|
2080
|
+
procedure: z.ZodString;
|
|
2081
|
+
input: z.ZodUnknown;
|
|
2082
|
+
minTs: z.ZodOptional<z.ZodString>;
|
|
2083
|
+
trace: z.ZodOptional<z.ZodString>;
|
|
2084
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2085
|
+
type: z.ZodLiteral<"subscribe">;
|
|
2086
|
+
id: z.ZodString;
|
|
2087
|
+
procedure: z.ZodString;
|
|
2088
|
+
input: z.ZodUnknown;
|
|
2089
|
+
trace: z.ZodOptional<z.ZodString>;
|
|
2090
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2091
|
+
type: z.ZodLiteral<"unsubscribe">;
|
|
2092
|
+
subId: z.ZodString;
|
|
2093
|
+
}, z.core.$strip>]>;
|
|
2094
|
+
type AuthMessage = z.infer<typeof AuthMessageSchema>;
|
|
2095
|
+
type CallMessage = z.infer<typeof CallMessageSchema>;
|
|
2096
|
+
type SubscribeMessage = z.infer<typeof SubscribeMessageSchema>;
|
|
2097
|
+
type UnsubscribeMessage = z.infer<typeof UnsubscribeMessageSchema>;
|
|
2098
|
+
type ClientMessage = z.infer<typeof ClientMessageSchema>;
|
|
2099
|
+
declare const ConnectedMessageSchema: z.ZodObject<{
|
|
2100
|
+
type: z.ZodLiteral<"connected">;
|
|
2101
|
+
sessionId: z.ZodString;
|
|
2102
|
+
}, z.core.$strip>;
|
|
2103
|
+
declare const AuthSuccessMessageSchema: z.ZodObject<{
|
|
2104
|
+
type: z.ZodLiteral<"auth:success">;
|
|
2105
|
+
userId: z.ZodString;
|
|
2106
|
+
extra: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
|
|
2107
|
+
}, z.core.$strip>;
|
|
2108
|
+
declare const AuthFailedMessageSchema: z.ZodObject<{
|
|
2109
|
+
type: z.ZodLiteral<"auth:failed">;
|
|
2110
|
+
message: z.ZodString;
|
|
2111
|
+
extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
2112
|
+
}, z.core.$strip>;
|
|
2113
|
+
declare const ResponseMessageSchema: z.ZodObject<{
|
|
2114
|
+
type: z.ZodLiteral<"response">;
|
|
2115
|
+
id: z.ZodString;
|
|
2116
|
+
success: z.ZodBoolean;
|
|
2117
|
+
data: z.ZodOptional<z.ZodUnknown>;
|
|
2118
|
+
error: z.ZodOptional<z.ZodString>;
|
|
2119
|
+
code: z.ZodOptional<z.ZodString>;
|
|
2120
|
+
subId: z.ZodOptional<z.ZodString>;
|
|
2121
|
+
ts: z.ZodOptional<z.ZodString>;
|
|
2122
|
+
}, z.core.$strip>;
|
|
2123
|
+
declare const SubscriptionUpdateMessageSchema: z.ZodObject<{
|
|
2124
|
+
type: z.ZodLiteral<"sub:update">;
|
|
2125
|
+
subId: z.ZodString;
|
|
2126
|
+
data: z.ZodUnknown;
|
|
2127
|
+
dataHash: z.ZodOptional<z.ZodString>;
|
|
2128
|
+
ts: z.ZodOptional<z.ZodString>;
|
|
2129
|
+
}, z.core.$strip>;
|
|
2130
|
+
/**
|
|
2131
|
+
* Notifies a client that a subscription is no longer tracked on the server
|
|
2132
|
+
* and will not receive further updates. Sent when, during a sub-manager
|
|
2133
|
+
* recovery cycle, the registration record could not be found (e.g. another
|
|
2134
|
+
* app-server instance fully unregistered the sub while we were disconnected).
|
|
2135
|
+
* The client may choose to re-subscribe or surface the state to the user.
|
|
2136
|
+
*/
|
|
2137
|
+
declare const SubscriptionGoneMessageSchema: z.ZodObject<{
|
|
2138
|
+
type: z.ZodLiteral<"sub:gone">;
|
|
2139
|
+
subId: z.ZodString;
|
|
2140
|
+
reason: z.ZodOptional<z.ZodString>;
|
|
2141
|
+
}, z.core.$strip>;
|
|
2142
|
+
/**
|
|
2143
|
+
* Server-driven liveness signal. Sent when the channel has been idle for
|
|
2144
|
+
* the configured app-ping interval (default 15s) and again after every
|
|
2145
|
+
* outbound message. Pure no-op for the client: receiving any message
|
|
2146
|
+
* (including this one) resets the client's inactivity watchdog. The client
|
|
2147
|
+
* does NOT reply.
|
|
2148
|
+
*/
|
|
2149
|
+
declare const ServerPingMessageSchema: z.ZodObject<{
|
|
2150
|
+
type: z.ZodLiteral<"ping">;
|
|
2151
|
+
}, z.core.$strip>;
|
|
2152
|
+
declare const ServerMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
2153
|
+
type: z.ZodLiteral<"connected">;
|
|
2154
|
+
sessionId: z.ZodString;
|
|
2155
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2156
|
+
type: z.ZodLiteral<"auth:success">;
|
|
2157
|
+
userId: z.ZodString;
|
|
2158
|
+
extra: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
|
|
2159
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2160
|
+
type: z.ZodLiteral<"auth:failed">;
|
|
2161
|
+
message: z.ZodString;
|
|
2162
|
+
extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
2163
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2164
|
+
type: z.ZodLiteral<"response">;
|
|
2165
|
+
id: z.ZodString;
|
|
2166
|
+
success: z.ZodBoolean;
|
|
2167
|
+
data: z.ZodOptional<z.ZodUnknown>;
|
|
2168
|
+
error: z.ZodOptional<z.ZodString>;
|
|
2169
|
+
code: z.ZodOptional<z.ZodString>;
|
|
2170
|
+
subId: z.ZodOptional<z.ZodString>;
|
|
2171
|
+
ts: z.ZodOptional<z.ZodString>;
|
|
2172
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2173
|
+
type: z.ZodLiteral<"sub:update">;
|
|
2174
|
+
subId: z.ZodString;
|
|
2175
|
+
data: z.ZodUnknown;
|
|
2176
|
+
dataHash: z.ZodOptional<z.ZodString>;
|
|
2177
|
+
ts: z.ZodOptional<z.ZodString>;
|
|
2178
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2179
|
+
type: z.ZodLiteral<"sub:gone">;
|
|
2180
|
+
subId: z.ZodString;
|
|
2181
|
+
reason: z.ZodOptional<z.ZodString>;
|
|
2182
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2183
|
+
type: z.ZodLiteral<"ping">;
|
|
2184
|
+
}, z.core.$strip>]>;
|
|
2185
|
+
type ConnectedMessage = z.infer<typeof ConnectedMessageSchema>;
|
|
2186
|
+
type AuthSuccessMessage = z.infer<typeof AuthSuccessMessageSchema>;
|
|
2187
|
+
type AuthFailedMessage = z.infer<typeof AuthFailedMessageSchema>;
|
|
2188
|
+
type ResponseMessage = z.infer<typeof ResponseMessageSchema>;
|
|
2189
|
+
type SubscriptionUpdateMessage = z.infer<typeof SubscriptionUpdateMessageSchema>;
|
|
2190
|
+
type SubscriptionGoneMessage = z.infer<typeof SubscriptionGoneMessageSchema>;
|
|
2191
|
+
type ServerPingMessage = z.infer<typeof ServerPingMessageSchema>;
|
|
2192
|
+
type ServerMessage = z.infer<typeof ServerMessageSchema>;
|
|
2193
|
+
declare class AuthenticationError extends Error {
|
|
2194
|
+
extra: Record<string, unknown>;
|
|
2195
|
+
constructor(message: string, extra?: Record<string, unknown>);
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Helper type to check if a procedure is internal.
|
|
2199
|
+
*/
|
|
2200
|
+
type IsInternal<T> = T extends {
|
|
2201
|
+
internal: infer I;
|
|
2202
|
+
} ? (I extends true ? true : false) : false;
|
|
2203
|
+
interface Context$1 {
|
|
2204
|
+
requestId: string;
|
|
2205
|
+
/** Authenticated user info */
|
|
2206
|
+
user: {
|
|
2207
|
+
userId: string;
|
|
2208
|
+
};
|
|
2209
|
+
}
|
|
2210
|
+
//#endregion
|
|
2211
|
+
//#region src/client/client.d.ts
|
|
2212
|
+
interface ClientOptions {
|
|
2213
|
+
/** WebSocket URL (e.g. ws://localhost:3000/ws) */
|
|
2214
|
+
url: string;
|
|
2215
|
+
/** Auth Info callback */
|
|
2216
|
+
token?: () => Promise<string>;
|
|
2217
|
+
/** Optional: reconnection timeout in ms (default: 180000 = 3 minutes) */
|
|
2218
|
+
reconnectionTimeout?: number;
|
|
2219
|
+
/** Reconnection options */
|
|
2220
|
+
reconnect?: WSClientOptions["reconnect"];
|
|
2221
|
+
/**
|
|
2222
|
+
* Inactivity watchdog. The client never sends a ping itself; the server
|
|
2223
|
+
* emits `{type:"ping"}` while idle and we close+reconnect if no inbound
|
|
2224
|
+
* message arrives within `serverInactivityMs` (default 60s).
|
|
2225
|
+
*/
|
|
2226
|
+
heartbeat?: WSClientOptions["heartbeat"];
|
|
2227
|
+
/**
|
|
2228
|
+
* Yields the event loop for `delayMs` after every `everyN` `call()`
|
|
2229
|
+
* invocations. Useful for keeping React renders / GC tasks scheduled
|
|
2230
|
+
* during long synchronous bursts; not load-bearing for the heartbeat.
|
|
2231
|
+
* Default `{ everyN: 100, delayMs: 10 }`. Set `everyN: 0` to disable.
|
|
2232
|
+
*/
|
|
2233
|
+
throttle?: WSClientOptions["throttle"];
|
|
2234
|
+
/** Custom log sink; when set, `logLevel` is ignored. See {@link WSClientOptions.logger}. */
|
|
2235
|
+
logger?: WSClientOptions["logger"];
|
|
2236
|
+
/** Level for the default console logger. Default `"warn"` (quiet). */
|
|
2237
|
+
logLevel?: WSClientOptions["logLevel"];
|
|
2238
|
+
/** Optional structured lifecycle events, for client-side metrics. */
|
|
2239
|
+
onEvent?: WSClientOptions["onEvent"];
|
|
2240
|
+
/** OpenTelemetry-agnostic W3C `traceparent` provider; see {@link WSClientOptions.getTraceparent}. */
|
|
2241
|
+
getTraceparent?: WSClientOptions["getTraceparent"];
|
|
2242
|
+
onConnect?: () => void;
|
|
2243
|
+
onDisConnect?: () => void;
|
|
2244
|
+
}
|
|
2245
|
+
/**
|
|
2246
|
+
* Public state of a live query subscription, exposed via `getState()` and
|
|
2247
|
+
* `onState()` on the handle so React (or any UI) can render a consistent
|
|
2248
|
+
* snapshot via `useSyncExternalStore`.
|
|
2249
|
+
*
|
|
2250
|
+
* - "connecting" — initial subscribe in flight
|
|
2251
|
+
* - "success" — subscribed, last server data is in `data`
|
|
2252
|
+
* - "stale" — was successful, transport dropped; keeping last `data`
|
|
2253
|
+
* until the resubscribe completes
|
|
2254
|
+
* - "loading" — `refetch()` triggered an explicit re-subscribe
|
|
2255
|
+
* - "error" — subscribe failed or server sent `sub:gone`
|
|
2256
|
+
*/
|
|
2257
|
+
type LiveQueryStatus = "connecting" | "success" | "stale" | "loading" | "error";
|
|
2258
|
+
interface LiveQueryState<T> {
|
|
2259
|
+
data: T | undefined;
|
|
2260
|
+
status: LiveQueryStatus;
|
|
2261
|
+
error: Error | null;
|
|
2262
|
+
}
|
|
2263
|
+
interface LiveQueryHandle<T> {
|
|
2264
|
+
/** Get current cached data (legacy convenience getter). */
|
|
2265
|
+
get(): T | undefined;
|
|
2266
|
+
/** Snapshot of `{ data, status, error }`. Stable between updates. */
|
|
2267
|
+
getState(): LiveQueryState<T>;
|
|
2268
|
+
/**
|
|
2269
|
+
* Listen for state changes (data, status or error). Returns an
|
|
2270
|
+
* unsubscribe function that removes only this listener — the underlying
|
|
2271
|
+
* server subscription stays alive as long as any listener is attached.
|
|
2272
|
+
*
|
|
2273
|
+
* Suitable for `useSyncExternalStore`.
|
|
2274
|
+
*/
|
|
2275
|
+
onState(listener: () => void): () => void;
|
|
2276
|
+
/** Listen for data-only changes. Returns listener-removal fn. */
|
|
2277
|
+
onData(callback: (data: T) => void): () => void;
|
|
2278
|
+
/** Force a re-subscribe round-trip. */
|
|
2279
|
+
refetch(): void;
|
|
2280
|
+
/** Unsubscribe from the server (drops listeners too). */
|
|
2281
|
+
unsubscribe(): void;
|
|
2282
|
+
}
|
|
2283
|
+
/**
|
|
2284
|
+
* Create a fully typed RPC client with WebSocket transport.
|
|
2285
|
+
*/
|
|
2286
|
+
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;
|
|
2287
|
+
/**
|
|
2288
|
+
* WebSocket client methods.
|
|
2289
|
+
*/
|
|
2290
|
+
interface WSClientMethods {
|
|
2291
|
+
/** Connect to the WebSocket server */
|
|
2292
|
+
connect(): Promise<void>;
|
|
2293
|
+
/** Disconnect from the server */
|
|
2294
|
+
disconnect(): void;
|
|
2295
|
+
/** Check if connected and authenticated */
|
|
2296
|
+
isReady(): boolean;
|
|
2297
|
+
/** Check if authenticated */
|
|
2298
|
+
isAuthenticated(): boolean;
|
|
2299
|
+
/** Check if anonymouse */
|
|
2300
|
+
isAnonymouse(): boolean;
|
|
2301
|
+
/**
|
|
2302
|
+
* The authenticated user id reported by the server on `auth:success`, or
|
|
2303
|
+
* null when anonymous/unauthenticated. This is the auth-tier identity,
|
|
2304
|
+
* NOT the server-side `queryIdentity` (which is the cache/subscription
|
|
2305
|
+
* segmentation key and is not exposed to the client).
|
|
2306
|
+
*/
|
|
2307
|
+
getAuthUserId(): string | null;
|
|
2308
|
+
/** Subscribe to client connection state transitions. Returns unsubscribe fn. */
|
|
2309
|
+
onState(listener: (s: ClientPublicState) => void): () => void;
|
|
2310
|
+
/** Snapshot of the current public state. */
|
|
2311
|
+
getPublicState(): ClientPublicState;
|
|
2312
|
+
}
|
|
2313
|
+
/**
|
|
2314
|
+
* Client type from procedures.
|
|
2315
|
+
* Filters internal procedures and creates appropriate methods.
|
|
2316
|
+
* Query procedures get an additional liveQuery() method for real-time subscriptions.
|
|
2317
|
+
*/
|
|
2318
|
+
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 {
|
|
2319
|
+
procedureType: "query";
|
|
2320
|
+
} ? {
|
|
2321
|
+
query: (input: InputOf<TProcedures[K]>) => Promise<OutputOf<TProcedures[K]>>;
|
|
2322
|
+
liveQuery: (input: InputOf<TProcedures[K]>) => LiveQueryHandle<OutputOf<TProcedures[K]>>;
|
|
2323
|
+
} : TProcedures[K] extends {
|
|
2324
|
+
procedureType: "mutation";
|
|
2325
|
+
} ? {
|
|
2326
|
+
mutate: (input: InputOf<TProcedures[K]>, opts?: CallOptions) => Promise<OutputOf<TProcedures[K]>>;
|
|
2327
|
+
} : TProcedures[K] extends {
|
|
2328
|
+
procedureType: "action";
|
|
2329
|
+
} ? {
|
|
2330
|
+
action: (input: InputOf<TProcedures[K]>, opts?: CallOptions) => Promise<OutputOf<TProcedures[K]>>;
|
|
2331
|
+
} : never };
|
|
2332
|
+
/**
|
|
2333
|
+
* Optional call options forwarded to the transport layer.
|
|
2334
|
+
*/
|
|
2335
|
+
interface CallOptions {
|
|
2336
|
+
/**
|
|
2337
|
+
* Fired the first time the request leaves the queue and is actually
|
|
2338
|
+
* sent on the wire. If the call was already sent immediately (client
|
|
2339
|
+
* was ready at call time), this is invoked synchronously.
|
|
2340
|
+
*
|
|
2341
|
+
* Used by `useMutation` to flip `state` from "queued" → "loading".
|
|
2342
|
+
*/
|
|
2343
|
+
onSend?: () => void;
|
|
2344
|
+
}
|
|
2345
|
+
//#endregion
|
|
2346
|
+
//#region src/client/caller_client.d.ts
|
|
2347
|
+
interface CallerOptions<TContext = unknown> {
|
|
2348
|
+
isInternal?: boolean;
|
|
2349
|
+
inContext: string;
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Create a server-side caller that bypasses HTTP/WebSocket.
|
|
2353
|
+
*
|
|
2354
|
+
* For in-memory calls, input validation is skipped (data is already a JS object).
|
|
2355
|
+
* Query procedures also get a liveQuery() method for server-side use.
|
|
2356
|
+
*/
|
|
2357
|
+
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>;
|
|
2358
|
+
/**
|
|
2359
|
+
* Caller type from procedures (includes internal procedures).
|
|
2360
|
+
* Query procedures also have liveQuery() for server-side use.
|
|
2361
|
+
*/
|
|
2362
|
+
type CallerFromProcedures<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = { [K in keyof TProcedures]: TProcedures[K] extends {
|
|
2363
|
+
procedureType: "query";
|
|
2364
|
+
} ? {
|
|
2365
|
+
query: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
|
|
2366
|
+
liveQuery: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<LiveResult<OutputOf<TProcedures[K]>>>;
|
|
2367
|
+
runQuery: (input: InputOf<TProcedures[K]>, ctx: ParentCtx<TContext>) => Promise<OutputOf<TProcedures[K]>>;
|
|
2368
|
+
} : TProcedures[K] extends {
|
|
2369
|
+
procedureType: "mutation";
|
|
2370
|
+
} ? {
|
|
2371
|
+
mutate: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
|
|
2372
|
+
runMutation: (input: InputOf<TProcedures[K]>, ctx: ParentCtx<TContext>) => Promise<OutputOf<TProcedures[K]>>;
|
|
2373
|
+
} : TProcedures[K] extends {
|
|
2374
|
+
procedureType: "action";
|
|
2375
|
+
} ? {
|
|
2376
|
+
action: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
|
|
2377
|
+
} : TProcedures[K] extends {
|
|
2378
|
+
procedureType: "job";
|
|
2379
|
+
} ? {
|
|
2380
|
+
run: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
|
|
2381
|
+
} : never } & {
|
|
2382
|
+
init: (config: CallerClientInitConfig) => Promise<void>;
|
|
2383
|
+
};
|
|
2384
|
+
type CallerClientInitConfig = {
|
|
2385
|
+
db: SupaliveDb;
|
|
2386
|
+
storage: ObjectStorage;
|
|
2387
|
+
scheduler: JobClient;
|
|
2388
|
+
/**
|
|
2389
|
+
* Observability so standalone internal calls log under the configured logger
|
|
2390
|
+
* (a per-procedure child). Required — a caller with no running server (e.g. a
|
|
2391
|
+
* CLI seed) passes a console-backed shim. Nested runQuery/runMutation always
|
|
2392
|
+
* inherit the parent handler's log instead.
|
|
2393
|
+
*/
|
|
2394
|
+
obs: CallerObservability;
|
|
2395
|
+
};
|
|
2396
|
+
/**
|
|
2397
|
+
* Caller type from router.
|
|
2398
|
+
*/
|
|
2399
|
+
type CallerFromRouter<TRouter extends Router<any, any>> = CallerFromProcedures<TRouter["procedures"]>;
|
|
2400
|
+
//#endregion
|
|
2401
|
+
export { ActionProcedures as $, RawClient as $n, RawReadEntry as $r, ResultOf as $t, ResponseMessage as A, MutationArgs as An, LeafPredicateSchema as Ar, QueryFn as At, SubscriptionUpdateMessage as B, StoredSchemaColumnsOptions as Bn, Predicate as Br, IncomingJobRequest as Bt, ClientMessage as C, ComputedFieldConfig as Cn, CachedPgMetadataSchema as Cr, MutationConfig as Ct, Context$1 as D, InferSchema as Dn, CompareOperatorSchema as Dr, OutputOf as Dt, ConnectedMessageSchema as E, IndexDefinition as En, CompareOperator as Er, MutationProcedure as Et, ServerPingMessageSchema as F, ReturnQuery as Fn, OccConflictError as Fr, createMutationBuilder as Ft, ClientLogLevel as G, tableNameToId as Gn, QueryCacheMetadataSchema as Gr, ScheduleHandle as Gt, UnsubscribeMessage as H, defineSchema as Hn, QueryCacheEntry as Hr, JobScheduler as Ht, SubscribeMessage as I, SchemaCodecs as In, OrPredicate as Ir, createQueryBuilder as It, HeartbeatOptions as J, DbQueryResult as Jn, RangeReadSchema as Jr, sleep as Jt, ClientLogger as K, CoreInitLockCtx as Kn, QuerySpec as Kr, ScheduledJobDef as Kt, SubscribeMessageSchema as L, SchemaColumnMapping as Ln, OrPredicateSchema as Lr, DevScheduler as Lt, ServerMessage as M, Prettify as Mn, MutationResult as Mr, TypeOf as Mt, ServerMessageSchema as N, QueryArgs as Nn, NO_RETRY as Nr, createActionBuilder as Nt, ErrorMessage as O, InsertData as On, DEFAULT_RETRY as Or, QueryConfig as Ot, ServerPingMessage as P, ReturnLiveQuery as Pn, OccAbortError as Pr, createJobBuilder as Pt, createConsoleLogger as Q, PreparedQueries as Qn, RawRangeReadSchema as Qr, QueryDefinition as Qt, SubscriptionGoneMessage as R, SchemaColumnsOptions as Rn, PointRead as Rr, DevSchedulerOptions as Rt, CallMessageSchema as S, ComputedField as Sn, CachedPgMetadata as Sr, JobProcedure as St, ConnectedMessage as T, DefineSchemaConfig as Tn, CommitTs as Tr, MutationFn as Tt, UnsubscribeMessageSchema as U, schemaRegistry as Un, QueryCacheEntrySchema as Ur, QStashScheduler as Ut, SubscriptionUpdateMessageSchema as V, defineComputedField as Vn, PredicateSchema as Vr, JobClient as Vt, ClientEvent as W, shouldTrackSchema as Wn, QueryCacheMetadata as Wr, QStashSchedulerOptions as Wt, WSClientOptions as X, LazyCommitTsParam as Xn, RawPointReadSchema as Xr, DefsToMap as Xt, RPCError as Y, DbType as Yn, RawPointRead as Yr, AnyQueryDef as Yt, WsClientManager as Z, PooledClient as Zn, RawRangeRead as Zr, ParamsOf as Zt, AuthMessageSchema as _, matchesPredicate as _n, UpdateSubscriptionReadSetParamsSchema as _r, HandlerLogger as _t, createCaller as a, WriteEntrySchema as ai, IdAndCommitTs as an, InvalidateWritesetParams as ar, PublicProcedures as at, AuthenticationError as b, ComputedCodec as bn, AndPredicateSchema as br, JobCtx as bt, ClientOptions as c, bytesFromJson as ci, JsonOpOptions as cn, RegisterSubscriptionParams as cr, Router as ct, LiveQueryStatus as d, PaginationClause as dn, UnregisterSubscriptionParams as dr, ActionConfig as dt, RawReadEntrySchema as ei, _resetGlobalDefs as en, SqlBuilder as er, AppRouter as et, WSClientMethods as f, QueryBuilder as fn, UnregisterSubscriptionParamsSchema as fr, ActionCtx as ft, AuthMessage as g, jsonPathExtract as gn, UpdateSubscriptionReadSetParams as gr, ContextOf as gt, AuthFailedMessageSchema as h, jsonPathExists as hn, UnregisterSubscriptionsResult as hr, AnyProcedure as ht, CallerOptions as i, WriteEntry as ii, TxContext as in, AffectedSubscription as ir, ProcedureNames as it, ResponseMessageSchema as j, OverrideField as jn, LiveResult as jr, QueryProcedure as jt, IsInternal as k, Model as kn, LeafPredicate as kr, QueryCtx as kt, LiveQueryHandle as l, normalizeIdToBytes as li, OrderByOptions as ln, RegisterSubscriptionParamsSchema as lr, getContextRegistry as lt, AuthFailedMessage as m, jsonContains as mn, UnregisterSubscriptionsParams as mr, ActionProcedure as mt, CallerFromProcedures as n, ReadEntrySchema as ni, DbReader as nn, CacheLayer as nr, JobProcedures as nt, CallOptions as o, WriteOp as oi, JsonContainsOptions as on, InvalidateWritesetParamsSchema as or, QueryProcedures as ot, createClient as p, buildPredicateSql as pn, UnregisterSubscriptionResult as pr, ActionFn as pt, ClientPublicState as q, Database as qn, RangeRead as qr, SupaliveDb as qt, CallerFromRouter as r, RetryConfig as ri, DbWriter as rn, RedisClient as rr, MutationProcedures as rt, ClientFromProcedures as s, WriteOpSchema as si, JsonHasKeyMultiOptions as sn, InvalidateWritesetResult as sr, RegisteredProcedure as st, CallerClientInitConfig as t, ReadEntry as ti, defineQuery as tn, TxDatabase as tr, ContextRegistry as tt, LiveQueryState as u, normalizeToBytes as ui, OrderDirection as un, RegisterSubscriptionResult as ur, router as ut, AuthSuccessMessage as v, ActionArgs as vn, UpdateSubscriptionReadSetResult as vr, HandlerObservability as vt, ClientMessageSchema as w, DeclarativeIndex as wn, CommitLogEntry as wr, MutationCtx as wt, CallMessage as x, ComputedDataType as xn, BigIntSchema as xr, JobFn as xt, AuthSuccessMessageSchema as y, ColumnCodec as yn, AndPredicate as yr, JobConfig as yt, SubscriptionGoneMessageSchema as z, SchemaDefinition as zn, PointReadSchema as zr, EnqueueOptions as zt };
|
|
2402
|
+
//# sourceMappingURL=index-B3i2G1gr.d.ts.map
|