@supalive/core 1.15.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/index-B4UxN1ZL.d.ts +2365 -0
  2. package/dist/index-B4UxN1ZL.d.ts.map +1 -0
  3. package/dist/index-B8JFAyw4.d.ts +2377 -0
  4. package/dist/index-B8JFAyw4.d.ts.map +1 -0
  5. package/dist/index-CfcrWLLm.d.ts +2377 -0
  6. package/dist/index-CfcrWLLm.d.ts.map +1 -0
  7. package/dist/index-ggi1DrSG.d.ts +2336 -0
  8. package/dist/index-ggi1DrSG.d.ts.map +1 -0
  9. package/dist/mysql-07ROfbBZ.d.ts +114 -0
  10. package/dist/mysql-07ROfbBZ.d.ts.map +1 -0
  11. package/dist/mysql-BTigT6mP.d.ts +114 -0
  12. package/dist/mysql-BTigT6mP.d.ts.map +1 -0
  13. package/dist/mysql-CXymz1Eu.d.ts +114 -0
  14. package/dist/mysql-CXymz1Eu.d.ts.map +1 -0
  15. package/dist/mysql-ClUK7S2j.js +623 -0
  16. package/dist/mysql-ClUK7S2j.js.map +1 -0
  17. package/dist/mysql-CtpWqOhO.d.ts +114 -0
  18. package/dist/mysql-CtpWqOhO.d.ts.map +1 -0
  19. package/dist/mysql-fTKZ1zaF.js +623 -0
  20. package/dist/mysql-fTKZ1zaF.js.map +1 -0
  21. package/dist/overlap-checker-1TwhkAwy.js +259 -0
  22. package/dist/overlap-checker-1TwhkAwy.js.map +1 -0
  23. package/dist/overlap-checker-CGlxWcyb.js +259 -0
  24. package/dist/overlap-checker-CGlxWcyb.js.map +1 -0
  25. package/dist/postgres-B5-5vgLJ.d.ts +118 -0
  26. package/dist/postgres-B5-5vgLJ.d.ts.map +1 -0
  27. package/dist/postgres-CN03Espg.js +868 -0
  28. package/dist/postgres-CN03Espg.js.map +1 -0
  29. package/dist/postgres-CRPJdZx2.js +868 -0
  30. package/dist/postgres-CRPJdZx2.js.map +1 -0
  31. package/dist/postgres-DCXnKaJr.d.ts +118 -0
  32. package/dist/postgres-DCXnKaJr.d.ts.map +1 -0
  33. package/dist/postgres-DgCYPf0j.d.ts +118 -0
  34. package/dist/postgres-DgCYPf0j.d.ts.map +1 -0
  35. package/dist/postgres-Dnshux6k.d.ts +118 -0
  36. package/dist/postgres-Dnshux6k.d.ts.map +1 -0
  37. package/dist/query-LJranz0c.js +795 -0
  38. package/dist/query-LJranz0c.js.map +1 -0
  39. package/dist/query-q1ZvKrZO.js +762 -0
  40. package/dist/query-q1ZvKrZO.js.map +1 -0
  41. package/dist/realtime_db-B0Tin87E.js +312 -0
  42. package/dist/realtime_db-B0Tin87E.js.map +1 -0
  43. package/dist/realtime_db-DVhhasJj.js +312 -0
  44. package/dist/realtime_db-DVhhasJj.js.map +1 -0
  45. package/dist/router-DP2ThAwh.js.map +1 -1
  46. package/dist/src/client/index.d.ts +2 -2
  47. package/dist/src/client/index.js +78 -16
  48. package/dist/src/client/index.js.map +1 -1
  49. package/dist/src/exports/mysql.d.ts +1 -1
  50. package/dist/src/exports/mysql.js +1 -1
  51. package/dist/src/exports/postgres.d.ts +1 -1
  52. package/dist/src/exports/postgres.js +1 -1
  53. package/dist/src/exports/procedure.d.ts +2 -2
  54. package/dist/src/exports/procedure.js +1 -1
  55. package/dist/src/exports/schema-sql.d.ts +1 -1
  56. package/dist/src/exports/server.d.ts +12 -6
  57. package/dist/src/exports/server.d.ts.map +1 -1
  58. package/dist/src/exports/server.js +792 -252
  59. package/dist/src/exports/server.js.map +1 -1
  60. package/dist/src/exports/sub-manager-worker-entry.js +1 -1
  61. package/dist/src/exports/types.d.ts +2 -2
  62. package/dist/src/exports/types.js +1 -1
  63. package/dist/sub-worker-dispatch-D7jfw6ys.js +826 -0
  64. package/dist/sub-worker-dispatch-D7jfw6ys.js.map +1 -0
  65. package/dist/sub-worker-dispatch-qiSs5Xkm.js +826 -0
  66. package/dist/sub-worker-dispatch-qiSs5Xkm.js.map +1 -0
  67. package/dist/types_client_rpc-CWZmlWmM.js +145 -0
  68. package/dist/types_client_rpc-CWZmlWmM.js.map +1 -0
  69. package/dist/types_client_rpc-D4td5W0Y.js +141 -0
  70. package/dist/types_client_rpc-D4td5W0Y.js.map +1 -0
  71. package/dist/types_server-BhC19R2a.js.map +1 -1
  72. package/dist/types_server-BmIgDd8d.d.ts +614 -0
  73. package/dist/types_server-BmIgDd8d.d.ts.map +1 -0
  74. package/dist/types_server-C6B9_b1R.d.ts +662 -0
  75. package/dist/types_server-C6B9_b1R.d.ts.map +1 -0
  76. package/dist/types_server-DRr5yKy1.d.ts +655 -0
  77. package/dist/types_server-DRr5yKy1.d.ts.map +1 -0
  78. package/dist/types_server-DmCbve3w.d.ts +684 -0
  79. package/dist/types_server-DmCbve3w.d.ts.map +1 -0
  80. package/dist/types_server-Gs_vSVaS.d.ts +655 -0
  81. package/dist/types_server-Gs_vSVaS.d.ts.map +1 -0
  82. package/dist/types_server-ILUmPFvk.d.ts +614 -0
  83. package/dist/types_server-ILUmPFvk.d.ts.map +1 -0
  84. package/package.json +2 -1
