@supalive/core 0.1.5 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bytes-AuEkyxeU.js +19 -0
- package/dist/bytes-AuEkyxeU.js.map +1 -0
- package/dist/codec-BHAmGEIQ.js +62 -0
- package/dist/codec-BHAmGEIQ.js.map +1 -0
- package/dist/{helper-zdJT5FUc.js → helper-wGbzz6zo.js} +2 -18
- package/dist/helper-wGbzz6zo.js.map +1 -0
- package/dist/{index-CTyXKcq_.d.ts → index-CaWMDqq0.d.ts} +21 -3
- package/dist/index-CaWMDqq0.d.ts.map +1 -0
- package/dist/index-DouKwYL6.d.ts +1754 -0
- package/dist/index-DouKwYL6.d.ts.map +1 -0
- package/dist/{mysql-C8SN443m.d.ts → mysql-Bxurg_PH.d.ts} +2 -2
- package/dist/{mysql-C8SN443m.d.ts.map → mysql-Bxurg_PH.d.ts.map} +1 -1
- package/dist/mysql-Cxd4Uq5p.d.ts +104 -0
- package/dist/mysql-Cxd4Uq5p.d.ts.map +1 -0
- package/dist/{mysql-DELSRrpY.js → mysql-bvnjYWvZ.js} +5 -4
- package/dist/{mysql-DELSRrpY.js.map → mysql-bvnjYWvZ.js.map} +1 -1
- package/dist/{overlap-checker-CVkbbuEQ.js → overlap-checker-Ct_HP_iB.js} +4 -4
- package/dist/{overlap-checker-CVkbbuEQ.js.map → overlap-checker-Ct_HP_iB.js.map} +1 -1
- package/dist/{postgres-DE-XyNAQ.js → postgres-B8u1YN8X.js} +5 -4
- package/dist/{postgres-DE-XyNAQ.js.map → postgres-B8u1YN8X.js.map} +1 -1
- package/dist/{postgres-D_gwCHx-.d.ts → postgres-CfT_aDx3.d.ts} +2 -2
- package/dist/{postgres-D_gwCHx-.d.ts.map → postgres-CfT_aDx3.d.ts.map} +1 -1
- package/dist/postgres-Ck-xt72U.d.ts +108 -0
- package/dist/postgres-Ck-xt72U.d.ts.map +1 -0
- package/dist/{schema-SKcIWHfo.js → procedure-DX87tyef.js} +2 -45
- package/dist/procedure-DX87tyef.js.map +1 -0
- package/dist/{query-CbQLjeME.js → query-Bh0RNxDz.js} +24 -64
- package/dist/query-Bh0RNxDz.js.map +1 -0
- package/dist/{realtime_db-D9p2X2PH.js → realtime_db-DOCgqbwi.js} +4 -3
- package/dist/{realtime_db-D9p2X2PH.js.map → realtime_db-DOCgqbwi.js.map} +1 -1
- package/dist/router-DlTYWpop.js.map +1 -1
- package/dist/schema-Dd7u0A1L.js +109 -0
- package/dist/schema-Dd7u0A1L.js.map +1 -0
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/index.js +6 -5
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/exports/codegen.d.ts +38 -0
- package/dist/src/exports/codegen.d.ts.map +1 -0
- package/dist/src/exports/codegen.js +134 -0
- package/dist/src/exports/codegen.js.map +1 -0
- package/dist/src/exports/mysql.d.ts +1 -1
- package/dist/src/exports/mysql.js +1 -1
- package/dist/src/exports/postgres.d.ts +1 -1
- package/dist/src/exports/postgres.js +1 -1
- package/dist/src/exports/procedure.d.ts +2 -2
- package/dist/src/exports/procedure.js +5 -4
- package/dist/src/exports/schema-sql.d.ts +18 -0
- package/dist/src/exports/schema-sql.d.ts.map +1 -0
- package/dist/src/exports/schema-sql.js +161 -0
- package/dist/src/exports/schema-sql.js.map +1 -0
- package/dist/src/exports/server.d.ts +4 -4
- package/dist/src/exports/server.d.ts.map +1 -1
- package/dist/src/exports/server.js +4 -9
- package/dist/src/exports/server.js.map +1 -1
- package/dist/src/exports/subscription-manager-worker-entry.js +2 -3
- package/dist/src/exports/subscription-manager-worker-entry.js.map +1 -1
- package/dist/src/exports/types.d.ts +2 -2
- package/dist/src/exports/types.js +2 -2
- package/dist/subscription-worker-CqoWp6zB.js +511 -0
- package/dist/subscription-worker-CqoWp6zB.js.map +1 -0
- package/dist/subscription-worker-PtmJWEj1.js +511 -0
- package/dist/subscription-worker-PtmJWEj1.js.map +1 -0
- package/dist/{subscription-worker-BurdPO8d.js → subscription-worker-pahX0zxg.js} +7 -7
- package/dist/{subscription-worker-BurdPO8d.js.map → subscription-worker-pahX0zxg.js.map} +1 -1
- package/dist/{types_db-Ctf-ksoy.js → types_db-DXj_l9n-.js} +2 -2
- package/dist/{types_db-Ctf-ksoy.js.map → types_db-DXj_l9n-.js.map} +1 -1
- package/dist/types_server-BW1ys_SK.d.ts +216 -0
- package/dist/types_server-BW1ys_SK.d.ts.map +1 -0
- package/dist/types_server-Dk6o_B7N.js.map +1 -1
- package/dist/types_server-Dpsi0wpG.d.ts +216 -0
- package/dist/types_server-Dpsi0wpG.d.ts.map +1 -0
- package/dist/types_server-DzrIccyO.d.ts +216 -0
- package/dist/types_server-DzrIccyO.d.ts.map +1 -0
- package/dist/{types_server-Ch56y8L3.d.ts → types_server-TFo6SWDH.d.ts} +2 -2
- package/dist/{types_server-Ch56y8L3.d.ts.map → types_server-TFo6SWDH.d.ts.map} +1 -1
- package/package.json +7 -2
- package/dist/helper-zdJT5FUc.js.map +0 -1
- package/dist/index-CTyXKcq_.d.ts.map +0 -1
- package/dist/query-CbQLjeME.js.map +0 -1
- package/dist/schema-SKcIWHfo.js.map +0 -1
|
@@ -1,61 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
case "boolean":
|
|
12
|
-
case "bigint": return BigInt(value);
|
|
13
|
-
default: throw new Error(`Unsupported commitTs type: ${typeof value}`);
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
};
|
|
17
|
-
const identityCodec = {
|
|
18
|
-
encode: (value) => value,
|
|
19
|
-
decode: (value) => value
|
|
20
|
-
};
|
|
21
|
-
const numberCodec = {
|
|
22
|
-
encode: (value) => value,
|
|
23
|
-
decode: (value) => typeof value === "string" ? Number(value) : value
|
|
24
|
-
};
|
|
25
|
-
const booleanCodec = {
|
|
26
|
-
encode: (value) => value,
|
|
27
|
-
decode: (value) => {
|
|
28
|
-
if (typeof value === "boolean") return value;
|
|
29
|
-
if (typeof value === "number") return value !== 0;
|
|
30
|
-
if (typeof value === "string") {
|
|
31
|
-
const normalized = value.toLowerCase();
|
|
32
|
-
return normalized === "t" || normalized === "1" || normalized === "true";
|
|
33
|
-
}
|
|
34
|
-
return Boolean(value);
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
const dateCodec = {
|
|
38
|
-
encode: (value) => value,
|
|
39
|
-
decode: (value) => value instanceof Date ? value : new Date(value)
|
|
40
|
-
};
|
|
41
|
-
function unwrapZodType(field) {
|
|
42
|
-
let current = field;
|
|
43
|
-
while (current instanceof z.ZodOptional || current instanceof z.ZodNullable || current instanceof z.ZodDefault || current instanceof z.ZodCatch || current instanceof z.ZodReadonly) current = current._def.innerType;
|
|
44
|
-
return current;
|
|
45
|
-
}
|
|
46
|
-
function getDefaultCodec(field) {
|
|
47
|
-
if (field instanceof z.ZodNumber) return numberCodec;
|
|
48
|
-
if (field instanceof z.ZodBoolean) return booleanCodec;
|
|
49
|
-
if (field instanceof z.ZodDate) return dateCodec;
|
|
50
|
-
return identityCodec;
|
|
51
|
-
}
|
|
52
|
-
function normalizeCodec(codec, zodField) {
|
|
53
|
-
const fallback = getDefaultCodec(zodField);
|
|
54
|
-
if (!codec) return fallback;
|
|
55
|
-
return {
|
|
56
|
-
encode: codec.encode ?? fallback.encode,
|
|
57
|
-
decode: codec.decode ?? fallback.decode
|
|
58
|
-
};
|
|
1
|
+
import { n as normalizeCodec } from "./codec-BHAmGEIQ.js";
|
|
2
|
+
import { t as bytesEqual } from "./bytes-AuEkyxeU.js";
|
|
3
|
+
import { z as z$1 } from "zod";
|
|
4
|
+
//#region src/db/sqlcommenter.ts
|
|
5
|
+
function comment(input) {
|
|
6
|
+
if (!input) return "";
|
|
7
|
+
if (typeof input === "string") return `/*${input}*/`;
|
|
8
|
+
const entries = Object.entries(input).filter(([_, v]) => v != null);
|
|
9
|
+
if (entries.length === 0) return "";
|
|
10
|
+
return `/*${entries.map(([k, v]) => `${encodeURIComponent(k)}='${encodeURIComponent(v)}'`).sort().join(",")}*/`;
|
|
59
11
|
}
|
|
60
12
|
//#endregion
|
|
61
13
|
//#region src/db/query.ts
|
|
@@ -93,7 +45,8 @@ var SelectQueryBuilder = class SelectQueryBuilder {
|
|
|
93
45
|
offsetVal = null;
|
|
94
46
|
selectedProps = [];
|
|
95
47
|
computedFields = [];
|
|
96
|
-
|
|
48
|
+
commentStr = "";
|
|
49
|
+
constructor(ctx, model, filters = [], orderByClause = null, limitVal = null, offsetVal = null, selectedProps = [], computedFields = [], commentStr = "") {
|
|
97
50
|
this.ctx = ctx;
|
|
98
51
|
this.model = model;
|
|
99
52
|
this.filters = filters;
|
|
@@ -102,6 +55,7 @@ var SelectQueryBuilder = class SelectQueryBuilder {
|
|
|
102
55
|
this.offsetVal = offsetVal;
|
|
103
56
|
this.selectedProps = selectedProps;
|
|
104
57
|
this.computedFields = computedFields;
|
|
58
|
+
this.commentStr = commentStr;
|
|
105
59
|
}
|
|
106
60
|
getColumnName(key) {
|
|
107
61
|
return this.model.columns[key] ?? key;
|
|
@@ -142,7 +96,11 @@ var SelectQueryBuilder = class SelectQueryBuilder {
|
|
|
142
96
|
codec: normalizeCodec(config.codec, config.type)
|
|
143
97
|
};
|
|
144
98
|
this.computedFields.push(computed);
|
|
145
|
-
return new SelectQueryBuilder(this.ctx, this.model, this.filters, this.orderByClause, this.limitVal, this.offsetVal, [...this.selectedProps, config.field], this.computedFields);
|
|
99
|
+
return new SelectQueryBuilder(this.ctx, this.model, this.filters, this.orderByClause, this.limitVal, this.offsetVal, [...this.selectedProps, config.field], this.computedFields, this.commentStr);
|
|
100
|
+
}
|
|
101
|
+
comment(input) {
|
|
102
|
+
this.commentStr = comment(input);
|
|
103
|
+
return this;
|
|
146
104
|
}
|
|
147
105
|
async first() {
|
|
148
106
|
return (await this.limit(1).get())[0] ?? null;
|
|
@@ -170,7 +128,7 @@ var SelectQueryBuilder = class SelectQueryBuilder {
|
|
|
170
128
|
offset: null
|
|
171
129
|
};
|
|
172
130
|
const params = [];
|
|
173
|
-
const sql = `SELECT COUNT(*) as count FROM ${table} WHERE (${buildPredicateSql(predicate, params, this.ctx.db.sqlBuilder)})`;
|
|
131
|
+
const sql = `SELECT COUNT(*) as count FROM ${table} WHERE (${buildPredicateSql(predicate, params, this.ctx.db.sqlBuilder)})${this.commentStr ? " " + this.commentStr : ""}`;
|
|
174
132
|
const raw = (await this.ctx.db.query(sql, params)).rows[0]?.count ?? "0";
|
|
175
133
|
this.ctx.internalGetReadSet().push({
|
|
176
134
|
...querySpec,
|
|
@@ -194,12 +152,13 @@ var SelectQueryBuilder = class SelectQueryBuilder {
|
|
|
194
152
|
}
|
|
195
153
|
const computedCols = this.computedFields.map((f) => `${f.sql} as ${f.alias}`);
|
|
196
154
|
const selectPropsWithComputed = this.selectedProps.slice(0, this.selectedProps.length - this.computedFields.length);
|
|
197
|
-
|
|
155
|
+
let sql = `SELECT ${selectPropsWithComputed.length > 0 ? [
|
|
198
156
|
"id",
|
|
199
157
|
...selectPropsWithComputed.map((p) => this.getColumnName(p)),
|
|
200
158
|
...computedCols,
|
|
201
159
|
"commit_ts"
|
|
202
160
|
].join(", ") : "*"} FROM ${table} WHERE id = ${this.ctx.db.sqlBuilder.placeholder(1)}`;
|
|
161
|
+
if (this.commentStr) sql += ` ${this.commentStr}`;
|
|
203
162
|
const row = (await this.ctx.db.query(sql, [id])).rows[0] ?? null;
|
|
204
163
|
const expectedCommitTs = row ? BigInt(row.commit_ts) : null;
|
|
205
164
|
this.ctx.internalGetReadSet().push({
|
|
@@ -244,6 +203,7 @@ var SelectQueryBuilder = class SelectQueryBuilder {
|
|
|
244
203
|
if (this.orderByClause) sql += ` ORDER BY ${this.orderByClause}`;
|
|
245
204
|
if (this.limitVal !== null) sql += ` LIMIT ${this.limitVal}`;
|
|
246
205
|
if (this.offsetVal !== null) sql += ` OFFSET ${this.offsetVal}`;
|
|
206
|
+
if (this.commentStr) sql += ` ${this.commentStr}`;
|
|
247
207
|
const result = await this.ctx.db.query(sql, params);
|
|
248
208
|
this.ctx.internalGetReadSet().push({
|
|
249
209
|
...querySpec,
|
|
@@ -708,6 +668,6 @@ function jsonPathExists(val, path) {
|
|
|
708
668
|
return cur !== void 0;
|
|
709
669
|
}
|
|
710
670
|
//#endregion
|
|
711
|
-
export { jsonPathExtract as a,
|
|
671
|
+
export { jsonPathExtract as a, jsonPathExists as i, buildPredicateSql as n, matchesPredicate as o, jsonContains as r, QueryBuilder as t };
|
|
712
672
|
|
|
713
|
-
//# sourceMappingURL=query-
|
|
673
|
+
//# sourceMappingURL=query-Bh0RNxDz.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-Bh0RNxDz.js","names":["formatComment","z"],"sources":["../src/db/sqlcommenter.ts","../src/db/query.ts"],"sourcesContent":["export function comment(input: string | Record<string, string>): string {\n if (!input) return \"\";\n if (typeof input === \"string\") return `/*${input}*/`;\n const entries = Object.entries(input).filter(([_, v]) => v != null);\n if (entries.length === 0) return \"\";\n const pairs = entries\n .map(([k, v]) => `${encodeURIComponent(k)}='${encodeURIComponent(v)}'`)\n .sort();\n return `/*${pairs.join(\",\")}*/`;\n}\n","import { z, ZodRawShape } from \"zod\";\nimport { Predicate, LeafPredicate, CompareOperator, QuerySpec, RangeRead } from \"./types_db\";\nimport {\n ColumnCodec, ComputedCodec, ComputedDataType, ComputedField, ComputedFieldConfig,\n InferSchema, Model, OverrideField, Prettify, SchemaDefinition\n} from \"./schema\";\nimport { TxContext } from \"./context\";\nimport { normalizeCodec } from \"./codec\";\nimport { SqlBuilder } from \"./db\";\nimport { bytesEqual } from \"./bytes\";\nimport { comment as formatComment } from \"./sqlcommenter\";\n\n// Decoded value type of a schema field (codec-applied), narrowed to the\n// caller's key. `K` is not constrained to `keyof InferSchema<S>` so callers\n// can pass a key constrained to a subset (e.g. StringFieldKeys) without\n// TypeScript widening the resulting value type.\ntype FieldValue<S extends SchemaDefinition<string, ZodRawShape>, K> =\n K extends keyof InferSchema<S> ? InferSchema<S>[K] : never;\n\ntype OrderableValue = number | bigint | string | Date;\n\n// Keys whose decoded value is string-like (covers `string`, string literal\n// unions like enums, and `string | null | undefined`).\ntype StringFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = {\n [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends string ? K : never;\n}[keyof InferSchema<S>];\n\n// Keys whose decoded value supports SQL ordering (gt/gte/lt/lte/between).\ntype OrderableFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = {\n [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends OrderableValue ? K : never;\n}[keyof InferSchema<S>];\n\n// Keys whose decoded value is shaped like a JSON/JSONB column (object/array/unknown).\n// Used to constrain jsonContains / jsonContainedBy / jsonHasKey / jsonArrayContains\n// so they can't be invoked on plain scalar fields.\ntype JsonFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = {\n [K in keyof InferSchema<S>]:\n NonNullable<InferSchema<S>[K]> extends OrderableValue ? never :\n NonNullable<InferSchema<S>[K]> extends boolean ? never :\n NonNullable<InferSchema<S>[K]> extends (object | unknown[]) ? K :\n unknown extends NonNullable<InferSchema<S>[K]> ? K :\n never;\n}[keyof InferSchema<S>];\n\nexport interface JsonOpOptions {\n /**\n * Skip client-side preparation of the value (no JSON-stringify, no key\n * escaping). The caller is responsible for the exact form the dialect\n * expects: a JSON path string for jsonHasKey, a JSON-encoded string for\n * the contains family.\n */\n raw?: true;\n}\n\nexport interface JsonContainsOptions extends JsonOpOptions {\n /**\n * Sub-path into the target JSON to scope the check to. `string` is a\n * single literal top-level key; `string[]` is a nested literal-key path\n * compiled to `$.\"a\".\"b\"`. Mutually exclusive with `pathRaw`.\n */\n path?: string | string[];\n /**\n * Raw jsonpath expression used verbatim by the dialect (PG `jsonpath`,\n * MySQL JSON path). Mutually exclusive with `path`.\n */\n pathRaw?: string;\n}\n\nexport interface JsonHasKeyMultiOptions extends JsonOpOptions {\n /** Required for the multi-path overload — chooses any vs every. */\n mode: \"one\" | \"all\";\n}\n\n// Escape and join a key path into a JSON path expression usable by both\n// PG (`jsonb_path_exists`) and MySQL (`JSON_CONTAINS_PATH`):\n// [\"a\", \"b.c\"] → `$.\"a\".\"b.c\"`\nfunction jsonKeysToPath(keys: string[]): string {\n let out = \"$\";\n for (const k of keys) {\n out += `.\"${k.replace(/\"/g, '\\\\\"')}\"`;\n }\n return out;\n}\n\n// Resolve the `path` / `pathRaw` option pair down to a single jsonpath\n// expression. Returns a string in `$.\"...\"` form for structured `path`,\n// or the caller's `pathRaw` verbatim. Returns `undefined` when neither is\n// set. Throws when both are supplied.\nfunction resolveJsonPath(opts: JsonContainsOptions | undefined): string | undefined {\n if (opts?.path !== undefined && opts?.pathRaw !== undefined) {\n throw new Error(\"jsonContains: pass either `path` or `pathRaw`, not both\");\n }\n if (opts?.pathRaw !== undefined) return opts.pathRaw;\n if (opts?.path !== undefined) {\n const arr = Array.isArray(opts.path) ? opts.path : [opts.path];\n return jsonKeysToPath(arr);\n }\n return undefined;\n}\n\nexport class QueryBuilder<S extends SchemaDefinition<string, ZodRawShape>> {\n constructor(\n protected ctx: TxContext,\n protected model: Model\n ) { }\n\n protected getColumnName(key: string): string {\n return this.model.columns[key] ?? key;\n }\n\n select(): SelectQueryBuilder<S, keyof InferSchema<S>>;\n select<K extends keyof InferSchema<S>>(...columns: K[]): SelectQueryBuilder<S, K>;\n select<K extends keyof InferSchema<S>>(...columns: K[]): SelectQueryBuilder<S, K> {\n const selectedProps = (columns.length > 0 ? columns : Object.keys(this.model.columns)) as K[];\n return new SelectQueryBuilder<S, K>(this.ctx, this.model, [], null, null, null, selectedProps);\n }\n}\n\nexport type IdAndCommitTs = { id: string; commitTs: bigint };\n\n// Row type returned by `.get()`, `.find()`, `.first()`. Selected schema keys\n// plus the always-included id/commitTs and any computed fields, flattened so\n// the IDE renders a plain object literal instead of an intersection chain.\ntype SelectRow<\n S extends SchemaDefinition<string, ZodRawShape>,\n K extends keyof InferSchema<S>,\n C extends Record<string, unknown>,\n> = Prettify<Pick<InferSchema<S>, Extract<K | \"id\" | \"commitTs\", keyof InferSchema<S>>> & C>;\n\nclass SelectQueryBuilder<\n S extends SchemaDefinition<string, ZodRawShape>,\n K extends keyof InferSchema<S> = never,\n C extends Record<string, unknown> = {},\n> {\n private filters: ((fb: FilterBuilder<S>) => void)[] = [];\n private orderByClause: string | null = null;\n private limitVal: number | null = null;\n private offsetVal: number | null = null;\n private selectedProps: (keyof InferSchema<S>)[] = [];\n private computedFields: ComputedField[] = [];\n private commentStr: string = \"\";\n\n constructor(\n private ctx: TxContext,\n private model: Model,\n filters: ((fb: FilterBuilder<S>) => void)[] = [],\n orderByClause: string | null = null,\n limitVal: number | null = null,\n offsetVal: number | null = null,\n selectedProps: (keyof InferSchema<S>)[] = [],\n computedFields: ComputedField[] = [],\n commentStr: string = \"\",\n ) {\n this.filters = filters;\n this.orderByClause = orderByClause;\n this.limitVal = limitVal;\n this.offsetVal = offsetVal;\n this.selectedProps = selectedProps;\n this.computedFields = computedFields;\n this.commentStr = commentStr;\n }\n\n private getColumnName(key: string): string {\n return this.model.columns[key] ?? key;\n }\n\n private getPropertyName(column: string): string {\n return this.model.reverseColumns[column] ?? this.computedFields.find(f => f.alias === column)?.field ?? column;\n }\n\n private mapRowToSchema(row: Record<string, any>): Record<string, any> {\n const result: Record<string, any> = {};\n for (const [col, value] of Object.entries(row)) {\n const prop = this.getPropertyName(col)\n const codec = this.model.codecs[prop] ?? this.computedFields.find((f) => f.alias === col)?.codec;\n result[prop] = codec?.decode && value !== undefined && value !== null ? codec.decode(value) : value;\n }\n return result;\n }\n\n where(filterFn: (fb: FilterBuilder<S>) => void): SelectQueryBuilder<S, K, C> {\n this.filters.push(filterFn);\n return this;\n }\n\n orderBy(\n column: keyof InferSchema<S> | keyof C,\n direction: \"asc\" | \"desc\" = \"asc\",\n ): SelectQueryBuilder<S, K, C> {\n this.orderByClause = `${this.getColumnName(column as string)} ${direction}`;\n return this\n }\n\n limit(n: number): SelectQueryBuilder<S, K, C> {\n this.limitVal = n;\n return this;\n }\n\n offset(n: number): SelectQueryBuilder<S, K, C> {\n this.offsetVal = n;\n return this;\n }\n computed<\n TField extends string,\n TZodType extends z.ZodTypeAny | undefined = undefined,\n TDecode extends (value: any) => any = (value: unknown) => unknown,\n >(\n config: ComputedFieldConfig<TField, ReturnType<TDecode>, Parameters<TDecode>[0], TZodType> & {\n codec: {\n decode: TDecode;\n encode?: (value: ReturnType<TDecode>) => Parameters<TDecode>[0];\n };\n }\n ): SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<ComputedCodec<ReturnType<TDecode>, Parameters<TDecode>[0]>, TZodType>>>;\n computed<\n TField extends string,\n TZodType extends z.ZodTypeAny | undefined = undefined,\n >(\n config: ComputedFieldConfig<TField, unknown, unknown, TZodType> & {\n codec?: undefined;\n }\n ): SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<undefined, TZodType>>>;\n computed<\n TField extends string,\n TZodType extends z.ZodTypeAny | undefined = undefined,\n TCodec extends ComputedCodec<any, any> | undefined = undefined,\n >(\n config: ComputedFieldConfig<TField, unknown, unknown, TZodType> & {\n codec?: TCodec;\n }\n ): SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<TCodec, TZodType>>> {\n const computed: ComputedField = {\n field: config.field,\n sql: config.sql,\n alias: config.alias ?? config.field,\n codec: normalizeCodec(config.codec, config.type),\n };\n this.computedFields.push(computed);\n return new SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<TCodec, TZodType>>>(\n this.ctx, this.model, this.filters, this.orderByClause,\n this.limitVal, this.offsetVal, [...this.selectedProps, config.field], this.computedFields,\n this.commentStr,\n );\n }\n\n comment(input: string | Record<string, string>): SelectQueryBuilder<S, K, C> {\n this.commentStr = formatComment(input);\n return this;\n }\n\n async first(): Promise<SelectRow<S, K, C> | null> {\n const rows = await this.limit(1).get();\n return (rows[0] ?? null) as any;\n }\n\n async exists(): Promise<boolean> {\n return await this.count() > 0;\n }\n\n private static defaultCountType = z.coerce.number();\n\n async count(): Promise<number>;\n async count<T extends z.ZodType>(parser: T): Promise<z.output<T>>;\n async count<T extends z.ZodType>(parser?: T): Promise<z.output<T>> {\n const predicate = this.buildPredicate() ?? { kind: \"leaf\" as const, column: \"1\", operator: \"=\" as const, value: \"1\" };\n const table = this.model.table;\n\n // Build query spec for read tracking (without totalTs)\n const querySpec: RangeRead = {\n kind: \"range\",\n table: table,\n tableId: this.model.tableId,\n predicate: predicate,\n columns: [\"count\"],\n orderBy: null,\n limit: null,\n offset: null,\n };\n\n // Execute query\n const params: unknown[] = [];\n const whereSql = buildPredicateSql(predicate, params, this.ctx.db.sqlBuilder);\n\n const sql = `SELECT COUNT(*) as count FROM ${table} WHERE (${whereSql})${this.commentStr ? \" \" + this.commentStr : \"\"}`;\n const result = await this.ctx.db.query(sql, params);\n const raw = result.rows[0]?.count ?? \"0\";\n\n // Record read with totalTs for OCC validation\n this.ctx.internalGetReadSet().push({\n ...querySpec,\n tableId: this.model.tableId,\n });\n\n if (parser) {\n return parser.parse(raw) as z.output<T>;\n } else {\n return SelectQueryBuilder.defaultCountType.parse(raw) as z.output<T>;\n }\n }\n\n async find(id: string): Promise<SelectRow<S, K, C> | null> {\n if (this.filters.length > 0) {\n throw new Error(`Cannot use find() after where() - find() is meant for primary key lookups without additional filters`);\n }\n\n const table = this.model.table;\n const tableId = this.model.tableId;\n\n // Check pending writes first\n const pendingWrite = this.ctx.internalGetWriteSet().find(w => w.id === id && bytesEqual(w.tableId, tableId));\n\n if (pendingWrite) {\n if (pendingWrite.op === \"delete\") {\n // Don't cache pending writes, just return\n return null;\n }\n const row = this.mapRowToSchema({ ...pendingWrite.data, id, commit_ts: this.ctx.beginTs });\n return row as SelectRow<S, K, C>;\n }\n\n const computedCols = this.computedFields.map(f => `${f.sql} as ${f.alias}`);\n const selectPropsWithComputed = this.selectedProps.slice(0, this.selectedProps.length - this.computedFields.length);\n const selectCols = selectPropsWithComputed.length > 0\n ? [\"id\", ...selectPropsWithComputed.map(p => this.getColumnName(p as string)), ...computedCols, \"commit_ts\"].join(\", \")\n : \"*\";\n let sql = `SELECT ${selectCols} FROM ${table} WHERE id = ${this.ctx.db.sqlBuilder.placeholder(1)}`;\n if (this.commentStr) sql += ` ${this.commentStr}`;\n const result = await this.ctx.db.query(sql, [id]);\n\n const row = result.rows[0] ?? null;\n\n // Capture commit_ts as the per-row OCC fingerprint. `null` means\n // \"no row at read time\" — a later concurrent insert with this id\n // becomes a conflict at commit time.\n const expectedCommitTs: bigint | null = row ? BigInt(row.commit_ts) : null;\n this.ctx.internalGetReadSet().push({\n kind: \"point\",\n table,\n tableId,\n id,\n expectedCommitTs,\n });\n\n const mappedRow = row ? this.mapRowToSchema(row) as SelectRow<S, K, C> : null;\n\n return mappedRow;\n }\n\n async get(): Promise<SelectRow<S, K, C>[]> {\n const predicate = this.buildPredicate() ?? { kind: \"leaf\" as const, column: \"1\", operator: \"=\" as const, value: \"1\" };\n const table = this.model.table;\n const tableId = this.model.tableId;\n\n // Build query spec for read tracking (without totalTs)\n const querySpec: RangeRead = {\n kind: \"range\",\n table: table,\n tableId: tableId,\n predicate: predicate,\n columns: this.selectedProps as string[],\n orderBy: this.orderByClause,\n limit: this.limitVal,\n offset: this.offsetVal,\n };\n\n // Execute query\n const params: unknown[] = [];\n const whereSql = buildPredicateSql(predicate, params, this.ctx.db.sqlBuilder);\n\n const computedCols = this.computedFields.map(f => `${f.sql} as ${f.alias}`);\n const selectPropsWithComputed = this.selectedProps.slice(0, this.selectedProps.length - this.computedFields.length);\n const selectColsNames = selectPropsWithComputed.length > 0\n ? [\"id\", ...selectPropsWithComputed.map(p => this.getColumnName(p as string)), ...computedCols, \"commit_ts\"]\n : \"*\";\n const selectCols = Array.from(new Set(selectColsNames).values()).join(\", \")\n let sql = `SELECT ${selectCols} FROM ${table} WHERE (${whereSql})`;\n\n if (this.orderByClause) {\n sql += ` ORDER BY ${this.orderByClause}`;\n }\n if (this.limitVal !== null) {\n sql += ` LIMIT ${this.limitVal}`;\n }\n if (this.offsetVal !== null) {\n sql += ` OFFSET ${this.offsetVal}`;\n }\n if (this.commentStr) sql += ` ${this.commentStr}`;\n\n const result = await this.ctx.db.query(sql, params);\n\n // Record read with totalTs for OCC validation\n this.ctx.internalGetReadSet().push({\n ...querySpec,\n tableId: tableId,\n });\n\n const rows = result.rows.map(row => this.mapRowToSchema(row)) as SelectRow<S, K, C>[];\n\n return rows;\n }\n\n private buildPredicate(): Predicate | null {\n if (this.filters.length === 0) return null;\n\n const predicates: Predicate[] = [];\n const fb = new FilterBuilder<S>(this.model.columns, this.model.codecs);\n\n for (const filterFn of this.filters) {\n filterFn(fb);\n if (fb.predicates.length > 0) {\n const hasOr = fb.predicates.some(p => p.kind === \"or\");\n if (hasOr) {\n predicates.push(...fb.predicates);\n } else {\n predicates.push({ kind: \"and\", children: fb.predicates });\n }\n fb.predicates = [];\n }\n }\n\n if (predicates.length === 0) return null;\n if (predicates.length === 1) return predicates[0] ?? null;\n return { kind: \"and\", children: predicates };\n }\n}\n\n// ─── Filter Builder ──────────────────────────────────────────────────────────────\n\nclass FilterBuilder<S extends SchemaDefinition<string, ZodRawShape>> {\n predicates: Predicate[] = [];\n\n constructor(\n private columns: Record<string, string>,\n private codecs: Record<string, ColumnCodec<unknown, unknown>>\n ) { }\n\n private add(column: string, operator: CompareOperator, value: unknown, value2?: unknown, raw?: boolean): void {\n const leaf: LeafPredicate = { kind: \"leaf\", column, operator: operator as any, value, value2 };\n if (raw) leaf.raw = true;\n this.predicates.push(leaf);\n }\n\n private addJsonContains(operator: CompareOperator, key: string, value: unknown, opts: JsonContainsOptions | undefined): void {\n const col = this.getColumnName(key);\n const leaf: LeafPredicate = {\n kind: \"leaf\",\n column: col,\n operator: operator as any,\n value: this.encodeJson(value, opts?.raw),\n };\n if (opts?.raw) leaf.raw = true;\n const path = resolveJsonPath(opts);\n if (path !== undefined) leaf.path = path;\n this.predicates.push(leaf);\n }\n\n private getColumnName(key: string): string {\n return this.columns[key] ?? key;\n }\n\n private encode(key: string, value: unknown): unknown {\n const codec = this.codecs[key];\n if (!codec?.encode || value === undefined || value === null) return value;\n return codec.encode(value);\n }\n\n private encodeJson(value: unknown, raw: boolean | undefined): unknown {\n if (value === null || value === undefined) return value;\n // raw=true: caller has already produced the dialect-native form\n // (typically a JSON-encoded string or a path expression). Pass through.\n if (raw) return value;\n // Otherwise serialize the JS value to a JSON literal so the SQL\n // emitter can hand a single text param to the driver.\n return JSON.stringify(value);\n }\n\n eq<K extends keyof InferSchema<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"=\", this.encode(key as string, value));\n return this;\n }\n\n neq<K extends keyof InferSchema<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"!=\", this.encode(key as string, value));\n return this;\n }\n\n gt<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \">\", this.encode(key as string, value));\n return this;\n }\n\n gte<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \">=\", this.encode(key as string, value));\n return this;\n }\n\n lt<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"<\", this.encode(key as string, value));\n return this;\n }\n\n lte<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"<=\", this.encode(key as string, value));\n return this;\n }\n\n like<K extends StringFieldKeys<S>>(key: K, pattern: string): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"like\", this.encode(key as string, pattern));\n return this;\n }\n\n ilike<K extends StringFieldKeys<S>>(key: K, pattern: string): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"ilike\", this.encode(key as string, pattern));\n return this;\n }\n\n contains<K extends StringFieldKeys<S>>(key: K, value: string): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"contains\", this.encode(key as string, value));\n return this;\n }\n\n icontains<K extends StringFieldKeys<S>>(key: K, value: string): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"icontains\", this.encode(key as string, value));\n return this;\n }\n\n /**\n * JSON containment. Targets a JSON/JSONB column and asserts the document\n * contains the given candidate (object-key subset for objects,\n * element-subset for arrays — see dialect-specific docs for edge cases).\n * Pass `{ raw: true }` if `value` is already a JSON-encoded string.\n * Pass `{ path: ... }` to scope the check to a sub-document of the\n * target (jsonb_path_query_first on PG, JSON_CONTAINS path arg on MySQL).\n */\n jsonContains<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S> {\n this.addJsonContains(\"jsonContains\", key as string, value, opts);\n return this;\n }\n\n /** Inverse of {@link jsonContains}: column is contained in the given value. */\n jsonContainedBy<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S> {\n this.addJsonContains(\"jsonContainedBy\", key as string, value, opts);\n return this;\n }\n\n /**\n * Key/path existence check on a JSON column.\n *\n * - String form (top-level key): `jsonHasKey(\"meta\", \"color\")`. On PG\n * also matches when the column is a string array and `value` is one of\n * its elements (PG `?` semantics); MySQL stays strict to object keys.\n * - Array form (nested path): `jsonHasKey(\"meta\", [\"a\", \"b\"])` compiles\n * to a path expression `$.\"a\".\"b\"` on both dialects.\n * - Raw form: `jsonHasKey(\"meta\", \"$.foo[*]\", { raw: true })` passes the\n * string through as a dialect path expression (PG `jsonb_path_exists`\n * jsonpath, MySQL `JSON_CONTAINS_PATH`). Caller owns the syntax.\n * - Multi-path form: `jsonHasKey(\"meta\", [[\"a\",\"b\"], \"color\"], { mode: \"all\" })`\n * compiles each entry to a jsonpath and emits PG OR/AND of\n * `jsonb_path_exists` or MySQL `JSON_CONTAINS_PATH('all', ...)`.\n */\n jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string): FilterBuilder<S>;\n jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string[]): FilterBuilder<S>;\n jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string, opts: { raw: true }): FilterBuilder<S>;\n jsonHasKey<K extends JsonFieldKeys<S>>(key: K, paths: (string | string[])[], opts: JsonHasKeyMultiOptions): FilterBuilder<S>;\n jsonHasKey<K extends JsonFieldKeys<S>>(key: K, paths: string[], opts: JsonHasKeyMultiOptions & { raw: true }): FilterBuilder<S>;\n jsonHasKey<K extends JsonFieldKeys<S>>(\n key: K,\n value: string | string[] | (string | string[])[],\n opts?: JsonOpOptions & { mode?: \"one\" | \"all\" }\n ): FilterBuilder<S> {\n const col = this.getColumnName(key as string);\n // Multi-path mode: array of (string|string[]) entries with explicit mode.\n if (opts?.mode && Array.isArray(value)) {\n const paths = (value as (string | string[])[]).map((p) =>\n opts.raw && typeof p === \"string\" ? p : jsonKeysToPath(Array.isArray(p) ? p : [p])\n );\n const leaf: LeafPredicate = {\n kind: \"leaf\",\n column: col,\n operator: \"jsonHasKey\",\n value: paths,\n mode: opts.mode,\n };\n this.predicates.push(leaf);\n return this;\n }\n // Single-key/path mode.\n if (Array.isArray(value)) {\n this.add(col, \"jsonHasKey\", jsonKeysToPath(value as string[]), undefined, true);\n } else if (opts?.raw) {\n this.add(col, \"jsonHasKey\", value, undefined, true);\n } else {\n this.add(col, \"jsonHasKey\", value, undefined, false);\n }\n return this;\n }\n\n /**\n * Array element containment: target column is a JSON array; the given\n * `value` (any JSON-encodable type) must appear as one of its elements.\n * Pass `{ raw: true }` if `value` is already a JSON-encoded string.\n * Pass `{ path: ... }` to scope the check to a sub-array of the column.\n */\n jsonArrayContains<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S> {\n this.addJsonContains(\"jsonArrayContains\", key as string, value, opts);\n return this;\n }\n\n between<K extends OrderableFieldKeys<S>>(key: K, lo: FieldValue<S, K>, hi: FieldValue<S, K>): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"between\", this.encode(key as string, lo), this.encode(key as string, hi));\n return this;\n }\n\n isNull<K extends keyof InferSchema<S>>(key: K): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"isNull\", null);\n return this;\n }\n\n notNull<K extends keyof InferSchema<S>>(key: K): FilterBuilder<S> {\n this.add(this.getColumnName(key as string), \"isNotNull\", null);\n return this;\n }\n\n /**\n * Compose an OR clause. Each callback fills a fresh sub-FilterBuilder\n * with predicates that are AND-ed together within that branch; the\n * branches themselves are OR-ed. Example:\n * f.or([\n * b => b.eq(\"tag\", \"a\"),\n * b => b.eq(\"tag\", \"b\").gt(\"qty\", 3), // (tag=b AND qty>3)\n * ])\n * produces (tag=a) OR (tag=b AND qty>3).\n */\n or(branches: ((fb: FilterBuilder<S>) => void)[]): FilterBuilder<S> {\n const children: Predicate[] = [];\n for (const fn of branches) {\n const sub = new FilterBuilder<S>(this.columns, this.codecs);\n fn(sub);\n if (sub.predicates.length === 1) {\n children.push(sub.predicates[0]);\n } else if (sub.predicates.length > 1) {\n children.push({ kind: \"and\", children: sub.predicates });\n }\n }\n if (children.length > 0) {\n this.predicates.push({ kind: \"or\", children });\n }\n return this;\n }\n}\n\n\nexport function buildPredicateSql(predicate: Predicate, params: unknown[], sql: SqlBuilder): string {\n switch (predicate.kind) {\n case \"and\": {\n const parts = predicate.children.map((c) => buildPredicateSql(c, params, sql));\n return `(${parts.join(\" AND \")})`;\n }\n case \"or\": {\n const parts = predicate.children.map((c) => buildPredicateSql(c, params, sql));\n return `(${parts.join(\" OR \")})`;\n }\n case \"leaf\": {\n return buildLeafSql(predicate, params, sql);\n }\n }\n}\n\nfunction buildLeafSql(leaf: LeafPredicate, params: unknown[], sql: SqlBuilder): string {\n const col = leaf.column;\n switch (leaf.operator) {\n case \"=\": case \"!=\": case \">\": case \">=\": case \"<\": case \"<=\": {\n params.push(leaf.value);\n return `${col} ${leaf.operator} ${sql.placeholder(params.length)}`;\n }\n case \"between\": {\n params.push(leaf.value);\n const p1 = sql.placeholder(params.length);\n params.push(leaf.value2);\n const p2 = sql.placeholder(params.length);\n return `${col} BETWEEN ${p1} AND ${p2}`;\n }\n case \"like\": {\n params.push(leaf.value);\n return `${col} LIKE ${sql.placeholder(params.length)}`;\n }\n case \"ilike\": {\n params.push(leaf.value);\n return sql.ilike(col, params.length);\n }\n case \"contains\": {\n params.push(`%${leaf.value}%`);\n return `${col} LIKE ${sql.placeholder(params.length)}`;\n }\n case \"icontains\": {\n params.push(`%${leaf.value}%`);\n return sql.icontains(col, params.length);\n }\n case \"jsonContains\": {\n params.push(leaf.value);\n const valIdx = params.length;\n let pathIndex: number | undefined;\n if (leaf.path !== undefined) {\n params.push(leaf.path);\n pathIndex = params.length;\n }\n return sql.jsonContains(col, valIdx, { raw: leaf.raw, pathIndex });\n }\n case \"jsonContainedBy\": {\n params.push(leaf.value);\n const valIdx = params.length;\n let pathIndex: number | undefined;\n if (leaf.path !== undefined) {\n params.push(leaf.path);\n pathIndex = params.length;\n }\n return sql.jsonContainedBy(col, valIdx, { raw: leaf.raw, pathIndex });\n }\n case \"jsonHasKey\": {\n if (leaf.mode && Array.isArray(leaf.value)) {\n const paths = leaf.value as string[];\n const startIdx = params.length + 1;\n for (const p of paths) params.push(p);\n return sql.jsonHasKey(col, startIdx, {\n raw: true,\n mode: leaf.mode,\n pathCount: paths.length,\n });\n }\n params.push(leaf.value);\n return sql.jsonHasKey(col, params.length, { raw: leaf.raw });\n }\n case \"jsonArrayContains\": {\n params.push(leaf.value);\n const valIdx = params.length;\n let pathIndex: number | undefined;\n if (leaf.path !== undefined) {\n params.push(leaf.path);\n pathIndex = params.length;\n }\n return sql.jsonArrayContains(col, valIdx, { raw: leaf.raw, pathIndex });\n }\n case \"isNull\": return `${col} IS NULL`;\n case \"isNotNull\": return `${col} IS NOT NULL`;\n }\n}\n\nexport function matchesPredicate(row: Record<string, unknown>, predicate: Predicate): boolean {\n switch (predicate.kind) {\n case \"and\": return predicate.children.every((c) => matchesPredicate(row, c));\n case \"or\": return predicate.children.some((c) => matchesPredicate(row, c));\n case \"leaf\": return matchesLeaf(row, predicate);\n }\n}\n\nfunction matchesLeaf(row: Record<string, unknown>, leaf: LeafPredicate): boolean {\n const val = row[leaf.column];\n\n switch (leaf.operator) {\n case \"=\": return val === leaf.value;\n case \"!=\": return val !== leaf.value;\n case \">\": return (val as number) > (leaf.value as number);\n case \">=\": return (val as number) >= (leaf.value as number);\n case \"<\": return (val as number) < (leaf.value as number);\n case \"<=\": return (val as number) <= (leaf.value as number);\n\n case \"between\":\n return (val as number) >= (leaf.value as number) &&\n (val as number) <= (leaf.value2 as number);\n\n case \"like\":\n case \"contains\":\n case \"ilike\":\n case \"icontains\": {\n if (typeof val !== \"string\" || typeof leaf.value !== \"string\") return false;\n const haystack = (leaf.operator === \"ilike\" || leaf.operator === \"icontains\")\n ? (val as string).toLowerCase()\n : val as string;\n const raw = leaf.value as string;\n const needle = (leaf.operator === \"ilike\" || leaf.operator === \"icontains\")\n ? raw.toLowerCase()\n : raw;\n const pattern = (leaf.operator === \"contains\" || leaf.operator === \"icontains\")\n ? `%${needle}%`\n : needle;\n const regex = new RegExp(\n \"^\" + pattern.replace(/%/g, \".*\").replace(/_/g, \".\") + \"$\"\n );\n return regex.test(haystack);\n }\n\n case \"jsonContains\": {\n const candidate = decodeJsonLeafValue(leaf);\n const target = leaf.path !== undefined ? jsonPathExtract(val, leaf.path) : val;\n if (target === undefined) return false;\n return jsonContains(target, candidate);\n }\n\n case \"jsonContainedBy\": {\n const candidate = decodeJsonLeafValue(leaf);\n const target = leaf.path !== undefined ? jsonPathExtract(val, leaf.path) : val;\n if (target === undefined) return false;\n return jsonContains(candidate, target);\n }\n\n case \"jsonHasKey\": {\n if (leaf.mode && Array.isArray(leaf.value)) {\n const paths = leaf.value as string[];\n if (paths.length === 0) return false;\n return leaf.mode === \"all\"\n ? paths.every((p) => jsonPathExists(val, p))\n : paths.some((p) => jsonPathExists(val, p));\n }\n if (leaf.raw) {\n return jsonPathExists(val, leaf.value as string);\n }\n const key = leaf.value as string;\n if (val === null || typeof val !== \"object\") return false;\n if (Array.isArray(val)) return (val as unknown[]).includes(key);\n return key in (val as object);\n }\n\n case \"jsonArrayContains\": {\n const candidate = decodeJsonLeafValue(leaf);\n const target = leaf.path !== undefined ? jsonPathExtract(val, leaf.path) : val;\n if (!Array.isArray(target)) return false;\n return (target as unknown[]).some((el) => jsonContains(el, candidate));\n }\n\n case \"isNull\":\n return val === null;\n\n case \"isNotNull\":\n return val !== null;\n\n default:\n return false;\n }\n}\n\n// When raw=true the leaf.value is a JSON-encoded string; decode for in-memory\n// comparison. Otherwise the value is the original JS value as passed.\nfunction decodeJsonLeafValue(leaf: LeafPredicate): unknown {\n if (!leaf.raw) return leaf.value;\n if (typeof leaf.value !== \"string\") return leaf.value;\n try { return JSON.parse(leaf.value); } catch { return leaf.value; }\n}\n\n// PG `@>` / MySQL `JSON_CONTAINS` semantics. Recursive containment:\n// - scalars: strict equality\n// - object: every candidate key matches target's value recursively\n// - array: every candidate element is contained in some target element\n// - scalar candidate vs array target: candidate equals some element\nexport function jsonContains(target: unknown, candidate: unknown): boolean {\n if (candidate === target) return true;\n if (target === null || candidate === null) return target === candidate;\n if (target === undefined || candidate === undefined) return false;\n\n const tArr = Array.isArray(target);\n const cArr = Array.isArray(candidate);\n const tObj = !tArr && typeof target === \"object\";\n const cObj = !cArr && typeof candidate === \"object\";\n\n // Scalar candidate in array target.\n if (!cArr && !cObj && tArr) {\n return (target as unknown[]).some((el) => jsonContains(el, candidate));\n }\n // Both arrays: every candidate element matches some target element.\n if (cArr && tArr) {\n const t = target as unknown[];\n return (candidate as unknown[]).every((c) => t.some((el) => jsonContains(el, c)));\n }\n // Both objects.\n if (cObj && tObj) {\n const t = target as Record<string, unknown>;\n const c = candidate as Record<string, unknown>;\n for (const k of Object.keys(c)) {\n if (!(k in t)) return false;\n if (!jsonContains(t[k], c[k])) return false;\n }\n return true;\n }\n return false;\n}\n\n// Walk the JSON path and return the value at it, or `undefined` if any\n// segment is missing or unresolvable. Same syntax subset as\n// {@link jsonPathExists}.\nexport function jsonPathExtract(val: unknown, path: string): unknown {\n let p = path;\n if (p.startsWith(\"$\")) p = p.slice(1);\n let cur: unknown = val;\n while (p.length > 0) {\n if (p.startsWith('.\"')) {\n let end = 2;\n while (end < p.length) {\n if (p[end] === \"\\\\\" && end + 1 < p.length) { end += 2; continue; }\n if (p[end] === '\"') break;\n end++;\n }\n if (end >= p.length) return undefined;\n const key = p.slice(2, end).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n if (cur === null || typeof cur !== \"object\" || Array.isArray(cur)) return undefined;\n if (!(key in (cur as object))) return undefined;\n cur = (cur as Record<string, unknown>)[key];\n p = p.slice(end + 1);\n } else if (p.startsWith(\".\")) {\n const m = p.slice(1).match(/^([^.[]+)/);\n if (!m) return undefined;\n const key = m[1];\n if (cur === null || typeof cur !== \"object\" || Array.isArray(cur)) return undefined;\n if (!(key in (cur as object))) return undefined;\n cur = (cur as Record<string, unknown>)[key];\n p = p.slice(1 + key.length);\n } else if (p.startsWith(\"[\")) {\n const end = p.indexOf(\"]\");\n if (end === -1) return undefined;\n const idx = parseInt(p.slice(1, end), 10);\n if (!Array.isArray(cur) || idx < 0 || idx >= (cur as unknown[]).length) return undefined;\n cur = (cur as unknown[])[idx];\n p = p.slice(end + 1);\n } else {\n return undefined;\n }\n }\n return cur;\n}\n\n// Best-effort JSON path evaluator for the in-memory predicate match.\n// Supports the path syntax this module emits (`$.\"key\".\"nested\"`) plus the\n// common shorthands `$.key` and `$.key[0]`. Anything more exotic (filters,\n// wildcards) returns false — DB will still evaluate it correctly server-side.\nexport function jsonPathExists(val: unknown, path: string): boolean {\n let p = path;\n if (p.startsWith(\"$\")) p = p.slice(1);\n let cur: unknown = val;\n while (p.length > 0) {\n if (p.startsWith('.\"')) {\n let end = 2;\n while (end < p.length) {\n if (p[end] === \"\\\\\" && end + 1 < p.length) { end += 2; continue; }\n if (p[end] === '\"') break;\n end++;\n }\n if (end >= p.length) return false;\n const key = p.slice(2, end).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n if (cur === null || typeof cur !== \"object\" || Array.isArray(cur)) return false;\n if (!(key in (cur as object))) return false;\n cur = (cur as Record<string, unknown>)[key];\n p = p.slice(end + 1);\n } else if (p.startsWith(\".\")) {\n const m = p.slice(1).match(/^([^.[]+)/);\n if (!m) return false;\n const key = m[1];\n if (cur === null || typeof cur !== \"object\" || Array.isArray(cur)) return false;\n if (!(key in (cur as object))) return false;\n cur = (cur as Record<string, unknown>)[key];\n p = p.slice(1 + key.length);\n } else if (p.startsWith(\"[\")) {\n const end = p.indexOf(\"]\");\n if (end === -1) return false;\n const idx = parseInt(p.slice(1, end), 10);\n if (!Array.isArray(cur) || idx < 0 || idx >= (cur as unknown[]).length) return false;\n cur = (cur as unknown[])[idx];\n p = p.slice(end + 1);\n } else {\n return false;\n }\n }\n return cur !== undefined;\n}\n"],"mappings":";;;;AAAA,SAAgB,QAAQ,OAAgD;CACpE,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,OAAO,UAAU,UAAU,OAAO,KAAK,MAAM;CACjD,MAAM,UAAU,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,CAAC,GAAG,OAAO,KAAK,IAAI;CAClE,IAAI,QAAQ,WAAW,GAAG,OAAO;CAIjC,OAAO,KAHO,QACT,KAAK,CAAC,GAAG,OAAO,GAAG,mBAAmB,CAAC,EAAE,IAAI,mBAAmB,CAAC,EAAE,EAAE,CAAC,CACtE,KACW,CAAC,CAAC,KAAK,GAAG,EAAE;AAChC;;;ACmEA,SAAS,eAAe,MAAwB;CAC5C,IAAI,MAAM;CACV,KAAK,MAAM,KAAK,M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,OAAO;EACvB,MAAM,MAAM,SAAS,EAAE,MAAM,GAAG,GAAG,GAAG,EAAE;EACxC,IAAI,CAAC,MAAM,QAAQ,GAAG,KAAK,MAAM,KAAK,OAAQ,IAAkB,QAAQ,OAAO;EAC/E,MAAO,IAAkB;EACzB,IAAI,EAAE,MAAM,MAAM,CAAC;CACvB,OACI,OAAO;CAGf,OAAO,QAAQ,KAAA;AACnB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { n as normalizeCodec, r as unwrapZodType } from "./codec-BHAmGEIQ.js";
|
|
2
|
+
import { t as QueryBuilder } from "./query-Bh0RNxDz.js";
|
|
3
|
+
import { l as OccConflictError } from "./types_db-DXj_l9n-.js";
|
|
3
4
|
import { z as z$1 } from "zod";
|
|
4
5
|
import { ExponentialBackoff, handleWhen, retry } from "cockatiel";
|
|
5
6
|
//#region src/db/db.ts
|
|
@@ -243,4 +244,4 @@ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
|
|
|
243
244
|
//#endregion
|
|
244
245
|
export { TxContext as a, DbWriter as i, sleep as n, DbReader as r, SupaliveDb as t };
|
|
245
246
|
|
|
246
|
-
//# sourceMappingURL=realtime_db-
|
|
247
|
+
//# sourceMappingURL=realtime_db-DOCgqbwi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"realtime_db-D9p2X2PH.js","names":["z"],"sources":["../src/db/db.ts","../src/db/context.ts","../src/db/realtime_db.ts"],"sourcesContent":["import { CacheLayer } from \"./cache\";\nimport type { CommitLogEntry, PointRead, RawPointRead, RawReadEntry } from \"./types_db\";\nimport { ReadEntry, WriteEntry } from \"./types_db\";\n\nexport interface DbQueryResult<T = any> {\n rows: T[];\n rowCount?: number | null;\n}\n\nexport interface RawClient {\n query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;\n}\n\nexport interface PooledClient extends RawClient {\n release(): void;\n}\n\nexport type DbType = \"postgres\" | \"mysql\";\n\nexport interface PendingPointEntry {\n entry: PointRead;\n /* Table name and point read id = key = `${tableName} ${entry.id}` */\n key: string;\n}\n\nexport interface PreparedQuery {\n sql: string;\n params: unknown[] | unknown[][];\n operation: \"insertSingle\" | \"insertBatch\" | \"updateSingle\" | \"updateBatch\" | \"deleteSingle\" | \"deleteBatch\" | \"pointReadValidation\" | \"commit_logs\";\n table: string;\n entryId?: unknown;\n expectedTs?: bigint,\n entries?: WriteEntry[],\n pendingsEntry?: PendingPointEntry[];\n};\n\nexport interface PreparedQueries {\n commits: PreparedQuery[];\n validateReadPoints?: PreparedQuery[];\n hasRangeRead: boolean;\n tableIds?: Uint8Array[];\n rawReadSet?: RawReadEntry[],\n}\n\nexport interface Database {\n readonly dbType: DbType;\n readonly sqlBuilder: SqlBuilder;\n columnTypes: Map<string, Map<string, string>>;\n migrationSql: string[];\n bootstrapColumnTypes(opts: { redis?: CacheLayer; cacheKey: string; tables?: string[]; }): Promise<void>;\n query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;\n getClient(): Promise<PooledClient>;\n getTransactionClient(): Promise<TxDatabase>;\n getLatestSnapshotTimestamp(): Promise<bigint>;\n updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;\n getNextTimestamp(): Promise<bigint>;\n prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;\n commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{ success: boolean }>;\n close(): Promise<void>;\n /**\n * Delete commit_logs older than `ts` (exclusive). Used by the periodic\n * retention sweep in SubscriptionManager so the table doesn't grow\n * unbounded.\n */\n pruneCommitLogsBefore(ts: bigint): Promise<bigint>;\n /**\n * Half-open range scan: ts >= beginTs AND ts < endTs. Used by the\n * subscription-recovery path to replay logs in a specific time window.\n */\n getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;\n /**\n * Conflict-check scan for OCC: ts >= sinceTs AND ts <> excludeTs. The\n * exclude is our own commitTs so we don't conflict with ourselves; the\n * lack of an upper bound is intentional, so a concurrent peer that\n * happens to have a higher commitTs but committed before us is still\n * visible. (MVCC keeps in-flight peers invisible until they commit.)\n */\n getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;\n /**\n * For each `update`/`delete` entry, attach `prevData` (consumed by the\n * invalidator) and `expectedCommitTs` (the CAS fence).\n *\n * `expectedCommitTs` is preferentially copied from a prior point-read of\n * the same row in `readSet` — that's the value the handler's logic\n * actually depended on, so the CAS check enforces beginTs-level isolation\n * for read-then-update patterns. If no prior read exists (\"blind\"\n * write), we fall back to the value observed in this batch fetch (weak\n * OCC, sufficient for writes that don't depend on prior state).\n *\n * `prevData` always comes from this batch fetch (SELECT * per table) so\n * the invalidator has the full row regardless of which columns the\n * handler's read selected.\n *\n * If the target row no longer exists at fetch time, `expectedCommitTs`\n * is left undefined and the per-row CAS will match nothing — surfaced\n * as OccConflictError.\n */\n attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;\n}\n\nexport interface TxDatabase extends Database {\n begin(): Promise<void>;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n release(): void;\n}\n\nexport interface JsonOpOptions {\n /**\n * When true, the bound `value` parameter is treated as already prepared\n * for the underlying SQL (e.g. a literal JSON path string for\n * jsonHasKey, a JSON-encoded literal for the contains family). When\n * false/omitted, the value was prepared client-side from a JS value.\n */\n raw?: boolean;\n /**\n * 1-based positional index of an extra bound parameter holding a\n * jsonpath that scopes the contains-family check to a sub-document of\n * the target column. When omitted, the check runs against the whole\n * column value.\n */\n pathIndex?: number;\n /**\n * jsonHasKey only: when set, multiple path parameters are bound starting\n * at `paramIndex`, and the predicate evaluates whether any (`one`) or\n * every (`all`) path exists in the column.\n */\n mode?: \"one\" | \"all\";\n /** Number of bound path parameters in multi-path mode. */\n pathCount?: number;\n}\n\nexport interface SqlBuilder {\n placeholder(index: number): string;\n like(col: string, paramIndex: number): string;\n ilike(col: string, paramIndex: number): string;\n icontains(col: string, paramIndex: number): string;\n /** PG @> ; MySQL JSON_CONTAINS */\n jsonContains(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n /** PG <@ ; MySQL JSON_CONTAINS(candidate, target) */\n jsonContainedBy(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n /**\n * Key/path existence. With `opts.raw === true`, the bound param is a JSON\n * path expression (PG `jsonb_path_exists`, MySQL `JSON_CONTAINS_PATH`).\n * Otherwise the bound param is a literal top-level key (PG `?`, MySQL\n * `JSON_CONTAINS_PATH($.\"<key>\")` with server-side quoting).\n * With `opts.pathCount` set, emits the multi-path form keyed by `mode`.\n */\n jsonHasKey(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n /** Array membership: target array contains the given element. */\n jsonArrayContains(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n}\n\nexport class LazyCommitTsParam {\n constructor(public value: unknown) { }\n\n // used by postgres\n toPostgres(prepareValue: (value: any) => any): any {\n return prepareValue(this.value);\n }\n\n // used by mysql\n toString() {\n return (this.value as any).toString();\n }\n\n validate() {\n const p = new LazyCommitTsParam(undefined);\n const hasNotObjConstructor = p.constructor !== Object;\n const hasNotToJSON = typeof (p as any).toJSON !== 'function';\n console.log('constructor must not object', hasNotObjConstructor);\n console.log('should not have toJSON', hasNotToJSON);\n }\n}","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\nexport class TxContext {\n readonly beginTs: bigint;\n readonly 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 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.ZodArray) {\n types[key] = \"array\";\n } else {\n types[key] = \"json\";\n }\n codecs[key] = normalizeCodec(schemaCodecs[key], baseField);\n }\n\n const model: Model = {\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 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 internalGetReadSet(): ReadEntry[] { return this.readSet; }\n internalGetWriteSet(): WriteEntry[] { return this.writeSet; }\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 { 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 constructor(readonly impl: Database) { }\n\n static create(config: { db: Database }): SupaliveDb {\n return new SupaliveDb(config.db);\n }\n\n protected onAfterCommit?: (writeSet: WriteEntry[], commitTs: CommitTs) => void;\n\n // ── Read-only query ──────────────────────────────────────────────\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 async liveQuery<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 // ── 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 () => {\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 db.commitWrites(\n beginTs,\n queries,\n 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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,MAAM,OAAO;IAC3C,MAAM,SAAS,MAAM,GAAG,GAAG;IAE3B,MAAM,UAAU,IAAI,mBAAmB;IACvC,MAAM,WAAW,IAAI,oBAAoB;IACzC,MAAM,eAAe,IAAI,kBAAkB,KAAA,CAAS;IAOpD,MAAM,KAAK,KAAK,yBAAyB,UAAU,OAAO;IAG1D,MAAM,UAAU,MAAM,KAAK,KAAK,oBAC9B,SACA,UACA,YACF;IAGA,KAAK,MAAM,uBAAuB,cAAc,KAAK,KAAK,qBAAqB,CAAC;IAChF,MAAM,GAAG,MAAM;IAGf,MAAM,WAAW,MAAM,GAAG,iBAAiB;IAC3C,aAAa,QAAQ;IAOrB,MAAM,eAAe,MAAM,GAAG,aAC5B,SACA,SACA,QACF;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
|
+
{"version":3,"file":"realtime_db-DOCgqbwi.js","names":["z"],"sources":["../src/db/db.ts","../src/db/context.ts","../src/db/realtime_db.ts"],"sourcesContent":["import { CacheLayer } from \"./cache\";\nimport type { CommitLogEntry, PointRead, RawPointRead, RawReadEntry } from \"./types_db\";\nimport { ReadEntry, WriteEntry } from \"./types_db\";\n\nexport interface DbQueryResult<T = any> {\n rows: T[];\n rowCount?: number | null;\n}\n\nexport interface RawClient {\n query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;\n}\n\nexport interface PooledClient extends RawClient {\n release(): void;\n}\n\nexport type DbType = \"postgres\" | \"mysql\";\n\nexport interface PendingPointEntry {\n entry: PointRead;\n /* Table name and point read id = key = `${tableName} ${entry.id}` */\n key: string;\n}\n\nexport interface PreparedQuery {\n sql: string;\n params: unknown[] | unknown[][];\n operation: \"insertSingle\" | \"insertBatch\" | \"updateSingle\" | \"updateBatch\" | \"deleteSingle\" | \"deleteBatch\" | \"pointReadValidation\" | \"commit_logs\";\n table: string;\n entryId?: unknown;\n expectedTs?: bigint,\n entries?: WriteEntry[],\n pendingsEntry?: PendingPointEntry[];\n};\n\nexport interface PreparedQueries {\n commits: PreparedQuery[];\n validateReadPoints?: PreparedQuery[];\n hasRangeRead: boolean;\n tableIds?: Uint8Array[];\n rawReadSet?: RawReadEntry[],\n}\n\nexport interface Database {\n readonly dbType: DbType;\n readonly sqlBuilder: SqlBuilder;\n columnTypes: Map<string, Map<string, string>>;\n migrationSql: string[];\n bootstrapColumnTypes(opts: { redis?: CacheLayer; cacheKey: string; tables?: string[]; }): Promise<void>;\n query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;\n getClient(): Promise<PooledClient>;\n getTransactionClient(): Promise<TxDatabase>;\n getLatestSnapshotTimestamp(): Promise<bigint>;\n updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;\n getNextTimestamp(): Promise<bigint>;\n prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;\n commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{ success: boolean }>;\n close(): Promise<void>;\n /**\n * Delete commit_logs older than `ts` (exclusive). Used by the periodic\n * retention sweep in SubscriptionManager so the table doesn't grow\n * unbounded.\n */\n pruneCommitLogsBefore(ts: bigint): Promise<bigint>;\n /**\n * Half-open range scan: ts >= beginTs AND ts < endTs. Used by the\n * subscription-recovery path to replay logs in a specific time window.\n */\n getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;\n /**\n * Conflict-check scan for OCC: ts >= sinceTs AND ts <> excludeTs. The\n * exclude is our own commitTs so we don't conflict with ourselves; the\n * lack of an upper bound is intentional, so a concurrent peer that\n * happens to have a higher commitTs but committed before us is still\n * visible. (MVCC keeps in-flight peers invisible until they commit.)\n */\n getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;\n /**\n * For each `update`/`delete` entry, attach `prevData` (consumed by the\n * invalidator) and `expectedCommitTs` (the CAS fence).\n *\n * `expectedCommitTs` is preferentially copied from a prior point-read of\n * the same row in `readSet` — that's the value the handler's logic\n * actually depended on, so the CAS check enforces beginTs-level isolation\n * for read-then-update patterns. If no prior read exists (\"blind\"\n * write), we fall back to the value observed in this batch fetch (weak\n * OCC, sufficient for writes that don't depend on prior state).\n *\n * `prevData` always comes from this batch fetch (SELECT * per table) so\n * the invalidator has the full row regardless of which columns the\n * handler's read selected.\n *\n * If the target row no longer exists at fetch time, `expectedCommitTs`\n * is left undefined and the per-row CAS will match nothing — surfaced\n * as OccConflictError.\n */\n attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;\n}\n\nexport interface TxDatabase extends Database {\n begin(): Promise<void>;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n release(): void;\n}\n\nexport interface JsonOpOptions {\n /**\n * When true, the bound `value` parameter is treated as already prepared\n * for the underlying SQL (e.g. a literal JSON path string for\n * jsonHasKey, a JSON-encoded literal for the contains family). When\n * false/omitted, the value was prepared client-side from a JS value.\n */\n raw?: boolean;\n /**\n * 1-based positional index of an extra bound parameter holding a\n * jsonpath that scopes the contains-family check to a sub-document of\n * the target column. When omitted, the check runs against the whole\n * column value.\n */\n pathIndex?: number;\n /**\n * jsonHasKey only: when set, multiple path parameters are bound starting\n * at `paramIndex`, and the predicate evaluates whether any (`one`) or\n * every (`all`) path exists in the column.\n */\n mode?: \"one\" | \"all\";\n /** Number of bound path parameters in multi-path mode. */\n pathCount?: number;\n}\n\nexport interface SqlBuilder {\n placeholder(index: number): string;\n like(col: string, paramIndex: number): string;\n ilike(col: string, paramIndex: number): string;\n icontains(col: string, paramIndex: number): string;\n /** PG @> ; MySQL JSON_CONTAINS */\n jsonContains(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n /** PG <@ ; MySQL JSON_CONTAINS(candidate, target) */\n jsonContainedBy(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n /**\n * Key/path existence. With `opts.raw === true`, the bound param is a JSON\n * path expression (PG `jsonb_path_exists`, MySQL `JSON_CONTAINS_PATH`).\n * Otherwise the bound param is a literal top-level key (PG `?`, MySQL\n * `JSON_CONTAINS_PATH($.\"<key>\")` with server-side quoting).\n * With `opts.pathCount` set, emits the multi-path form keyed by `mode`.\n */\n jsonHasKey(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n /** Array membership: target array contains the given element. */\n jsonArrayContains(col: string, paramIndex: number, opts?: JsonOpOptions): string;\n}\n\nexport class LazyCommitTsParam {\n constructor(public value: unknown) { }\n\n // used by postgres\n toPostgres(prepareValue: (value: any) => any): any {\n return prepareValue(this.value);\n }\n\n // used by mysql\n toString() {\n return (this.value as any).toString();\n }\n\n validate() {\n const p = new LazyCommitTsParam(undefined);\n const hasNotObjConstructor = p.constructor !== Object;\n const hasNotToJSON = typeof (p as any).toJSON !== 'function';\n console.log('constructor must not object', hasNotObjConstructor);\n console.log('should not have toJSON', hasNotToJSON);\n }\n}","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\nexport class TxContext {\n readonly beginTs: bigint;\n readonly 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 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.ZodArray) {\n types[key] = \"array\";\n } else {\n types[key] = \"json\";\n }\n codecs[key] = normalizeCodec(schemaCodecs[key], baseField);\n }\n\n const model: Model = {\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 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 internalGetReadSet(): ReadEntry[] { return this.readSet; }\n internalGetWriteSet(): WriteEntry[] { return this.writeSet; }\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 { 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 constructor(readonly impl: Database) { }\n\n static create(config: { db: Database }): SupaliveDb {\n return new SupaliveDb(config.db);\n }\n\n protected onAfterCommit?: (writeSet: WriteEntry[], commitTs: CommitTs) => void;\n\n // ── Read-only query ──────────────────────────────────────────────\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 async liveQuery<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 // ── 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 () => {\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 db.commitWrites(\n beginTs,\n queries,\n 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) => set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AAI,SAAS,KAAK,MAAM,OAAO;IAC3C,MAAM,SAAS,MAAM,GAAG,GAAG;IAE3B,MAAM,UAAU,IAAI,mBAAmB;IACvC,MAAM,WAAW,IAAI,oBAAoB;IACzC,MAAM,eAAe,IAAI,kBAAkB,KAAA,CAAS;IAOpD,MAAM,KAAK,KAAK,yBAAyB,UAAU,OAAO;IAG1D,MAAM,UAAU,MAAM,KAAK,KAAK,oBAC9B,SACA,UACA,YACF;IAGA,KAAK,MAAM,uBAAuB,cAAc,KAAK,KAAK,qBAAqB,CAAC;IAChF,MAAM,GAAG,MAAM;IAGf,MAAM,WAAW,MAAM,GAAG,iBAAiB;IAC3C,aAAa,QAAQ;IAOrB,MAAM,eAAe,MAAM,GAAG,aAC5B,SACA,SACA,QACF;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-DlTYWpop.js","names":[],"sources":["../src/router/router.ts"],"sourcesContent":["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 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\";\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, input: unknown) => string | null | undefined);\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 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 });\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 /** 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":";;;;;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EA,oBAAoB,MAAuB;EACzC,OAAO,KAAK,uBAAuB,IAAI,IAAI;CAC7C;CAEA,0BAAgC;EAC9B,KAAK,uBAAuB,MAAM;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"router-DlTYWpop.js","names":[],"sources":["../src/router/router.ts"],"sourcesContent":["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 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\";\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}\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 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 });\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 /** 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":";;;;;;;;;;;;;;;;AAsEA,SAAgB,OACd,QAC+B;CAC/B,MAAM,WAAW,mBAAmB,OAAO,eAAe,SAAS;CAGnE,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,UAAU,GACzD,SAAS,kBAAkB,MAAM,IAAI;CAIvC,OAAO;EACL,OAAO;EACP,YAAY,OAAO;EACnB,aAAa,OAAO,eAAe;CACrC;AACF;AAaA,MAAM,kCAAkB,IAAI,IAA6B;AAEzD,SAAgB,mBAAmB,WAAoC;CACrE,IAAI,WAAW,gBAAgB,IAAI,SAAS;CAC5C,IAAI,CAAC,UAAU;EACb,WAAW,IAAI,gBAAgB;EAC/B,gBAAgB,IAAI,WAAW,QAAQ;CACzC;CACA,OAAO;AACT;AAEA,IAAa,kBAAb,MAA6B;CAC3B,oCAAoB,IAAI,IAAsC;CAC9D,yCAAyB,IAAI,IAAY;CAEzC,kBAA4B,MAAc,MAAoC;EAC5E,IAAI,KAAK,kBAAkB,IAAI,IAAI,GACjC,MAAM,IAAI,MACR,uBAAuB,KAAK,oFAE9B;EAIF,IAAI,KAAK,UACP,KAAK,sBAAsB,IAAI;EAGjC,MAAM,gBACJ,KAAK,kBAAkB,UAClB,KAA4E,gBAC7E,KAAA;EAEN,KAAK,kBAAkB,IAAI,MAAM;GAC/B;GACA,MAAM,KAAK;GACX,UAAU,KAAK;GACf,aAAa,KAAK;GAClB,IAAI,KAAK;GACT;EACF,CAAC;CACH;;CAGA,aAAiC,MAAyD;EACxF,OAAO,KAAK,kBAAkB,IAAI,IAAI;CACxC;;CAGA,oBAA8B;EAC5B,OAAO,CAAC,GAAG,KAAK,kBAAkB,KAAK,CAAC;CAC1C;;CAGA,mBAAqD;EACnD,OAAO,IAAI,IAAI,KAAK,iBAAiB;CACvC;;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"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { t as commitTsCodec } from "./codec-BHAmGEIQ.js";
|
|
2
|
+
import { r as utf8Encode } from "./bytes-AuEkyxeU.js";
|
|
3
|
+
import { z as z$1 } from "zod";
|
|
4
|
+
//#region src/db/schema.ts
|
|
5
|
+
function defineComputedField(config) {
|
|
6
|
+
return config;
|
|
7
|
+
}
|
|
8
|
+
const schemaRegistry = /* @__PURE__ */ new Map();
|
|
9
|
+
let shouldTrackSchema = false;
|
|
10
|
+
function trackSchema() {
|
|
11
|
+
shouldTrackSchema = true;
|
|
12
|
+
}
|
|
13
|
+
function getAutoIdCodec(idMeta, userCodec) {
|
|
14
|
+
if (userCodec) return void 0;
|
|
15
|
+
const rawType = idMeta.pgType ?? idMeta.mysqlType;
|
|
16
|
+
if (!rawType) return void 0;
|
|
17
|
+
const upper = rawType.toUpperCase().replace(/\(.*\)/, "").trim();
|
|
18
|
+
if ([
|
|
19
|
+
"BIGINT",
|
|
20
|
+
"INT8",
|
|
21
|
+
"SERIAL8"
|
|
22
|
+
].includes(upper)) return {
|
|
23
|
+
encode: (v) => BigInt(v),
|
|
24
|
+
decode: (v) => String(v)
|
|
25
|
+
};
|
|
26
|
+
if ([
|
|
27
|
+
"INTEGER",
|
|
28
|
+
"INT",
|
|
29
|
+
"SERIAL",
|
|
30
|
+
"INT4",
|
|
31
|
+
"SMALLINT",
|
|
32
|
+
"INT2"
|
|
33
|
+
].includes(upper)) return {
|
|
34
|
+
encode: (v) => Number(v),
|
|
35
|
+
decode: (v) => String(v)
|
|
36
|
+
};
|
|
37
|
+
if ([
|
|
38
|
+
"DECIMAL",
|
|
39
|
+
"NUMERIC",
|
|
40
|
+
"FLOAT",
|
|
41
|
+
"REAL",
|
|
42
|
+
"DOUBLE",
|
|
43
|
+
"FLOAT8",
|
|
44
|
+
"FLOAT4"
|
|
45
|
+
].includes(upper)) return {
|
|
46
|
+
encode: (v) => Number(v),
|
|
47
|
+
decode: (v) => String(v)
|
|
48
|
+
};
|
|
49
|
+
if (upper === "BOOLEAN" || upper === "BOOL" || upper.startsWith("TINYINT") && rawType.toUpperCase().includes("(1)")) return {
|
|
50
|
+
encode: (v) => v === "true" || v === "1",
|
|
51
|
+
decode: (v) => String(v)
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function defineSchema(config) {
|
|
55
|
+
const columns = {};
|
|
56
|
+
if (config.columns) Object.assign(columns, {
|
|
57
|
+
"id": "id",
|
|
58
|
+
"commitTs": "commit_ts",
|
|
59
|
+
...config.columns
|
|
60
|
+
});
|
|
61
|
+
else {
|
|
62
|
+
for (const key of Object.keys(config.schema)) columns[key] = key;
|
|
63
|
+
columns["id"] = "id";
|
|
64
|
+
columns["commitTs"] = "commit_ts";
|
|
65
|
+
}
|
|
66
|
+
const idMeta = {};
|
|
67
|
+
if ("id" in config.schema) {
|
|
68
|
+
const userMeta = config.schema.id?.meta?.();
|
|
69
|
+
if (userMeta) for (const k of Object.keys(userMeta)) {
|
|
70
|
+
if (k === "primaryKey") continue;
|
|
71
|
+
idMeta[k] = userMeta[k];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const augmentedShape = {
|
|
75
|
+
...config.schema,
|
|
76
|
+
id: z$1.string().meta({
|
|
77
|
+
primaryKey: true,
|
|
78
|
+
...idMeta
|
|
79
|
+
}),
|
|
80
|
+
commitTs: z$1.coerce.bigint()
|
|
81
|
+
};
|
|
82
|
+
const userCodecs = config.options?.codecs;
|
|
83
|
+
const autoIdCodec = getAutoIdCodec(idMeta, userCodecs?.id);
|
|
84
|
+
const mergedCodecs = {
|
|
85
|
+
...autoIdCodec ? { id: autoIdCodec } : {},
|
|
86
|
+
...userCodecs,
|
|
87
|
+
commitTs: commitTsCodec
|
|
88
|
+
};
|
|
89
|
+
const result = {
|
|
90
|
+
tableId: tableNameToId(config.name),
|
|
91
|
+
table: config.name,
|
|
92
|
+
schema: z$1.object(augmentedShape),
|
|
93
|
+
columnsOptions: {
|
|
94
|
+
...config.options,
|
|
95
|
+
codecs: mergedCodecs
|
|
96
|
+
},
|
|
97
|
+
columns,
|
|
98
|
+
indexes: config.indexes ?? []
|
|
99
|
+
};
|
|
100
|
+
if (shouldTrackSchema) schemaRegistry.set(config.name, result);
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
103
|
+
function tableNameToId(tableName) {
|
|
104
|
+
return utf8Encode(tableName);
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
export { tableNameToId as a, shouldTrackSchema as i, defineSchema as n, trackSchema as o, schemaRegistry as r, defineComputedField as t };
|
|
108
|
+
|
|
109
|
+
//# sourceMappingURL=schema-Dd7u0A1L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-Dd7u0A1L.js","names":["z"],"sources":["../src/db/schema.ts"],"sourcesContent":["import { z, ZodRawShape } from \"zod\";\nimport { commitTsCodec } from \"./codec\";\nimport { LiveQueryHandle } from \"../client\";\nimport { utf8Encode } from \"./bytes\";\n\nexport interface ColumnCodec<TData = unknown, TDriver = unknown> {\n encode?: (value: TData) => TDriver;\n decode?: (value: TDriver) => TData;\n}\n\n// Constrain a codec's decoded type to match the schema field's inferred type.\n// Without this, `decode` could return any value (e.g. a string outside an enum)\n// and silently override the schema's declared type at the type level.\ntype SchemaCodecField<TSchema extends ZodRawShape, K extends PropertyKey> =\n K extends keyof TSchema\n ? TSchema[K] extends z.ZodTypeAny ? z.infer<TSchema[K]> : unknown\n : K extends keyof BaseSchema\n ? BaseSchema[K] extends z.ZodTypeAny ? z.infer<BaseSchema[K]> : unknown\n : unknown;\n\nexport type SchemaCodecs<TSchema extends ZodRawShape> = Partial<{\n [K in keyof (TSchema & BaseSchema)]: ColumnCodec<SchemaCodecField<TSchema, K>, any>;\n}>;\n\nexport interface SchemaColumnsOptions<TSchema extends ZodRawShape = ZodRawShape> {\n codecs?: SchemaCodecs<TSchema>;\n}\n\nexport interface SchemaColumnMapping {\n [key: string]: string;\n}\n\nexport interface DeclarativeIndex {\n name: string;\n columns: string[];\n unique?: boolean;\n type?: \"btree\" | \"hash\" | \"gin\" | \"gist\" | \"spgist\" | \"brin\";\n where?: string;\n using?: string;\n options?: string;\n tablespace?: string;\n}\n\nexport type IndexDefinition = string | DeclarativeIndex;\n\nexport interface DefineSchemaConfig<TSchema extends ZodRawShape> {\n name: string;\n schema: TSchema;\n options?: SchemaColumnsOptions<TSchema>;\n columns?: SchemaColumnMapping;\n indexes?: IndexDefinition[];\n}\n\n// Tuple-wrap the `undefined` checks so they don't fall through to the\n// object-shape conditionals when consumers compile under `strict: false`\n// (without `strictNullChecks`, `undefined` is assignable to object types and\n// would otherwise match `{ decode: ... }` / `ColumnCodec<...>` with all\n// `infer`s collapsing to `unknown`).\ntype CodecDataType<TCodec, TFallback> =\n [TCodec] extends [undefined] ? TFallback\n : TCodec extends { decode: (...args: any[]) => infer TDecoded } ? TDecoded\n : TCodec extends ColumnCodec<infer TData, unknown> ? TData\n : TFallback;\n\ntype ZodOutput<TZod> =\n [TZod] extends [undefined] ? unknown\n : TZod extends z.ZodTypeAny ? z.infer<TZod>\n : unknown;\nexport type ComputedDataType<TCodec, TZod> = CodecDataType<TCodec, ZodOutput<TZod>>;\nexport type ComputedCodec<TData, TDriver> = ColumnCodec<TData, TDriver>;\nexport type OverrideField<TObj, TKey extends PropertyKey, TValue> = Omit<TObj, TKey> & { [K in TKey]: TValue };\nexport interface ComputedFieldConfig<\n TField extends string,\n TDecoded = unknown,\n TDriver = unknown,\n TZodType extends z.ZodTypeAny | undefined = undefined,\n> {\n field: TField;\n sql: string;\n alias?: string;\n type?: TZodType;\n codec?: {\n decode: (value: TDriver) => TDecoded;\n encode?: (value: TDecoded) => TDriver;\n };\n}\n\nexport type ComputedField = {\n field: string;\n sql: string;\n alias: string;\n codec?: ColumnCodec<any, any>;\n};\n\nexport function defineComputedField<\n TField extends string,\n TDecoded = unknown,\n TDriver = unknown,\n TZodType extends z.ZodTypeAny | undefined = undefined,\n>(\n config: ComputedFieldConfig<TField, TDecoded, TDriver, TZodType>\n): ComputedFieldConfig<TField, TDecoded, TDriver, TZodType> {\n return config;\n}\n\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\ntype ApplySchemaCodecs<TBase, TCodecs> = {\n [K in keyof TBase]: K extends keyof TCodecs ? CodecDataType<TCodecs[K], TBase[K]> : TBase[K];\n};\n\n// Only apply codecs when `options.codecs` is explicitly provided. Without this\n// guard, the default constraint (`SchemaColumnsOptions<TSchema>`) makes\n// `TOptions[\"codecs\"]` infer as `Partial<{ [K]: ColumnCodec<any, any> }>`,\n// which collapses every field to `any` inside `ApplySchemaCodecs`.\ntype ResolveSchemaType<\n TSchema extends ZodRawShape,\n TOptions extends SchemaColumnsOptions<TSchema>\n> = TOptions extends { codecs: infer TCodecs }\n ? Prettify<ApplySchemaCodecs<z.infer<z.ZodObject<TSchema & BaseSchema>>, TCodecs>>\n : Prettify<z.infer<z.ZodObject<TSchema & BaseSchema>>>;\n\n// Helper to detect if a Zod type is optional or nullable\ntype IsOptionalField<T> =\n T extends z.ZodOptional<any> ? true :\n T extends z.ZodNullable<any> ? true :\n T extends z.ZodDefault<any> ? true :\n false;\n\n// Split schema keys into required vs optional\ntype OptionalKeys<TZod extends ZodRawShape> = {\n [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? K : never\n}[keyof TZod];\n\ntype RequiredKeys<TZod extends ZodRawShape> = {\n [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? never : K\n}[keyof TZod];\n\n// Add a base shape type that all schemas will include\ntype BaseSchema = {\n id: z.ZodString;\n commitTs: z.ZodCoercedBigInt;\n};\n\nexport const schemaRegistry = new Map<string, SchemaDefinition<string, any, any>>();\nexport let shouldTrackSchema = false;\n\nexport function trackSchema(): void {\n shouldTrackSchema = true;\n}\n\nfunction getAutoIdCodec(idMeta: Record<string, unknown>, userCodec: unknown): ColumnCodec<any, any> | undefined {\n if (userCodec) return undefined;\n const rawType = (idMeta.pgType as string | undefined) ?? (idMeta.mysqlType as string | undefined);\n if (!rawType) return undefined;\n\n const upper = rawType.toUpperCase().replace(/\\(.*\\)/, \"\").trim();\n if ([\"BIGINT\", \"INT8\", \"SERIAL8\"].includes(upper)) {\n return {\n encode: (v: string) => BigInt(v),\n decode: (v: unknown) => String(v),\n };\n }\n if ([\"INTEGER\", \"INT\", \"SERIAL\", \"INT4\", \"SMALLINT\", \"INT2\"].includes(upper)) {\n return {\n encode: (v: string) => Number(v),\n decode: (v: unknown) => String(v),\n };\n }\n if ([\"DECIMAL\", \"NUMERIC\", \"FLOAT\", \"REAL\", \"DOUBLE\", \"FLOAT8\", \"FLOAT4\"].includes(upper)) {\n return {\n encode: (v: string) => Number(v),\n decode: (v: unknown) => String(v),\n };\n }\n if (upper === \"BOOLEAN\" || upper === \"BOOL\" || (upper.startsWith(\"TINYINT\") && rawType.toUpperCase().includes(\"(1)\"))) {\n return {\n encode: (v: string) => v === \"true\" || v === \"1\",\n decode: (v: unknown) => String(v),\n };\n }\n return undefined;\n}\n\nexport function defineSchema<\n TSchema extends ZodRawShape,\n TName extends string,\n TOptions extends SchemaColumnsOptions<TSchema> = SchemaColumnsOptions<TSchema>\n>(\n config: DefineSchemaConfig<TSchema> & { name: TName; options?: TOptions }\n): SchemaDefinition<TName, Prettify<TSchema & BaseSchema>, ResolveSchemaType<TSchema, TOptions>> {\n const columns: Record<string, string> = {};\n\n if (config.columns) {\n Object.assign(columns, { 'id': 'id', 'commitTs': 'commit_ts', ...config.columns });\n } else {\n // Default: use field name as column name\n for (const key of Object.keys(config.schema)) {\n columns[key] = key;\n }\n columns['id'] = 'id';\n columns['commitTs'] = 'commit_ts';\n }\n\n // Preserve user's id meta (pgType, mysqlType, etc.) so the SQL generator\n // can emit the correct raw type. primaryKey is always forced true.\n const idMeta: Record<string, unknown> = {};\n if (\"id\" in config.schema) {\n const userMeta = (config.schema.id as any)?.meta?.();\n if (userMeta) {\n for (const k of Object.keys(userMeta)) {\n if (k === \"primaryKey\") continue; // always forced true\n idMeta[k] = userMeta[k];\n }\n }\n }\n\n // Merge id/commitTs into the Zod schema, user-defined fields win for everything else,\n // but id/commitTs are always forced to their correct types\n const augmentedShape = {\n ...config.schema,\n // always string, even if user defined it differently\n id: z.string().meta({ primaryKey: true, ...idMeta }),\n // always bigint, mapped to commit_ts column\n commitTs: z.coerce.bigint(),\n };\n\n const userCodecs = config.options?.codecs;\n const autoIdCodec = getAutoIdCodec(idMeta, userCodecs?.id);\n const mergedCodecs = {\n ...(autoIdCodec ? { id: autoIdCodec } : {}),\n ...userCodecs,\n commitTs: commitTsCodec,\n };\n\n const result = {\n tableId: tableNameToId(config.name),\n table: config.name,\n schema: z.object(augmentedShape),\n columnsOptions: {\n ...config.options,\n codecs: mergedCodecs,\n },\n columns,\n indexes: config.indexes ?? [],\n } as SchemaDefinition<TName, TSchema & BaseSchema, ResolveSchemaType<TSchema, TOptions>>;\n\n if (shouldTrackSchema) {\n schemaRegistry.set(config.name, result);\n }\n\n return result\n}\n\nexport function tableNameToId(tableName: string): Uint8Array {\n return utf8Encode(tableName);\n}\n\n// Stored codec map is intentionally loose: the strict per-field constraint is\n// enforced on the input (`DefineSchemaConfig.options`), but storing the strict\n// type here would break variance when assigning a specific schema to a generic\n// `SchemaDefinition<string, ZodRawShape>` constraint (ColumnCodec.encode is\n// contravariant in its data type).\nexport interface StoredSchemaColumnsOptions {\n codecs?: Record<string, ColumnCodec<any, any>>;\n}\n\nexport interface SchemaDefinition<\n TTable extends string,\n TZod extends ZodRawShape,\n TData = z.infer<z.ZodObject<TZod>>\n> {\n tableId: Uint8Array;\n table: TTable;\n schema: z.ZodObject<TZod>;\n columnsOptions: StoredSchemaColumnsOptions;\n columns: Record<string, string>;\n indexes: IndexDefinition[];\n _dataType?: TData;\n}\n\nexport type InferSchema<T extends SchemaDefinition<string, ZodRawShape, any>> =\n T extends SchemaDefinition<string, ZodRawShape, infer TData> ? TData : never;\n\nexport type InsertData<T extends SchemaDefinition<string, ZodRawShape, any>> =\n T extends SchemaDefinition<string, infer TZod, infer TData>\n ? {\n [K in RequiredKeys<TZod> as K extends \"id\" | \"commitTs\" ? never : K]:\n Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never\n } & {\n [K in OptionalKeys<TZod> as K extends \"id\" | \"commitTs\" ? never : K]?:\n Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never\n }\n : never;\n\nexport interface Model {\n table: string;\n tableId: Uint8Array,\n columns: Record<string, string>;\n reverseColumns: Record<string, string>;\n types: Record<string, string>;\n codecs: Record<string, ColumnCodec<any, any>>;\n}\n\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ReturnLiveQuery<\n TLiveQueryFn extends (...args: any[]) => MaybePromise<LiveQueryHandle<any>>\n> =\n Awaited<ReturnType<TLiveQueryFn>> extends LiveQueryHandle<infer T>\n ? T\n : never;\n\nexport type ReturnQuery<TQueryFn extends (...args: any[]) => any> =\n Awaited<ReturnType<TQueryFn>>;\n\nexport type QueryArgs<TQueryFn extends (...args: any[]) => any> =\n Parameters<TQueryFn>[0];\n\nexport type MutationArgs<TMutationFn extends (...args: any[]) => any> =\n Parameters<TMutationFn>[0];\n\nexport type ActionArgs<TActionFn extends (...args: any[]) => any> =\n Parameters<TActionFn>[0];"],"mappings":";;;;AA8FA,SAAgB,oBAMZ,QACwD;CACxD,OAAO;AACX;AAyCA,MAAa,iCAAiB,IAAI,IAAgD;AAClF,IAAW,oBAAoB;AAE/B,SAAgB,cAAoB;CAChC,oBAAoB;AACxB;AAEA,SAAS,eAAe,QAAiC,WAAuD;CAC5G,IAAI,WAAW,OAAO,KAAA;CACtB,MAAM,UAAW,OAAO,UAAkC,OAAO;CACjE,IAAI,CAAC,SAAS,OAAO,KAAA;CAErB,MAAM,QAAQ,QAAQ,YAAY,CAAC,CAAC,QAAQ,UAAU,EAAE,CAAC,CAAC,KAAK;CAC/D,IAAI;EAAC;EAAU;EAAQ;CAAS,CAAC,CAAC,SAAS,KAAK,GAC5C,OAAO;EACH,SAAS,MAAc,OAAO,CAAC;EAC/B,SAAS,MAAe,OAAO,CAAC;CACpC;CAEJ,IAAI;EAAC;EAAW;EAAO;EAAU;EAAQ;EAAY;CAAM,CAAC,CAAC,SAAS,KAAK,GACvE,OAAO;EACH,SAAS,MAAc,OAAO,CAAC;EAC/B,SAAS,MAAe,OAAO,CAAC;CACpC;CAEJ,IAAI;EAAC;EAAW;EAAW;EAAS;EAAQ;EAAU;EAAU;CAAQ,CAAC,CAAC,SAAS,KAAK,GACpF,OAAO;EACH,SAAS,MAAc,OAAO,CAAC;EAC/B,SAAS,MAAe,OAAO,CAAC;CACpC;CAEJ,IAAI,UAAU,aAAa,UAAU,UAAW,MAAM,WAAW,SAAS,KAAK,QAAQ,YAAY,CAAC,CAAC,SAAS,KAAK,GAC/G,OAAO;EACH,SAAS,MAAc,MAAM,UAAU,MAAM;EAC7C,SAAS,MAAe,OAAO,CAAC;CACpC;AAGR;AAEA,SAAgB,aAKZ,QAC6F;CAC7F,MAAM,UAAkC,CAAC;CAEzC,IAA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