@@ -0,0 +1,312 @@
1
+ import { a as unwrapZodType, i as normalizeCodec } from "./table-id-DyrJBKAQ.js";
2
+ import { s as traceDbCall, t as QueryBuilder } from "./query-q1ZvKrZO.js";
3
+ import { r as LazyCommitTsParam } from "./db-ClCicssQ.js";
4
+ import { l as OccConflictError } from "./types_db-OUou3o2Z.js";
5
+ import { z as z$1 } from "zod";
6
+ import { ExponentialBackoff, handleWhen, retry } from "cockatiel";
7
+ //#region src/db/context.ts
8
+ /**
9
+ * Materialize a schema's runtime {@link Model}: column-name mapping, per-column
10
+ * coarse type tags, and the codec used to (de)serialize each column.
11
+ *
12
+ * Codecs are resolved via {@link normalizeCodec}, which supplies a sensible
13
+ * default per Zod type (e.g. a {@link dateCodec} for `z.date()`, so `Date`
14
+ * columns round-trip automatically) while letting a user-supplied codec in
15
+ * `schema.columnsOptions.codecs` override it — partially or fully.
16
+ */
17
+ function buildModel(schema) {
18
+ const shape = schema.schema.shape;
19
+ const customColumns = schema.columns;
20
+ const columns = {};
21
+ const types = {};
22
+ const codecs = {};
23
+ const schemaCodecs = schema.columnsOptions.codecs ?? {};
24
+ for (const key of Object.keys(shape)) {
25
+ columns[key] = customColumns?.[key] ?? key;
26
+ const field = shape[key];
27
+ const baseField = unwrapZodType(field);
28
+ if (baseField instanceof z$1.ZodNumber) types[key] = "integer";
29
+ else if (baseField instanceof z$1.ZodString) types[key] = "string";
30
+ else if (baseField instanceof z$1.ZodBoolean) types[key] = "boolean";
31
+ else if (baseField instanceof z$1.ZodDate) types[key] = "date";
32
+ else if (baseField instanceof z$1.ZodArray) types[key] = "array";
33
+ else types[key] = "json";
34
+ codecs[key] = normalizeCodec(schemaCodecs[key], baseField);
35
+ }
36
+ return {
37
+ table: schema.table,
38
+ tableId: schema.tableId,
39
+ columns,
40
+ reverseColumns: Object.fromEntries(Object.entries(columns).map(([k, v]) => [v, k])),
41
+ types,
42
+ codecs
43
+ };
44
+ }
45
+ var TxContext = class {
46
+ beginTs;
47
+ db;
48
+ readSet = [];
49
+ writeSet = [];
50
+ models = /* @__PURE__ */ new Map();
51
+ getOrCreateModel(schema) {
52
+ const existing = this.models.get(schema.table);
53
+ if (existing) return existing;
54
+ const model = buildModel(schema);
55
+ this.models.set(schema.table, model);
56
+ return model;
57
+ }
58
+ constructor(db, beginTs) {
59
+ this.db = db;
60
+ this.beginTs = beginTs;
61
+ }
62
+ /**
63
+ * Rebind the read connection (and its snapshot ts). Used by the replica
64
+ * router when a query handler calls `ctx.usePrimaryConn()`/`useReplicaConn()`.
65
+ * Must be called BEFORE any read — the readSet/beginTs would otherwise mix
66
+ * snapshots — so this throws if a read or write has already happened.
67
+ */
68
+ useConnection(db, beginTs) {
69
+ if (this.readSet.length > 0 || this.writeSet.length > 0) throw new Error("useConnection()/usePrimaryConn()/useReplicaConn() must be called before any read or write in the handler");
70
+ this.db = db;
71
+ this.beginTs = beginTs;
72
+ }
73
+ internalGetReadSet() {
74
+ return this.readSet;
75
+ }
76
+ internalGetWriteSet() {
77
+ return this.writeSet;
78
+ }
79
+ /**
80
+ * Merge a parent procedure's reads into this context's readSet. Used when a
81
+ * `runMutation` sub-transaction inherits the reads of the procedure that
82
+ * invoked it, so the sub-tx's OCC validation also fences on those rows.
83
+ * Entries are shallow-cloned so the two readSets don't alias.
84
+ */
85
+ appendInternalReadSet(parentEntries) {
86
+ this.readSet.push(...parentEntries.map((e) => ({ ...e })));
87
+ }
88
+ findPendingWrite(table, id) {
89
+ return this.writeSet.find((w) => w.table === table && w.id === id);
90
+ }
91
+ findPendingInsert(table, id) {
92
+ return this.writeSet.find((w) => w.table === table && w.id === id && w.op === "insert");
93
+ }
94
+ encodeWithCodec(model, property, value) {
95
+ const codec = model.codecs[property];
96
+ if (!codec?.encode || value === void 0 || value === null) return value;
97
+ return codec.encode(value);
98
+ }
99
+ };
100
+ var DbReader = class extends TxContext {
101
+ query(schema) {
102
+ const model = this.getOrCreateModel(schema);
103
+ return new QueryBuilder(this, model);
104
+ }
105
+ };
106
+ var DbWriter = class extends DbReader {
107
+ async insert(schema, id, data) {
108
+ const model = this.getOrCreateModel(schema);
109
+ const mappedData = { id };
110
+ const shape = schema.schema.shape;
111
+ for (const key of Object.keys(shape)) {
112
+ let value = data[key];
113
+ if (value === void 0) {
114
+ const field = shape[key];
115
+ if (field instanceof z$1.ZodDefault) {
116
+ const defaultVal = field.def.defaultValue;
117
+ value = typeof defaultVal === "function" ? defaultVal() : defaultVal;
118
+ if (value !== void 0) {
119
+ const columnName = model.columns[key] ?? key;
120
+ mappedData[columnName] = this.encodeWithCodec(model, key, value);
121
+ }
122
+ }
123
+ } else {
124
+ const columnName = model.columns[key] ?? key;
125
+ mappedData[columnName] = this.encodeWithCodec(model, key, value);
126
+ }
127
+ }
128
+ mappedData["id"] = id;
129
+ const existing = this.findPendingWrite(schema.table, id);
130
+ if (existing) if (existing.op === "delete") {
131
+ existing.op = "update";
132
+ existing.data = mappedData;
133
+ } else existing.data = {
134
+ ...existing.data,
135
+ ...mappedData
136
+ };
137
+ else this.writeSet.push({
138
+ table: schema.table,
139
+ tableId: schema.tableId,
140
+ id,
141
+ op: "insert",
142
+ data: mappedData
143
+ });
144
+ }
145
+ async update(schema, id, data) {
146
+ const model = this.getOrCreateModel(schema);
147
+ const mappedData = {};
148
+ for (const [key, value] of Object.entries(data)) {
149
+ const columnName = model.columns[key] ?? key;
150
+ mappedData[columnName] = this.encodeWithCodec(model, key, value);
151
+ }
152
+ const existing = this.findPendingWrite(schema.table, id);
153
+ if (existing) {
154
+ existing.op = existing.op === "insert" ? "insert" : "update";
155
+ existing.data = {
156
+ ...existing.data,
157
+ ...mappedData
158
+ };
159
+ } else this.writeSet.push({
160
+ table: schema.table,
161
+ tableId: schema.tableId,
162
+ id,
163
+ op: "update",
164
+ data: mappedData
165
+ });
166
+ }
167
+ async delete(schema, id) {
168
+ const existingInsert = this.findPendingInsert(schema.table, id);
169
+ if (existingInsert) {
170
+ this.writeSet = this.writeSet.filter((w) => w !== existingInsert);
171
+ return;
172
+ }
173
+ this.writeSet.push({
174
+ table: schema.table,
175
+ tableId: schema.tableId,
176
+ id,
177
+ op: "delete"
178
+ });
179
+ }
180
+ };
181
+ //#endregion
182
+ //#region src/db/realtime_db.ts
183
+ const occRetryPolicy = retry(handleWhen((err) => OccConflictError.isOccConflictError(err)), {
184
+ maxAttempts: 15,
185
+ backoff: new ExponentialBackoff({
186
+ initialDelay: 10,
187
+ maxDelay: 7e3,
188
+ exponent: 2
189
+ })
190
+ });
191
+ const getDbclientRetryPolicy = retry(handleWhen((err) => err.message.includes("timeout exceeded")), {
192
+ maxAttempts: 3,
193
+ backoff: new ExponentialBackoff({
194
+ initialDelay: 500,
195
+ maxDelay: 2e3,
196
+ exponent: 2
197
+ })
198
+ });
199
+ var SupaliveDb = class SupaliveDb {
200
+ impl;
201
+ replica;
202
+ /**
203
+ * @param impl the PRIMARY (writer) connection — all mutations, the OCC
204
+ * commit-ts source, and cache-freshness commit-log scans run here.
205
+ * @param replica optional read replica for query/action reads (see the
206
+ * routing in one-shot-query.ts). Undefined → reads use primary.
207
+ */
208
+ constructor(impl, replica) {
209
+ this.impl = impl;
210
+ this.replica = replica;
211
+ }
212
+ static create(config) {
213
+ return new SupaliveDb(config.db, config.replica ? new SupaliveDb(config.replica) : void 0);
214
+ }
215
+ /** True when a distinct read replica is configured. */
216
+ get hasReplica() {
217
+ return this.replica !== void 0;
218
+ }
219
+ onAfterCommit;
220
+ /**
221
+ * Register a hook fired once after every successful `mutation()` commit
222
+ * (never on an OCC conflict/rollback), with the committed writeSet and its
223
+ * commitTs. The server uses this to drive subscription invalidation for ALL
224
+ * mutation sources — client WS calls, actions, jobs, and the internal caller —
225
+ * so a server-side write pushes live updates just like a client write does.
226
+ * Non-server consumers (migration tooling, tests) leave it unset (no-op).
227
+ */
228
+ setOnAfterCommit(cb) {
229
+ this.onAfterCommit = cb;
230
+ }
231
+ /**
232
+ * One-shot read against an EXPLICIT connection + snapshot ts (rather than this
233
+ * db's own latest). Used by the replica router: the caller pre-resolves the
234
+ * default read connection (replica for queries) and hands the handler a
235
+ * `DbReader` it can rebind via `useConnection` (ctx.usePrimaryConn/…). The
236
+ * returned `ts` is the FINAL bound connection's snapshot, so the cache entry is
237
+ * stamped with the ts actually read at.
238
+ */
239
+ async queryInternalOn(read, fn) {
240
+ const ctx = new DbReader(read.impl, read.beginTs);
241
+ const data = await fn(ctx);
242
+ return {
243
+ ts: ctx.beginTs,
244
+ data,
245
+ readSet: ctx.internalGetReadSet()
246
+ };
247
+ }
248
+ async query(fn) {
249
+ const beginTs = await this.impl.getLatestSnapshotTimestamp();
250
+ return await fn(new DbReader(this.impl, beginTs));
251
+ }
252
+ /**
253
+ * Compute a query once at the latest snapshot, returning the result together
254
+ * with the snapshot `ts` and the tracked `readSet`. This is a plain one-shot
255
+ * evaluation — it registers NO live subscription; the `readSet`/`ts` are
256
+ * returned purely so the caller (e.g. the one-shot query cache) can store
257
+ * freshness metadata. Use this for cached one-shot query calls (WS `call`,
258
+ * HTTP RPC). `liveQuery` is the same computation under the subscription path's
259
+ * name and simply delegates here.
260
+ */
261
+ async queryInternal(fn) {
262
+ const beginTs = await this.impl.getLatestSnapshotTimestamp();
263
+ const ctx = new DbReader(this.impl, beginTs);
264
+ return {
265
+ ts: beginTs,
266
+ data: await fn(ctx),
267
+ readSet: ctx.internalGetReadSet()
268
+ };
269
+ }
270
+ async liveQuery(fn) {
271
+ return this.queryInternal(fn);
272
+ }
273
+ async mutation(fn, retryPolicy = occRetryPolicy) {
274
+ return await retryPolicy.execute(async (p) => {
275
+ let db;
276
+ try {
277
+ const beginTs = await this.impl.getLatestSnapshotTimestamp() + 1n;
278
+ const ctx = new DbWriter(this.impl, beginTs);
279
+ const result = await fn(ctx);
280
+ const readSet = ctx.internalGetReadSet();
281
+ const writeSet = ctx.internalGetWriteSet();
282
+ const commitTsLazy = new LazyCommitTsParam(void 0);
283
+ await this.impl.attachPrevDataToWriteSet(writeSet, readSet);
284
+ const queries = await this.impl.prepareCommitWrites(readSet, writeSet, commitTsLazy);
285
+ db = await getDbclientRetryPolicy.execute(() => this.impl.getTransactionClient());
286
+ await db.begin();
287
+ const commitTs = await db.getNextTimestamp();
288
+ commitTsLazy.value = commitTs;
289
+ const commitResult = await traceDbCall("commit", "", this.impl.dbType, () => db.commitWrites(beginTs, queries, commitTs));
290
+ if (!commitResult.success) throw new OccConflictError("Commit failed", { commitResult });
291
+ await db.updateLatestSnapshotTimestamp(commitTs);
292
+ await db.commit();
293
+ this.onAfterCommit?.(writeSet, commitTs);
294
+ return {
295
+ result,
296
+ writeSet,
297
+ commitTs
298
+ };
299
+ } catch (err) {
300
+ await db?.rollback();
301
+ throw err;
302
+ } finally {
303
+ db?.release();
304
+ }
305
+ });
306
+ }
307
+ };
308
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
309
+ //#endregion
310
+ export { TxContext as a, DbWriter as i, sleep as n, DbReader as r, SupaliveDb as t };
311
+
312
+ //# sourceMappingURL=realtime_db-DVhhasJj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"realtime_db-DVhhasJj.js","names":["z"],"sources":["../src/db/context.ts","../src/db/realtime_db.ts"],"sourcesContent":["import { z, ZodRawShape } from \"zod\";\nimport { Database } from \"./db\";\nimport { ReadEntry, WriteEntry, } from \"./types_db\";\n\nimport { ColumnCodec, InferSchema, InsertData, Model, SchemaDefinition } from \"./schema\";\nimport { normalizeCodec, unwrapZodType } from \"./codec\";\nimport { QueryBuilder } from \"./query\";\n\n/**\n * Materialize a schema's runtime {@link Model}: column-name mapping, per-column\n * coarse type tags, and the codec used to (de)serialize each column.\n *\n * Codecs are resolved via {@link normalizeCodec}, which supplies a sensible\n * default per Zod type (e.g. a {@link dateCodec} for `z.date()`, so `Date`\n * columns round-trip automatically) while letting a user-supplied codec in\n * `schema.columnsOptions.codecs` override it — partially or fully.\n */\nexport function buildModel(schema: SchemaDefinition<string, ZodRawShape>): Model {\n const shape = schema.schema.shape;\n const customColumns = (schema as any).columns;\n const columns: Record<string, string> = {};\n const types: Record<string, string> = {};\n const codecs: Record<string, ColumnCodec<any, any>> = {};\n const schemaCodecs = schema.columnsOptions.codecs ?? {};\n\n for (const key of Object.keys(shape)) {\n columns[key] = customColumns?.[key] ?? key;\n const field = shape[key];\n const baseField = unwrapZodType(field);\n if (baseField instanceof z.ZodNumber) {\n types[key] = \"integer\";\n } else if (baseField instanceof z.ZodString) {\n types[key] = \"string\";\n } else if (baseField instanceof z.ZodBoolean) {\n types[key] = \"boolean\";\n } else if (baseField instanceof z.ZodDate) {\n types[key] = \"date\";\n } else if (baseField instanceof z.ZodArray) {\n types[key] = \"array\";\n } else {\n types[key] = \"json\";\n }\n codecs[key] = normalizeCodec(schemaCodecs[key], baseField);\n }\n\n return {\n table: schema.table,\n tableId: schema.tableId,\n columns,\n reverseColumns: Object.fromEntries(Object.entries(columns).map(([k, v]) => [v, k])),\n types,\n codecs,\n };\n}\n\nexport class TxContext {\n // Not `readonly`: a query's read connection can be rebound (primary↔replica)\n // via {@link useConnection} before the first read — see the replica routing in\n // realtime_db.ts / one-shot-query.ts. Mutations never rebind.\n beginTs: bigint;\n db: Database;\n protected readSet: ReadEntry[] = [];\n protected writeSet: WriteEntry[] = [];\n private models: Map<string, Model> = new Map();\n\n protected getOrCreateModel(schema: SchemaDefinition<string, ZodRawShape>): Model {\n const existing = this.models.get(schema.table);\n if (existing) return existing;\n\n const model = buildModel(schema);\n this.models.set(schema.table, model);\n return model;\n }\n\n constructor(db: Database, beginTs: bigint) {\n this.db = db;\n this.beginTs = beginTs;\n }\n\n /**\n * Rebind the read connection (and its snapshot ts). Used by the replica\n * router when a query handler calls `ctx.usePrimaryConn()`/`useReplicaConn()`.\n * Must be called BEFORE any read — the readSet/beginTs would otherwise mix\n * snapshots — so this throws if a read or write has already happened.\n */\n useConnection(db: Database, beginTs: bigint): void {\n if (this.readSet.length > 0 || this.writeSet.length > 0) {\n throw new Error(\n \"useConnection()/usePrimaryConn()/useReplicaConn() must be called before any read or write in the handler\",\n );\n }\n this.db = db;\n this.beginTs = beginTs;\n }\n\n internalGetReadSet(): ReadEntry[] { return this.readSet; }\n internalGetWriteSet(): WriteEntry[] { return this.writeSet; }\n\n /**\n * Merge a parent procedure's reads into this context's readSet. Used when a\n * `runMutation` sub-transaction inherits the reads of the procedure that\n * invoked it, so the sub-tx's OCC validation also fences on those rows.\n * Entries are shallow-cloned so the two readSets don't alias.\n */\n appendInternalReadSet(parentEntries: ReadEntry[]) {\n this.readSet.push(...parentEntries.map((e) => ({...e})));\n }\n\n protected findPendingWrite(table: string, id: string): WriteEntry | undefined {\n return this.writeSet.find(w => w.table === table && w.id === id);\n }\n\n protected findPendingInsert(table: string, id: string): WriteEntry | undefined {\n return this.writeSet.find(w => w.table === table && w.id === id && w.op === \"insert\");\n }\n\n protected encodeWithCodec(model: Model, property: string, value: unknown): unknown {\n const codec = model.codecs[property];\n if (!codec?.encode || value === undefined || value === null) return value;\n return codec.encode(value);\n }\n}\n\nexport class DbReader extends TxContext {\n query<S extends SchemaDefinition<string, ZodRawShape>>(schema: S): QueryBuilder<S> {\n const model = this.getOrCreateModel(schema);\n return new QueryBuilder<S>(this, model);\n }\n}\n\nexport class DbWriter extends DbReader {\n async insert<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n data: InsertData<S>\n ): Promise<void> {\n const model = this.getOrCreateModel(schema);\n const mappedData: Record<string, unknown> = { id };\n const shape = schema.schema.shape;\n\n for (const key of Object.keys(shape)) {\n let value = data[key];\n\n if (value === undefined) {\n const field = shape[key];\n if (field instanceof z.ZodDefault) {\n const defaultVal = field.def.defaultValue;\n value = (typeof defaultVal === \"function\" ? defaultVal() : defaultVal)\n\n if (value !== undefined) {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n }\n } else {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n }\n // ensure id same\n mappedData[\"id\"] = id;\n\n // Check for existing pending write for the same ID\n const existing = this.findPendingWrite(schema.table, id);\n if (existing) {\n if (existing.op === \"delete\") {\n // If there's a pending delete, change it to an update with the new data\n existing.op = \"update\";\n existing.data = mappedData;\n } else {\n // If there's a pending update or same insert with the same ID , merge the new data\n existing.data = { ...existing.data, ...mappedData };\n }\n } else {\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id: id, op: \"insert\", data: mappedData });\n }\n }\n\n async update<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n data: Partial<Omit<InferSchema<S>, \"id\" | \"commitTs\">>,\n ): Promise<void> {\n const model = this.getOrCreateModel(schema);\n const mappedData: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(data)) {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n\n const existing = this.findPendingWrite(schema.table, id);\n if (existing) {\n existing.op = existing.op === \"insert\" ? \"insert\" : \"update\";\n existing.data = { ...existing.data, ...mappedData };\n } else {\n // expectedTs will be filled by the committer via batch fetch if not known yet\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id, op: \"update\", data: mappedData });\n }\n }\n\n async delete<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n ): Promise<void> {\n // If there's a pending insert for the same ID, remove it instead of adding a delete\n const existingInsert = this.findPendingInsert(schema.table, id);\n if (existingInsert) {\n this.writeSet = this.writeSet.filter(w => w !== existingInsert);\n return;\n }\n\n // expectedTs will be filled by the committer via batch fetch if not known yet\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id, op: \"delete\" });\n }\n}\n","import { Database, LazyCommitTsParam, TxDatabase } from \"./db\";\nimport {\n OccConflictError, WriteEntry, CommitTs, LiveResult, MutationResult\n} from \"./types_db\";\nimport { DbReader, DbWriter } from \"./context\";\nimport { traceDbCall } from \"./db-trace\";\nimport { ExponentialBackoff, handleWhen, retry, RetryPolicy } from \"cockatiel\";\n\nexport const occRetryPolicy = retry(\n handleWhen((err) => OccConflictError.isOccConflictError(err)),\n {\n maxAttempts: 15,\n backoff: new ExponentialBackoff({\n initialDelay: 10,\n maxDelay: 7000,\n exponent: 2,\n }),\n },\n);\n\nexport const getDbclientRetryPolicy = retry(\n handleWhen((err) => err.message.includes('timeout exceeded')),\n {\n maxAttempts: 3,\n backoff: new ExponentialBackoff({\n initialDelay: 500,\n maxDelay: 2000,\n exponent: 2,\n }),\n },\n);\n\nexport class SupaliveDb {\n /**\n * @param impl the PRIMARY (writer) connection — all mutations, the OCC\n * commit-ts source, and cache-freshness commit-log scans run here.\n * @param replica optional read replica for query/action reads (see the\n * routing in one-shot-query.ts). Undefined → reads use primary.\n */\n constructor(readonly impl: Database, readonly replica?: SupaliveDb) { }\n\n static create(config: { db: Database; replica?: Database }): SupaliveDb {\n return new SupaliveDb(config.db, config.replica ? new SupaliveDb(config.replica) : undefined);\n }\n\n /** True when a distinct read replica is configured. */\n get hasReplica(): boolean {\n return this.replica !== undefined;\n }\n\n protected onAfterCommit?: (writeSet: WriteEntry[], commitTs: CommitTs) => void;\n\n /**\n * Register a hook fired once after every successful `mutation()` commit\n * (never on an OCC conflict/rollback), with the committed writeSet and its\n * commitTs. The server uses this to drive subscription invalidation for ALL\n * mutation sources — client WS calls, actions, jobs, and the internal caller —\n * so a server-side write pushes live updates just like a client write does.\n * Non-server consumers (migration tooling, tests) leave it unset (no-op).\n */\n setOnAfterCommit(cb: (writeSet: WriteEntry[], commitTs: CommitTs) => void): void {\n this.onAfterCommit = cb;\n }\n\n // ── Read-only query ──────────────────────────────────────────────\n\n /**\n * One-shot read against an EXPLICIT connection + snapshot ts (rather than this\n * db's own latest). Used by the replica router: the caller pre-resolves the\n * default read connection (replica for queries) and hands the handler a\n * `DbReader` it can rebind via `useConnection` (ctx.usePrimaryConn/…). The\n * returned `ts` is the FINAL bound connection's snapshot, so the cache entry is\n * stamped with the ts actually read at.\n */\n async queryInternalOn<T>(\n read: { impl: Database; beginTs: bigint },\n fn: (ctx: DbReader) => Promise<T>,\n ): Promise<LiveResult<T>> {\n const ctx = new DbReader(read.impl, read.beginTs);\n const data = await fn(ctx);\n return { ts: ctx.beginTs, data, readSet: ctx.internalGetReadSet() };\n }\n\n async query<T>(fn: (ctx: DbReader) => Promise<T>): Promise<T> {\n const beginTs = await this.impl.getLatestSnapshotTimestamp();\n const ctx = new DbReader(this.impl, beginTs);\n return await fn(ctx);\n }\n\n /**\n * Compute a query once at the latest snapshot, returning the result together\n * with the snapshot `ts` and the tracked `readSet`. This is a plain one-shot\n * evaluation — it registers NO live subscription; the `readSet`/`ts` are\n * returned purely so the caller (e.g. the one-shot query cache) can store\n * freshness metadata. Use this for cached one-shot query calls (WS `call`,\n * HTTP RPC). `liveQuery` is the same computation under the subscription path's\n * name and simply delegates here.\n */\n async queryInternal<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>> {\n const beginTs = await this.impl.getLatestSnapshotTimestamp();\n const ctx = new DbReader(this.impl, beginTs);\n const data = await fn(ctx);\n\n return {\n ts: beginTs,\n data,\n readSet: ctx.internalGetReadSet(),\n };\n }\n\n async liveQuery<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>> {\n return this.queryInternal(fn);\n }\n\n // ── Mutation ───────────────────────────────────────────────────────\n\n async mutation<T>(\n fn: (ctx: DbWriter) => Promise<T>,\n retryPolicy: RetryPolicy = occRetryPolicy,\n ): Promise<MutationResult<T>> {\n return await retryPolicy.execute(async (p) => {\n let db: TxDatabase | undefined;\n try {\n // Step1: Get latest snapshot timestamp as beginTs\n const beginTs = await this.impl.getLatestSnapshotTimestamp() + 1n;\n\n const ctx = new DbWriter(this.impl, beginTs);\n const result = await fn(ctx);\n\n const readSet = ctx.internalGetReadSet();\n const writeSet = ctx.internalGetWriteSet();\n const commitTsLazy = new LazyCommitTsParam(undefined);\n\n // Step2: Capture prevData + expectedCommitTs per write. prevData\n // is consumed by the invalidator (range subs need it to detect\n // result-set transitions). expectedCommitTs becomes the CAS fence\n // for the apply step — preferring prior find()-captured ts so\n // read-then-update patterns get beginTs-level isolation.\n await this.impl.attachPrevDataToWriteSet(writeSet, readSet);\n\n // Step3: Prepare quieries before transaction\n const queries = await this.impl.prepareCommitWrites(\n readSet,\n writeSet,\n commitTsLazy,\n );\n\n // Step4: Starts new transaction\n db = await getDbclientRetryPolicy.execute(() => this.impl.getTransactionClient());\n await db.begin();\n\n // Step5: Get commitTs from DB sequence (bigger than all previous)\n const commitTs = await db.getNextTimestamp();\n commitTsLazy.value = commitTs;\n\n // Step6: Apply + validate. CAS UPDATE/DELETE catches concurrent\n // peer touches on the write set; the readSet is validated either\n // per-row (fast path, no range reads) or via commit-log scan\n // (slow path, when range reads are present so phantoms still\n // need detection).\n const commitResult = await traceDbCall(\n \"commit\",\n \"\",\n this.impl.dbType,\n () => db!.commitWrites(beginTs, queries, commitTs),\n );\n\n if (!commitResult.success) {\n throw new OccConflictError(\"Commit failed\", { commitResult });\n }\n\n await db.updateLatestSnapshotTimestamp(commitTs);\n await db.commit();\n\n // Notify after successful commit\n this.onAfterCommit?.(writeSet, commitTs);\n\n return { result, writeSet, commitTs };\n } catch (err) {\n await db?.rollback();\n throw err;\n } finally {\n db?.release();\n }\n });\n }\n}\n\nexport const sleep = (ms: number) => new Promise<void>((res) => setTimeout(res, ms));\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,WAAW,QAAsD;CAC/E,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,gBAAiB,OAAe;CACtC,MAAM,UAAkC,CAAC;CACzC,MAAM,QAAgC,CAAC;CACvC,MAAM,SAAgD,CAAC;CACvD,MAAM,eAAe,OAAO,eAAe,UAAU,CAAC;CAEtD,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAG;EACpC,QAAQ,OAAO,gBAAgB,QAAQ;EACvC,MAAM,QAAQ,MAAM;EACpB,MAAM,YAAY,cAAc,KAAK;EACrC,IAAI,qBAAqBA,IAAE,WACzB,MAAM,OAAO;OACR,IAAI,qBAAqBA,IAAE,WAChC,MAAM,OAAO;OACR,IAAI,qBAAqBA,IAAE,YAChC,MAAM,OAAO;OACR,IAAI,qBAAqBA,IAAE,SAChC,MAAM,OAAO;OACR,IAAI,qBAAqBA,IAAE,UAChC,MAAM,OAAO;OAEb,MAAM,OAAO;EAEf,OAAO,OAAO,eAAe,aAAa,MAAM,SAAS;CAC3D;CAEA,OAAO;EACL,OAAO,OAAO;EACd,SAAS,OAAO;EAChB;EACA,gBAAgB,OAAO,YAAY,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;EAClF;EACA;CACF;AACF;AAEA,IAAa,YAAb,MAAuB;CAIrB;CACA;CACA,UAAiC,CAAC;CAClC,WAAmC,CAAC;CACpC,yBAAqC,IAAI,IAAI;CAE7C,iBAA2B,QAAsD;EAC/E,MAA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Q,CACnD;IAEA,IAAI,CAAC,aAAa,SAChB,MAAM,IAAI,iBAAiB,iBAAiB,EAAE,aAAa,CAAC;IAG9D,MAAM,GAAG,8BAA8B,QAAQ;IAC/C,MAAM,GAAG,OAAO;IAGhB,KAAK,gBAAgB,UAAU,QAAQ;IAEvC,OAAO;KAAE;KAAQ;KAAU;IAAS;GACtC,SAAS,KAAK;IACZ,MAAM,IAAI,SAAS;IACnB,MAAM;GACR,UAAU;IACR,IAAI,QAAQ;GACd;EACF,CAAC;CACH;AACF;AAEA,MAAa,SAAS,OAAe,IAAI,SAAe,QAAQ,WAAW,KAAK,EAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"router-DP2ThAwh.js","names":[],"sources":["../src/router/procedure.ts","../src/router/router.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { DbReader, DbWriter } from \"../db/context\";\nimport type { SupaliveDb } from \"../db/realtime_db\";\nimport type { ObjectStorage } from \"../storage\";\nimport type { JobClient } from \"../jobs/scheduler\";\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\n/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */\nexport interface ConnOpts {\n /**\n * Force the PRIMARY (writer) connection even inside a query/action —\n * read-your-writes. On `useReplicaConn` this overrides the replica choice.\n */\n readOwnWrite?: boolean;\n}\n\nexport interface QueryCtx<TContext = unknown> {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * Route this query's reads to the PRIMARY (writer) connection. Must be called\n * BEFORE any read (throws otherwise). A no-op when reads already run on primary\n * (no replica configured, or a primary-only path like a live query).\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /**\n * Route this query's reads to the read REPLICA, if one is configured. Must be\n * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.\n */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * No-op connection routing for query paths that genuinely ALWAYS run on the\n * primary — live subscription re-execution and mutation handlers. Spread into\n * the ctx so `ctx.usePrimaryConn()`/`useReplicaConn()` are always callable but\n * inert (there is only ever the primary connection to bind).\n *\n * For a nested `runQuery` that JOINS a parent transaction, use {@link parentConn}\n * instead — there the connection isn't necessarily the primary.\n */\nexport const primaryOnlyConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * No-op connection routing for a nested `runQuery` that JOINS a parent\n * transaction (a `runQuery` called with a query/mutation `parentCtx`). The knobs\n * always use the PARENT's connection because the read connection is fixed to the\n * parent transaction's — which may be the PRIMARY or the REPLICA, depending on\n * how the parent query was routed.\n *\n * They MUST be inert: a nested query shares the parent's snapshot + readSet, so\n * calling `useConnection` here would either repoint the parent's connection\n * mid-flight (before its first read) or throw (after it) — either way corrupting\n * the parent transaction. A handler that needs to force primary therefore cannot\n * do so while nested under a replica-routed parent (it inherits the replica,\n * which is already safe w.r.t. the client's `minTs` floor); call it via an\n * action-parent `runQuery` instead, which opens a fresh routed read.\n */\nexport const parentConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * Mutation context passed to mutation handlers.\n * Contains database writer and user-defined server context.\n */\nexport interface MutationCtx<TContext = unknown> {\n /** Database writer for mutations (includes insert/update/delete) */\n db: DbWriter;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * No-op on a mutation — writes (and their reads) always run on the primary.\n * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.\n * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * Action context passed to action handlers.\n *\n * Actions are the \"external I/O\" tier: they hold the full {@link SupaliveDb}\n * (queries + mutations) and are the ONLY context that also carries side-effect\n * services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}\n * for scheduling precise one-shots. Queries/mutations stay pure (db only) so\n * they remain cacheable and transaction-scoped.\n */\nexport interface ActionCtx<TContext = unknown> {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** Object storage, when the server was configured with one (see\n * `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home\n * for upload/download presigning. */\n storage: ObjectStorage;\n /** Job scheduler client for enqueueing precise one-shots, when the server\n * was configured with a `scheduler`; `undefined` otherwise. Scheduling is\n * network I/O, so it belongs in actions, never inside a DB transaction. */\n scheduler: JobClient;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Job context passed to job handlers. Structurally identical to\n * {@link ActionCtx}: a job is a server-only procedure that runs\n * non-transactionally against the full {@link SupaliveDb} and may perform\n * external work, but it is triggered by the scheduler over HTTP (a cron tick\n * or a precise one-shot) rather than by a connected client. `serverCtx` is\n * the system context built by the server's `jobContext` factory.\n */\nexport interface JobCtx<TContext = unknown> {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** System server context built by the server for scheduler-triggered runs */\n serverCtx?: TContext;\n}\n\n/**\n * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one\n * procedure from inside another. Pass the caller handler's own `ctx` — its `db`\n * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,\n * inside an action, the full {@link SupaliveDb}. The caller uses this to decide\n * whether the nested call joins the parent's snapshot (queries) or runs as an\n * independent sub-transaction (mutations).\n */\nexport interface ParentCtx<TContext = unknown> {\n db: DbReader | DbWriter | SupaliveDb;\n serverCtx?: TContext | undefined;\n}\n\n// ─── Procedure Types ─────────────────────────────────────────────────────────\n\nexport type QueryFn<TInput, TResult, TContext = unknown> = (\n ctx: QueryCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type MutationFn<TInput, TResult, TContext = unknown> = (\n ctx: MutationCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type ActionFn<TInput, TResult, TContext = unknown> = (\n ctx: ActionCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type JobFn<TInput, TResult, TContext = unknown> = (\n ctx: JobCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\n/**\n * Per-procedure override for the cache/subscription segmentation key.\n *\n * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)\n * false → no identity in hash; cache/sub shared across all users\n * string → a static identity literal (e.g. \"public\" or a tenant id)\n * function → compute from serverCtx + input (sync)\n *\n * When the result of a query is identical regardless of who calls it, set\n * this to a literal (or `false`) so a single cache entry serves everyone.\n *\n * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)\n * because identity is resolved before any DB read is issued.\n */\nexport type QueryIdentitySpec<TInput, TContext> =\n | false\n | string\n | ((serverCtx: TContext, input: TInput) => string | null | undefined);\n\nexport interface BaseProcedure<\n TInput, TResult,\n TType extends \"query\" | \"mutation\" | \"action\" | \"job\",\n TContext = unknown,\n TInternal extends boolean = boolean\n> {\n readonly _type: \"procedure\";\n readonly procedureType: TType;\n readonly inputSchema: ZodType<TInput>;\n readonly outputSchema?: ZodType<any>;\n readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;\n readonly internal: TInternal;\n}\n\nexport interface QueryProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"query\", TContext, TInternal> {\n readonly procedureType: \"query\";\n readonly fn: QueryFn<TInput, TResult, TContext>;\n readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"mutation\", TContext, TInternal> {\n readonly procedureType: \"mutation\";\n readonly fn: MutationFn<TInput, TResult, TContext>;\n}\n\nexport interface ActionProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"action\", TContext, TInternal> {\n readonly procedureType: \"action\";\n readonly fn: ActionFn<TInput, TResult, TContext>;\n}\n\n/**\n * A scheduler-triggered, server-only procedure. Runs like an action (full\n * db, non-transactional, may do external work) but is dispatched by the\n * server's HTTP job endpoint on a cron tick or a precise one-shot rather\n * than over the client WebSocket. Always {@link internal}: true, so it is\n * never reachable via `call`/`subscribe`.\n */\nexport interface JobProcedure<\n TInput, TResult,\n TContext = unknown,\n> extends BaseProcedure<TInput, TResult, \"job\", TContext, true> {\n readonly procedureType: \"job\";\n readonly fn: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring job (e.g. `\"0 3 * * *\"`). Declared crons\n * are synced to the scheduler at server startup. Omit for a job that is\n * only ever invoked as a precise one-shot via the scheduler API.\n */\n readonly cron?: string;\n}\n\nexport type AnyProcedure<TContext = unknown> =\n | QueryProcedure<any, any, TContext>\n | MutationProcedure<any, any, TContext>\n | ActionProcedure<any, any, TContext>\n | JobProcedure<any, any, TContext>;\n\n// ─── Procedure Configuration Types ───────────────────────────────────────────\n\nexport interface QueryConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The query handler function */\n handler: QueryFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type. Use `.modelName(\"Name\")`\n * on a Zod object to rename the generated model class.\n */\n returns?: ZodType<any>;\n /**\n * Override the cache/subscription segmentation key for this procedure.\n * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.\n */\n queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The mutation handler function */\n handler: MutationFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface ActionConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The action handler function */\n handler: ActionFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface JobConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for the job payload */\n args: ZodType<TInput>;\n /** The job handler function */\n handler: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring schedule (e.g. `\"0 3 * * *\"`). Omit for a\n * job that is only invoked as a precise one-shot.\n */\n cron?: string;\n}\n\n/** Extract input type from a procedure */\nexport type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;\n\n/** Extract output type from a procedure */\nexport type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;\n\n/** Extract procedure type (query/mutation) */\nexport type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;\n\n/** Extract server context type from a procedure */\nexport type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;\n\n/**\n * Create a query builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your query handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed query builder\n * const query = createQueryBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const getUser = query({\n * args: z.object({ id: z.string() }),\n * handler: async (ctx, { id }) => {\n * // ctx.db for database queries\n * const user = await ctx.db.query(UsersSchema).find(id);\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return user;\n * }\n * });\n */\nexport function createQueryBuilder<TContext = unknown>() {\n return function query<TInput, TResult, const TInternal extends boolean = false>(\n config: QueryConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): QueryProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"query\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n queryIdentity: config.queryIdentity,\n };\n };\n}\n\n// ─── Mutation Builder Factory ────────────────────────────────────────────────\n\n/**\n * Create a mutation builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your mutation handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed mutation builder\n * const mutation = createMutationBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const createUser = mutation({\n * args: z.object({ name: z.string() }),\n * handler: async (ctx, { name }) => {\n * // ctx.db for mutations\n * await ctx.db.insert(UsersSchema, id, { name });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createMutationBuilder<TContext = unknown>() {\n return function mutation<TInput, TResult, const TInternal extends boolean = false>(\n config: MutationConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): MutationProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"mutation\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Action Builder Factory ──────────────────────────────────────────────────\n\n/**\n * Create an action builder with a pre-defined context type.\n * Actions have access to the full SupaliveDb for both queries and mutations.\n *\n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n *\n * // Create a typed action builder\n * const action = createActionBuilder<ServerContext>();\n *\n * // Use it - context type is automatically inferred!\n * const processOrder = action({\n * args: z.object({ orderId: z.string() }),\n * handler: async (ctx, { orderId }) => {\n * // ctx.db for full database access\n * const order = await ctx.db.query(async (db) => {\n * return db.query(OrdersSchema).find(orderId);\n * });\n * await ctx.db.mutation(async (db) => {\n * await db.update(OrdersSchema, orderId, { status: \"processed\" });\n * });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createActionBuilder<TContext = unknown>() {\n return function action<TInput, TResult, const TInternal extends boolean = false>(\n config: ActionConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): ActionProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"action\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Job Builder Factory ─────────────────────────────────────────────────────\n\n/**\n * Create a job builder with a pre-defined context type. A job is a\n * server-only procedure invoked by the scheduler over HTTP — either on its\n * declared `cron` schedule or as a precise one-shot enqueued via the\n * server's job API. Jobs run like actions (full db, non-transactional) and\n * are always internal, so they are never reachable from a client.\n *\n * @example\n * const job = createJobBuilder<ServerContext>();\n *\n * export const cleanupOtps = job({\n * cron: \"0 * * * *\", // hourly\n * args: z.object({}),\n * handler: async (ctx) => {\n * await ctx.db.mutation(async (db) => { ... });\n * return { ok: true };\n * },\n * });\n */\nexport function createJobBuilder<TContext = unknown>() {\n return function job<TInput, TResult>(\n config: JobConfig<TInput, TResult, TContext>\n ): JobProcedure<TInput, TResult, TContext> {\n return {\n _type: \"procedure\",\n procedureType: \"job\",\n inputSchema: config.args,\n fn: config.handler,\n internal: true,\n cron: config.cron,\n };\n };\n}","import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":";;;;;;;;;;AAgDA,MAAa,kBAAuE;CAClF,sBAAsB,CAAE;CACxB,sBAAsB,CAAE;AAC1B;;;;;;;;;;;;;;;;AAiBA,MAAa,aAAkE;CAC7E,sBAAsB,CAAE;CACxB,sBAAsB,CAAE;AAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+RA,SAAgB,qBAAyC;CACvD,OAAO,SAAS,MACd,QACsD;EACtD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;GAC9B,eAAe,OAAO;EACxB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,wBAA4C;CAC1D,OAAO,SAAS,SACd,QACyD;EACzD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;EAChC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAA0C;CACxD,OAAO,SAAS,OACd,QACuD;EACvD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB,IAAI,OAAO;GAC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AAkB,IAAI,IAAI;CACxC;;CAGA,oBAA8B;EAC5B,OAAO,CAAC,GAAG,KAAK,kBAAkB,KAAK,CAAC;CAC1C;;CAGA,mBAAqD;EACnD,OAAO,IAAI,IAAI,KAAK,iBAAiB;CACvC;;CAGA,mBAA0C;EACxC,OAAO,CAAC,GAAG,KAAK,kBAAkB,OAAO,CAAC,CAAC,CAAC,QAAQ,MAAM,EAAE,SAAS,KAAK;CAC5E;;CAGA,gBAAsB;EACpB,KAAK,kBAAkB,MAAM;EAC7B,KAAK,wBAAwB;CAC/B;CAEA,sBAAsB,MAAoB;EACxC,KAAK,uBAAuB,IAAI,IAAI;CACtC;CAEA,oBAAoB,MAAuB;EACzC,OAAO,KAAK,uBAAuB,IAAI,IAAI;CAC7C;CAEA,0BAAgC;EAC9B,KAAK,uBAAuB,MAAM;CACpC;AACF"}
1
+ {"version":3,"file":"router-DP2ThAwh.js","names":[],"sources":["../src/router/procedure.ts","../src/router/router.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { Span } from \"@opentelemetry/api\";\nimport type { DbReader, DbWriter } from \"../db/context\";\nimport type { SupaliveDb } from \"../db/realtime_db\";\nimport type { ObjectStorage } from \"../storage\";\nimport type { JobClient } from \"../jobs/scheduler\";\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\n/**\n * Minimal request-scoped logger exposed as `ctx.log`. Structurally satisfied by\n * a pino logger, so the server hands its own child logger straight through; the\n * interface keeps handler code decoupled from pino. Bound with `reqId`, the\n * procedure name, and (when tracing is enabled) the `traceId`, so every line a\n * handler writes correlates to its request and trace.\n */\nexport interface HandlerLogger {\n debug(...args: any[]): void;\n info(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n}\n\n/**\n * Observability handles present on a handler context when it runs through the\n * server (absent for direct internal-caller invocations).\n */\nexport interface HandlerObservability {\n /** Request-scoped logger, correlated to this operation (reqId + trace id). */\n log?: HandlerLogger;\n /** The active OpenTelemetry span for this operation. Add attributes/events or\n * parent child spans off it. A non-recording no-op span when tracing is off. */\n span?: Span;\n}\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\n/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */\nexport interface ConnOpts {\n /**\n * Force the PRIMARY (writer) connection even inside a query/action —\n * read-your-writes. On `useReplicaConn` this overrides the replica choice.\n */\n readOwnWrite?: boolean;\n}\n\nexport interface QueryCtx<TContext = unknown> extends HandlerObservability {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * Route this query's reads to the PRIMARY (writer) connection. Must be called\n * BEFORE any read (throws otherwise). A no-op when reads already run on primary\n * (no replica configured, or a primary-only path like a live query).\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /**\n * Route this query's reads to the read REPLICA, if one is configured. Must be\n * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.\n */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * No-op connection routing for query paths that genuinely ALWAYS run on the\n * primary — live subscription re-execution and mutation handlers. Spread into\n * the ctx so `ctx.usePrimaryConn()`/`useReplicaConn()` are always callable but\n * inert (there is only ever the primary connection to bind).\n *\n * For a nested `runQuery` that JOINS a parent transaction, use {@link parentConn}\n * instead — there the connection isn't necessarily the primary.\n */\nexport const primaryOnlyConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * No-op connection routing for a nested `runQuery` that JOINS a parent\n * transaction (a `runQuery` called with a query/mutation `parentCtx`). The knobs\n * always use the PARENT's connection because the read connection is fixed to the\n * parent transaction's — which may be the PRIMARY or the REPLICA, depending on\n * how the parent query was routed.\n *\n * They MUST be inert: a nested query shares the parent's snapshot + readSet, so\n * calling `useConnection` here would either repoint the parent's connection\n * mid-flight (before its first read) or throw (after it) — either way corrupting\n * the parent transaction. A handler that needs to force primary therefore cannot\n * do so while nested under a replica-routed parent (it inherits the replica,\n * which is already safe w.r.t. the client's `minTs` floor); call it via an\n * action-parent `runQuery` instead, which opens a fresh routed read.\n */\nexport const parentConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * Mutation context passed to mutation handlers.\n * Contains database writer and user-defined server context.\n */\nexport interface MutationCtx<TContext = unknown> extends HandlerObservability {\n /** Database writer for mutations (includes insert/update/delete) */\n db: DbWriter;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * No-op on a mutation — writes (and their reads) always run on the primary.\n * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.\n * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * Action context passed to action handlers.\n *\n * Actions are the \"external I/O\" tier: they hold the full {@link SupaliveDb}\n * (queries + mutations) and are the ONLY context that also carries side-effect\n * services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}\n * for scheduling precise one-shots. Queries/mutations stay pure (db only) so\n * they remain cacheable and transaction-scoped.\n */\nexport interface ActionCtx<TContext = unknown> extends HandlerObservability {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** Object storage, when the server was configured with one (see\n * `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home\n * for upload/download presigning. */\n storage: ObjectStorage;\n /** Job scheduler client for enqueueing precise one-shots, when the server\n * was configured with a `scheduler`; `undefined` otherwise. Scheduling is\n * network I/O, so it belongs in actions, never inside a DB transaction. */\n scheduler: JobClient;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Job context passed to job handlers. Structurally identical to\n * {@link ActionCtx}: a job is a server-only procedure that runs\n * non-transactionally against the full {@link SupaliveDb} and may perform\n * external work, but it is triggered by the scheduler over HTTP (a cron tick\n * or a precise one-shot) rather than by a connected client. `serverCtx` is\n * the system context built by the server's `jobContext` factory.\n */\nexport interface JobCtx<TContext = unknown> extends HandlerObservability {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** System server context built by the server for scheduler-triggered runs */\n serverCtx?: TContext;\n}\n\n/**\n * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one\n * procedure from inside another. Pass the caller handler's own `ctx` — its `db`\n * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,\n * inside an action, the full {@link SupaliveDb}. The caller uses this to decide\n * whether the nested call joins the parent's snapshot (queries) or runs as an\n * independent sub-transaction (mutations).\n */\nexport interface ParentCtx<TContext = unknown> {\n db: DbReader | DbWriter | SupaliveDb;\n serverCtx?: TContext | undefined;\n}\n\n// ─── Procedure Types ─────────────────────────────────────────────────────────\n\nexport type QueryFn<TInput, TResult, TContext = unknown> = (\n ctx: QueryCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type MutationFn<TInput, TResult, TContext = unknown> = (\n ctx: MutationCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type ActionFn<TInput, TResult, TContext = unknown> = (\n ctx: ActionCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type JobFn<TInput, TResult, TContext = unknown> = (\n ctx: JobCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\n/**\n * Per-procedure override for the cache/subscription segmentation key.\n *\n * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)\n * false → no identity in hash; cache/sub shared across all users\n * string → a static identity literal (e.g. \"public\" or a tenant id)\n * function → compute from serverCtx + input (sync)\n *\n * When the result of a query is identical regardless of who calls it, set\n * this to a literal (or `false`) so a single cache entry serves everyone.\n *\n * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)\n * because identity is resolved before any DB read is issued.\n */\nexport type QueryIdentitySpec<TInput, TContext> =\n | false\n | string\n | ((serverCtx: TContext, input: TInput) => string | null | undefined);\n\nexport interface BaseProcedure<\n TInput, TResult,\n TType extends \"query\" | \"mutation\" | \"action\" | \"job\",\n TContext = unknown,\n TInternal extends boolean = boolean\n> {\n readonly _type: \"procedure\";\n readonly procedureType: TType;\n readonly inputSchema: ZodType<TInput>;\n readonly outputSchema?: ZodType<any>;\n readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;\n readonly internal: TInternal;\n}\n\nexport interface QueryProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"query\", TContext, TInternal> {\n readonly procedureType: \"query\";\n readonly fn: QueryFn<TInput, TResult, TContext>;\n readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"mutation\", TContext, TInternal> {\n readonly procedureType: \"mutation\";\n readonly fn: MutationFn<TInput, TResult, TContext>;\n}\n\nexport interface ActionProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"action\", TContext, TInternal> {\n readonly procedureType: \"action\";\n readonly fn: ActionFn<TInput, TResult, TContext>;\n}\n\n/**\n * A scheduler-triggered, server-only procedure. Runs like an action (full\n * db, non-transactional, may do external work) but is dispatched by the\n * server's HTTP job endpoint on a cron tick or a precise one-shot rather\n * than over the client WebSocket. Always {@link internal}: true, so it is\n * never reachable via `call`/`subscribe`.\n */\nexport interface JobProcedure<\n TInput, TResult,\n TContext = unknown,\n> extends BaseProcedure<TInput, TResult, \"job\", TContext, true> {\n readonly procedureType: \"job\";\n readonly fn: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring job (e.g. `\"0 3 * * *\"`). Declared crons\n * are synced to the scheduler at server startup. Omit for a job that is\n * only ever invoked as a precise one-shot via the scheduler API.\n */\n readonly cron?: string;\n}\n\nexport type AnyProcedure<TContext = unknown> =\n | QueryProcedure<any, any, TContext>\n | MutationProcedure<any, any, TContext>\n | ActionProcedure<any, any, TContext>\n | JobProcedure<any, any, TContext>;\n\n// ─── Procedure Configuration Types ───────────────────────────────────────────\n\nexport interface QueryConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The query handler function */\n handler: QueryFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type. Use `.modelName(\"Name\")`\n * on a Zod object to rename the generated model class.\n */\n returns?: ZodType<any>;\n /**\n * Override the cache/subscription segmentation key for this procedure.\n * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.\n */\n queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The mutation handler function */\n handler: MutationFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface ActionConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The action handler function */\n handler: ActionFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface JobConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for the job payload */\n args: ZodType<TInput>;\n /** The job handler function */\n handler: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring schedule (e.g. `\"0 3 * * *\"`). Omit for a\n * job that is only invoked as a precise one-shot.\n */\n cron?: string;\n}\n\n/** Extract input type from a procedure */\nexport type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;\n\n/** Extract output type from a procedure */\nexport type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;\n\n/** Extract procedure type (query/mutation) */\nexport type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;\n\n/** Extract server context type from a procedure */\nexport type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;\n\n/**\n * Create a query builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your query handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed query builder\n * const query = createQueryBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const getUser = query({\n * args: z.object({ id: z.string() }),\n * handler: async (ctx, { id }) => {\n * // ctx.db for database queries\n * const user = await ctx.db.query(UsersSchema).find(id);\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return user;\n * }\n * });\n */\nexport function createQueryBuilder<TContext = unknown>() {\n return function query<TInput, TResult, const TInternal extends boolean = false>(\n config: QueryConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): QueryProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"query\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n queryIdentity: config.queryIdentity,\n };\n };\n}\n\n// ─── Mutation Builder Factory ────────────────────────────────────────────────\n\n/**\n * Create a mutation builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your mutation handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed mutation builder\n * const mutation = createMutationBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const createUser = mutation({\n * args: z.object({ name: z.string() }),\n * handler: async (ctx, { name }) => {\n * // ctx.db for mutations\n * await ctx.db.insert(UsersSchema, id, { name });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createMutationBuilder<TContext = unknown>() {\n return function mutation<TInput, TResult, const TInternal extends boolean = false>(\n config: MutationConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): MutationProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"mutation\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Action Builder Factory ──────────────────────────────────────────────────\n\n/**\n * Create an action builder with a pre-defined context type.\n * Actions have access to the full SupaliveDb for both queries and mutations.\n *\n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n *\n * // Create a typed action builder\n * const action = createActionBuilder<ServerContext>();\n *\n * // Use it - context type is automatically inferred!\n * const processOrder = action({\n * args: z.object({ orderId: z.string() }),\n * handler: async (ctx, { orderId }) => {\n * // ctx.db for full database access\n * const order = await ctx.db.query(async (db) => {\n * return db.query(OrdersSchema).find(orderId);\n * });\n * await ctx.db.mutation(async (db) => {\n * await db.update(OrdersSchema, orderId, { status: \"processed\" });\n * });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createActionBuilder<TContext = unknown>() {\n return function action<TInput, TResult, const TInternal extends boolean = false>(\n config: ActionConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): ActionProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"action\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Job Builder Factory ─────────────────────────────────────────────────────\n\n/**\n * Create a job builder with a pre-defined context type. A job is a\n * server-only procedure invoked by the scheduler over HTTP — either on its\n * declared `cron` schedule or as a precise one-shot enqueued via the\n * server's job API. Jobs run like actions (full db, non-transactional) and\n * are always internal, so they are never reachable from a client.\n *\n * @example\n * const job = createJobBuilder<ServerContext>();\n *\n * export const cleanupOtps = job({\n * cron: \"0 * * * *\", // hourly\n * args: z.object({}),\n * handler: async (ctx) => {\n * await ctx.db.mutation(async (db) => { ... });\n * return { ok: true };\n * },\n * });\n */\nexport function createJobBuilder<TContext = unknown>() {\n return function job<TInput, TResult>(\n config: JobConfig<TInput, TResult, TContext>\n ): JobProcedure<TInput, TResult, TContext> {\n return {\n _type: \"procedure\",\n procedureType: \"job\",\n inputSchema: config.args,\n fn: config.handler,\n internal: true,\n cron: config.cron,\n };\n };\n}","import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":";;;;;;;;;;AA2EA,MAAa,kBAAuE;CAClF,sBAAsB,CAAE;CACxB,sBAAsB,CAAE;AAC1B;;;;;;;;;;;;;;;;AAiBA,MAAa,aAAkE;CAC7E,sBA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pSchema, Ar as PointRead, Bn as Database, Br as RangeReadSchema, Bt as SupaliveDb, Cr as LiveResult, Ct as QueryFn, Dr as OccConflictError, Er as OccAbortError, Et as createActionBuilder, Fn as defineSchema, Fr as QueryCacheEntrySchema, G as RPCError, Gr as RawReadEntry, Gt as QueryDefinition, Hr as RawPointReadSchema, Ht as AnyQueryDef, Ir as QueryCacheMetadata, J as ActionProcedures, Jr as ReadEntrySchema, Jt as defineQuery, K as WSClientOptions, Kn as RawClient, Kr as RawReadEntrySchema, Kt as ResultOf, Lr as QueryCacheMetadataSchema, Mn as SchemaDefinition, Mr as Predicate, Nr as PredicateSchema, Or as OrPredicate, Ot as createMutationBuilder, Pn as defineComputedField, Pr as QueryCacheEntry, Q as MutationProcedures, Qr as WriteOp, Rr as QuerySpec, Sn as Model, Sr as LeafPredicateSchema, St as QueryCtx, Tr as NO_RETRY, Tt as TypeOf, U as ClientPublicState, Ur as RawRangeRead, Ut as DefsToMap, Vn as DbQueryResult, Vr as RawPointRead, Vt as sleep, W as HeartbeatOptions, Wn as PooledClient, Wr as RawRangeReadSchema, Wt as ParamsOf, Xr as WriteEntry, Xt as DbWriter, Y as AppRouter, Yr as RetryConfig, Yt as DbReader, Zr as WriteEntrySchema, Zt as TxContext, _r as CommitTs, _t as MutationCtx, a as CallOptions, at as router, bn as InferSchema, br as DEFAULT_RETRY, bt as OutputOf, c as LiveQueryHandle, ct as ActionFn, d as WSClientMethods, dr as AndPredicate, dt as ContextOf, ei as bytesFromJson, et as PublicProcedures, f as createClient, fn as ColumnCodec, fr as AndPredicateSchema, gn as ComputedFieldConfig, gr as CommitLogEntry, gt as MutationConfig, hr as CachedPgMetadataSchema, i as createCaller, jn as SchemaColumnsOptions, jr as PointReadSchema, kn as SchemaCodecs, kr as OrPredicateSchema, kt as createQueryBuilder, l as LiveQueryState, lt as ActionProcedure, mr as CachedPgMetadata, n as CallerFromRouter, ni as normalizeToBytes, nt as RegisteredProcedure, o as ClientFromProcedures, ot as ActionConfig, pr as BigIntSchema, q as WsClientManager, qr as ReadEntry, qt as _resetGlobalDefs, r as CallerOptions, rt as Router, s as ClientOptions, st as ActionCtx, t as CallerFromProcedures, ti as normalizeIdToBytes, tt as QueryProcedures, u as LiveQueryStatus, un as matchesPredicate, ut as AnyProcedure, vr as CompareOperator, vt as MutationFn, wr as MutationResult, wt as QueryProcedure, xn as InsertData, xr as LeafPredicate, xt as QueryConfig, yr as CompareOperatorSchema, yt as MutationProcedure, zr as RangeRead } from "../../index-Ddr4NiPf.js";
2
- export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientFromProcedures, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
1
+ import { $ as AppRouter, $r as ReadEntry, $t as _resetGlobalDefs, Ar as MutationResult, At as QueryProcedure, Bn as defineComputedField, Br as QueryCacheEntry, Cr as CommitTs, Ct as MutationCtx, Dn as InsertData, Dr as LeafPredicate, Dt as QueryConfig, En as InferSchema, Er as DEFAULT_RETRY, Et as OutputOf, Fn as SchemaCodecs, Fr as OrPredicateSchema, Ft as createQueryBuilder, G as ClientLogger, Gr as RangeRead, Hr as QueryCacheMetadata, Ir as PointRead, J as RPCError, Jr as RawPointReadSchema, Jt as AnyQueryDef, K as ClientPublicState, Kn as Database, Kr as RangeReadSchema, Kt as SupaliveDb, Ln as SchemaColumnsOptions, Lr as PointReadSchema, Mr as OccAbortError, Mt as createActionBuilder, Nr as OccConflictError, On as Model, Or as LeafPredicateSchema, Ot as QueryCtx, Pr as OrPredicate, Pt as createMutationBuilder, Q as ActionProcedures, Qn as RawClient, Qr as RawReadEntrySchema, Qt as ResultOf, Rn as SchemaDefinition, Rr as Predicate, Sn as ComputedFieldConfig, Sr as CommitLogEntry, St as MutationConfig, Tr as CompareOperatorSchema, Tt as MutationProcedure, U as ClientEvent, Ur as QueryCacheMetadataSchema, Vn as defineSchema, Vr as QueryCacheEntrySchema, W as ClientLogLevel, Wr as QuerySpec, X as WsClientManager, Xn as PooledClient, Xr as RawRangeReadSchema, Xt as ParamsOf, Y as WSClientOptions, Yr as RawRangeRead, Yt as DefsToMap, Z as createConsoleLogger, Zr as RawReadEntry, Zt as QueryDefinition, _r as AndPredicate, _t as HandlerObservability, a as CallOptions, ai as WriteOpSchema, at as QueryProcedures, br as CachedPgMetadata, c as LiveQueryHandle, ci as normalizeToBytes, d as WSClientMethods, dt as ActionCtx, ei as ReadEntrySchema, en as defineQuery, f as createClient, ft as ActionFn, gn as matchesPredicate, gt as HandlerLogger, ht as ContextOf, i as createCaller, ii as WriteOp, it as PublicProcedures, jr as NO_RETRY, jt as TypeOf, kr as LiveResult, kt as QueryFn, l as LiveQueryState, lt as router, mt as AnyProcedure, n as CallerFromRouter, ni as WriteEntry, nn as DbWriter, nt as MutationProcedures, o as ClientFromProcedures, oi as bytesFromJson, ot as RegisteredProcedure, pt as ActionProcedure, q as HeartbeatOptions, qn as DbQueryResult, qr as RawPointRead, qt as sleep, r as CallerOptions, ri as WriteEntrySchema, rn as TxContext, rt as ProcedureNames, s as ClientOptions, si as normalizeIdToBytes, st as Router, t as CallerFromProcedures, ti as RetryConfig, tn as DbReader, u as LiveQueryStatus, ut as ActionConfig, vn as ColumnCodec, vr as AndPredicateSchema, wr as CompareOperator, wt as MutationFn, xr as CachedPgMetadataSchema, yr as BigIntSchema, zr as PredicateSchema } from "../../index-CfcrWLLm.js";
2
+ export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientEvent, type ClientFromProcedures, type ClientLogLevel, type ClientLogger, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, type HandlerLogger, type HandlerObservability, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createConsoleLogger, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };