@hyper-fetch/db 0.0.0-stage → 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.
Files changed (141) hide show
  1. package/README.md +180 -2
  2. package/__tests__/e2e/db.e2e.spec.ts +269 -0
  3. package/__tests__/features/connection/connection.spec.ts +23 -0
  4. package/__tests__/features/model/live-query.model.spec.ts +320 -0
  5. package/__tests__/features/operators/operators.spec.ts +113 -0
  6. package/__tests__/features/runtime/runtime.spec.ts +185 -0
  7. package/__tests__/features/serializer/serializer.spec.ts +73 -0
  8. package/__tests__/features/store/store.spec.ts +147 -0
  9. package/__tests__/features/types/db.types.spec.ts +337 -0
  10. package/__tests__/integration/audit.spec.ts +639 -0
  11. package/__tests__/integration/competitors.spec.ts +393 -0
  12. package/__tests__/integration/convergence.model.spec.ts +162 -0
  13. package/__tests__/integration/edge-cases.spec.ts +465 -0
  14. package/__tests__/integration/errors.spec.ts +178 -0
  15. package/__tests__/integration/infinite.model.spec.ts +142 -0
  16. package/__tests__/integration/infinite.spec.ts +290 -0
  17. package/__tests__/integration/inspect.spec.ts +103 -0
  18. package/__tests__/integration/joins-many.spec.ts +177 -0
  19. package/__tests__/integration/joins.spec.ts +179 -0
  20. package/__tests__/integration/key-loaders.spec.ts +196 -0
  21. package/__tests__/integration/links.spec.ts +105 -0
  22. package/__tests__/integration/mutations.spec.ts +337 -0
  23. package/__tests__/integration/normalize.spec.ts +80 -0
  24. package/__tests__/integration/offline.spec.ts +479 -0
  25. package/__tests__/integration/queries.spec.ts +513 -0
  26. package/__tests__/integration/races.spec.ts +127 -0
  27. package/__tests__/integration/server-operators.spec.ts +123 -0
  28. package/__tests__/integration/ssr.spec.ts +111 -0
  29. package/__tests__/integration/syncs.spec.ts +564 -0
  30. package/__tests__/integration/transactions.spec.ts +344 -0
  31. package/__tests__/integration/windows.spec.ts +192 -0
  32. package/__tests__/tsconfig.json +11 -0
  33. package/__tests__/type-budget/budget.fixture.ts +2476 -0
  34. package/__tests__/type-budget/tsconfig.json +4 -0
  35. package/__tests__/utils/fixtures.ts +225 -0
  36. package/__tests__/utils/random.ts +19 -0
  37. package/__tests__/vitest.setup.ts +11 -0
  38. package/dist/collection/collection.d.ts +111 -0
  39. package/dist/collection/collection.d.ts.map +1 -0
  40. package/dist/collection/collection.types.d.ts +316 -0
  41. package/dist/collection/collection.types.d.ts.map +1 -0
  42. package/dist/collection/resource.types.d.ts +77 -0
  43. package/dist/collection/resource.types.d.ts.map +1 -0
  44. package/dist/db/collection.runtime.d.ts +98 -0
  45. package/dist/db/collection.runtime.d.ts.map +1 -0
  46. package/dist/db/db.d.ts +154 -0
  47. package/dist/db/db.d.ts.map +1 -0
  48. package/dist/db/db.runtime.d.ts +114 -0
  49. package/dist/db/db.runtime.d.ts.map +1 -0
  50. package/dist/db/db.types.d.ts +162 -0
  51. package/dist/db/db.types.d.ts.map +1 -0
  52. package/dist/graphql/connection.d.ts +25 -0
  53. package/dist/graphql/connection.d.ts.map +1 -0
  54. package/dist/index.d.ts +17 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.mjs +4220 -0
  57. package/dist/index.mjs.map +1 -0
  58. package/dist/mutation/mutation.d.ts +136 -0
  59. package/dist/mutation/mutation.d.ts.map +1 -0
  60. package/dist/mutation/mutation.errors.d.ts +6 -0
  61. package/dist/mutation/mutation.errors.d.ts.map +1 -0
  62. package/dist/mutation/mutation.utils.d.ts +35 -0
  63. package/dist/mutation/mutation.utils.d.ts.map +1 -0
  64. package/dist/operators/operators.d.ts +33 -0
  65. package/dist/operators/operators.d.ts.map +1 -0
  66. package/dist/operators/operators.types.d.ts +68 -0
  67. package/dist/operators/operators.types.d.ts.map +1 -0
  68. package/dist/operators/operators.utils.d.ts +19 -0
  69. package/dist/operators/operators.utils.d.ts.map +1 -0
  70. package/dist/persistence/persistence.d.ts +42 -0
  71. package/dist/persistence/persistence.d.ts.map +1 -0
  72. package/dist/persistence/serializer.d.ts +23 -0
  73. package/dist/persistence/serializer.d.ts.map +1 -0
  74. package/dist/persistence/snapshot.d.ts +29 -0
  75. package/dist/persistence/snapshot.d.ts.map +1 -0
  76. package/dist/persistence/tabs.d.ts +53 -0
  77. package/dist/persistence/tabs.d.ts.map +1 -0
  78. package/dist/query/infinite-query.d.ts +59 -0
  79. package/dist/query/infinite-query.d.ts.map +1 -0
  80. package/dist/query/live-query.d.ts +85 -0
  81. package/dist/query/live-query.d.ts.map +1 -0
  82. package/dist/query/planner.d.ts +57 -0
  83. package/dist/query/planner.d.ts.map +1 -0
  84. package/dist/query/query.d.ts +155 -0
  85. package/dist/query/query.d.ts.map +1 -0
  86. package/dist/query/query.types.d.ts +71 -0
  87. package/dist/query/query.types.d.ts.map +1 -0
  88. package/dist/schema/schema.types.d.ts +33 -0
  89. package/dist/schema/schema.types.d.ts.map +1 -0
  90. package/dist/store/store.d.ts +76 -0
  91. package/dist/store/store.d.ts.map +1 -0
  92. package/dist/store/store.types.d.ts +27 -0
  93. package/dist/store/store.types.d.ts.map +1 -0
  94. package/dist/subset/base-subset.d.ts +66 -0
  95. package/dist/subset/base-subset.d.ts.map +1 -0
  96. package/dist/subset/key-subset.d.ts +23 -0
  97. package/dist/subset/key-subset.d.ts.map +1 -0
  98. package/dist/subset/list-subset.d.ts +63 -0
  99. package/dist/subset/list-subset.d.ts.map +1 -0
  100. package/dist/sync/sync.d.ts +42 -0
  101. package/dist/sync/sync.d.ts.map +1 -0
  102. package/dist/utils/request.utils.d.ts +11 -0
  103. package/dist/utils/request.utils.d.ts.map +1 -0
  104. package/package.json +71 -4
  105. package/project.json +4 -0
  106. package/scripts/docs-typescript.mjs +24 -0
  107. package/scripts/type-budget.mjs +37 -0
  108. package/src/collection/collection.ts +330 -0
  109. package/src/collection/collection.types.ts +383 -0
  110. package/src/collection/resource.types.ts +114 -0
  111. package/src/db/collection.runtime.ts +572 -0
  112. package/src/db/db.runtime.ts +537 -0
  113. package/src/db/db.ts +451 -0
  114. package/src/db/db.types.ts +157 -0
  115. package/src/graphql/connection.ts +23 -0
  116. package/src/index.ts +16 -0
  117. package/src/mutation/mutation.errors.ts +7 -0
  118. package/src/mutation/mutation.ts +776 -0
  119. package/src/mutation/mutation.utils.ts +58 -0
  120. package/src/operators/operators.ts +90 -0
  121. package/src/operators/operators.types.ts +67 -0
  122. package/src/operators/operators.utils.ts +169 -0
  123. package/src/persistence/persistence.ts +168 -0
  124. package/src/persistence/serializer.ts +123 -0
  125. package/src/persistence/snapshot.ts +76 -0
  126. package/src/persistence/tabs.ts +86 -0
  127. package/src/query/infinite-query.ts +206 -0
  128. package/src/query/live-query.ts +552 -0
  129. package/src/query/planner.ts +199 -0
  130. package/src/query/query.ts +319 -0
  131. package/src/query/query.types.ts +90 -0
  132. package/src/schema/schema.types.ts +29 -0
  133. package/src/store/store.ts +300 -0
  134. package/src/store/store.types.ts +17 -0
  135. package/src/subset/base-subset.ts +169 -0
  136. package/src/subset/key-subset.ts +44 -0
  137. package/src/subset/list-subset.ts +328 -0
  138. package/src/sync/sync.ts +99 -0
  139. package/src/utils/request.utils.ts +67 -0
  140. package/tsconfig.json +12 -0
  141. package/vite.config.ts +71 -0
@@ -0,0 +1,320 @@
1
+ /**
2
+ * A model test: random server writes, deletes and optimistic layers against live queries with random filters, orders
3
+ * and limits. After every step, each query must equal what a naive oracle computes from scratch, both when it is
4
+ * subscribed (and kept current incrementally) and when it is read fresh. Seeds are fixed, so a failure reproduces.
5
+ */
6
+ import { and, collection, eq, gt, gte, inArray, lt, lte, not, or, rowType } from "@hyper-fetch/db";
7
+ import type { Condition, FieldRef, RowRefs } from "@hyper-fetch/db";
8
+
9
+ import { CollectionHandle } from "../../../src/db/db";
10
+ import { DbRuntime } from "../../../src/db/db.runtime";
11
+ import type { Stamp } from "../../../src/store/store.types";
12
+ import { createRandom } from "../../utils/random";
13
+ import type { Random } from "../../utils/random";
14
+
15
+ type Item = { id: number; group: number; score: number | null; title: string; note?: string };
16
+
17
+ const KEYS = [1, 2, 3, 4, 5, 6, 7, 8];
18
+ const TITLES = ["a", "b", "ab", "B", ""];
19
+
20
+ /** A small deterministic PRNG, so every seed replays the same steps */
21
+
22
+ const randomRow = (random: Random, id: number): Item => {
23
+ const row: Item = {
24
+ id,
25
+ group: random.int(0, 3),
26
+ score: random.chance(0.2) ? null : random.int(-2, 5),
27
+ title: random.pick(TITLES),
28
+ };
29
+ if (random.chance(0.5)) {
30
+ row.note = random.pick(["x", "y"]);
31
+ }
32
+ return row;
33
+ };
34
+
35
+ const randomChanges = (random: Random, id: number): Partial<Item> & { id: number } => {
36
+ const full = randomRow(random, id);
37
+ const changes: Partial<Item> & { id: number } = { id };
38
+ (["group", "score", "title"] as const).forEach((field) => {
39
+ if (random.chance(0.5)) {
40
+ Object.assign(changes, { [field]: full[field] });
41
+ }
42
+ });
43
+ return changes;
44
+ };
45
+
46
+ /* ------------------------------------------------------------------ oracle */
47
+
48
+ type Predicate = (row: Item) => boolean;
49
+
50
+ const isEmpty = (value: unknown) => value === null || value === undefined;
51
+
52
+ /** The order the db promises: empty values first, numbers by value, strings by code point, ties by key */
53
+ const compareNaive = (left: unknown, right: unknown): number => {
54
+ if (isEmpty(left) || isEmpty(right)) {
55
+ if (isEmpty(left) && isEmpty(right)) {
56
+ return 0;
57
+ }
58
+ return isEmpty(left) ? -1 : 1;
59
+ }
60
+ if (typeof left === "string" && typeof right === "string") {
61
+ const a = [...left].map((char) => char.codePointAt(0)!);
62
+ const b = [...right].map((char) => char.codePointAt(0)!);
63
+ for (let index = 0; index < Math.min(a.length, b.length); index += 1) {
64
+ if (a[index] !== b[index]) {
65
+ return a[index] < b[index] ? -1 : 1;
66
+ }
67
+ }
68
+ return Math.sign(a.length - b.length);
69
+ }
70
+ return Math.sign((left as number) - (right as number));
71
+ };
72
+
73
+ type QuerySpec = {
74
+ describe: string;
75
+ where?: (row: RowRefs<Item>) => Condition<string, string>;
76
+ predicate: Predicate;
77
+ orderBy: { field: "group" | "score" | "title" | "id"; direction: "asc" | "desc" }[];
78
+ limit?: number;
79
+ };
80
+
81
+ const FIELDS = ["group", "score", "title"] as const;
82
+
83
+ const randomComparison = (
84
+ random: Random,
85
+ ): { describe: string; build: (row: RowRefs<Item>) => Condition<string, string>; predicate: Predicate } => {
86
+ const field = random.pick(FIELDS);
87
+ const value = field === "title" ? random.pick(TITLES) : random.int(-2, 4);
88
+ const op = random.pick(["eq", "gt", "gte", "lt", "lte", "inArray"] as const);
89
+ const ref = (row: RowRefs<Item>) => row[field] as FieldRef<string, unknown>;
90
+ const compare = (row: Item) => compareNaive(row[field], value);
91
+ switch (op) {
92
+ case "eq": {
93
+ return {
94
+ describe: `${field} = ${String(value)}`,
95
+ build: (row) => eq(ref(row), value as never),
96
+ predicate: (row) => Object.is(row[field], value),
97
+ };
98
+ }
99
+ case "inArray": {
100
+ const values = [value, field === "title" ? random.pick(TITLES) : random.int(-2, 4)];
101
+ return {
102
+ describe: `${field} in ${values.join(",")}`,
103
+ build: (row) => inArray(ref(row), values as never[]),
104
+ predicate: (row) => values.some((item) => Object.is(row[field], item)),
105
+ };
106
+ }
107
+ case "gt": {
108
+ return {
109
+ describe: `${field} > ${String(value)}`,
110
+ build: (row) => gt(ref(row) as never, value as never),
111
+ predicate: (row) => !isEmpty(row[field]) && compare(row) > 0,
112
+ };
113
+ }
114
+ case "gte": {
115
+ return {
116
+ describe: `${field} >= ${String(value)}`,
117
+ build: (row) => gte(ref(row) as never, value as never),
118
+ predicate: (row) => !isEmpty(row[field]) && compare(row) >= 0,
119
+ };
120
+ }
121
+ case "lt": {
122
+ return {
123
+ describe: `${field} < ${String(value)}`,
124
+ build: (row) => lt(ref(row) as never, value as never),
125
+ predicate: (row) => !isEmpty(row[field]) && compare(row) < 0,
126
+ };
127
+ }
128
+ default: {
129
+ return {
130
+ describe: `${field} <= ${String(value)}`,
131
+ build: (row) => lte(ref(row) as never, value as never),
132
+ predicate: (row) => !isEmpty(row[field]) && compare(row) <= 0,
133
+ };
134
+ }
135
+ }
136
+ };
137
+
138
+ const randomCondition = (
139
+ random: Random,
140
+ depth = 0,
141
+ ): { describe: string; build: (row: RowRefs<Item>) => Condition<string, string>; predicate: Predicate } => {
142
+ if (depth >= 2 || random.chance(0.5)) {
143
+ return randomComparison(random);
144
+ }
145
+ const kind = random.pick(["and", "or", "not"] as const);
146
+ if (kind === "not") {
147
+ const inner = randomCondition(random, depth + 1);
148
+ return {
149
+ describe: `not(${inner.describe})`,
150
+ build: (row) => not(inner.build(row)),
151
+ predicate: (row) => !inner.predicate(row),
152
+ };
153
+ }
154
+ const left = randomCondition(random, depth + 1);
155
+ const right = randomCondition(random, depth + 1);
156
+ return kind === "and"
157
+ ? {
158
+ describe: `(${left.describe} and ${right.describe})`,
159
+ build: (row) => and(left.build(row), right.build(row)),
160
+ predicate: (row) => left.predicate(row) && right.predicate(row),
161
+ }
162
+ : {
163
+ describe: `(${left.describe} or ${right.describe})`,
164
+ build: (row) => or(left.build(row), right.build(row)),
165
+ predicate: (row) => left.predicate(row) || right.predicate(row),
166
+ };
167
+ };
168
+
169
+ const randomQuery = (random: Random): QuerySpec => {
170
+ const condition = random.chance(0.85) ? randomCondition(random) : undefined;
171
+ const orderBy = Array.from({ length: random.int(0, 2) }, () => ({
172
+ field: random.pick(["group", "score", "title", "id"] as const),
173
+ direction: random.pick(["asc", "desc"] as const),
174
+ }));
175
+ const limit = random.chance(0.4) ? random.int(0, 4) : undefined;
176
+ return {
177
+ describe: `${condition?.describe ?? "all"} order ${orderBy.map((o) => `${o.field} ${o.direction}`).join(", ")}${
178
+ limit === undefined ? "" : ` limit ${limit}`
179
+ }`,
180
+ where: condition?.build,
181
+ predicate: condition?.predicate ?? (() => true),
182
+ orderBy: orderBy.length > 0 ? orderBy : [{ field: "id", direction: "asc" }],
183
+ limit,
184
+ };
185
+ };
186
+
187
+ /** What every query should show, computed from the visible rows without the db */
188
+ const expected = (spec: QuerySpec, rows: Item[]) => {
189
+ const sorted = rows.filter(spec.predicate).toSorted((left, right) => {
190
+ for (const { field, direction } of spec.orderBy) {
191
+ const result = compareNaive(left[field], right[field]);
192
+ if (result !== 0) {
193
+ return direction === "desc" ? -result : result;
194
+ }
195
+ }
196
+ return left.id - right.id;
197
+ });
198
+ return spec.limit === undefined ? sorted : sorted.slice(0, spec.limit);
199
+ };
200
+
201
+ type Layer = { id: string; key: number; type: "insert" | "update" | "delete"; values: Record<string, unknown> };
202
+
203
+ /** The visible rows as the db promises them: server rows with every pending layer applied in order */
204
+ const visibleRows = (server: Map<number, Item>, layers: Layer[]): Item[] => {
205
+ const keys = new Set([...server.keys(), ...layers.map((layer) => layer.key)]);
206
+ return [...keys]
207
+ .map((key) => {
208
+ let row: Record<string, unknown> | undefined = server.get(key);
209
+ layers
210
+ .filter((layer) => layer.key === key)
211
+ .forEach((layer) => {
212
+ if (layer.type === "insert") {
213
+ row = { ...layer.values };
214
+ } else if (layer.type === "update") {
215
+ row = row ? { ...row, ...layer.values } : undefined;
216
+ } else {
217
+ row = undefined;
218
+ }
219
+ });
220
+ return row as Item | undefined;
221
+ })
222
+ .filter((row): row is Item => row !== undefined);
223
+ };
224
+
225
+ /* --------------------------------------------------------------- the test */
226
+
227
+ const runSeed = (seed: number, steps: number) => {
228
+ const random = createRandom(seed);
229
+ const runtime = new DbRuntime({ item: collection(rowType<Item>(), { key: "id" }) });
230
+ const handle = new CollectionHandle(runtime, "item");
231
+ const runtimeCollection = runtime.collections.get("item")!;
232
+ const { store } = runtimeCollection;
233
+ let seq = 0;
234
+ const stamp = (): Stamp => {
235
+ seq += 1;
236
+ return { kind: "sent", seq, wall: seq };
237
+ };
238
+
239
+ const specs = Array.from({ length: 8 }, () => randomQuery(random));
240
+ const build = (spec: QuerySpec, extraLimit?: number) => {
241
+ let query: any = handle.local();
242
+ if (spec.where) {
243
+ query = query.where(spec.where);
244
+ }
245
+ spec.orderBy.forEach(({ field, direction }) => {
246
+ query = query.orderBy((row: RowRefs<Item>) => row[field], direction);
247
+ });
248
+ const limit = spec.limit ?? extraLimit;
249
+ return limit === undefined ? query : query.limit(limit);
250
+ };
251
+ const live = specs.map((spec) => build(spec));
252
+ const unsubscribes = live.map((query) => query.subscribe(() => {}));
253
+
254
+ const server = new Map<number, Item>();
255
+ let layers: Layer[] = [];
256
+ let layerCounter = 0;
257
+ const log: string[] = [];
258
+
259
+ const check = () => {
260
+ const rows = visibleRows(server, layers);
261
+ specs.forEach((spec, index) => {
262
+ const want = expected(spec, rows);
263
+ const context = `seed ${seed}, query "${spec.describe}", after:\n${log.join("\n")}`;
264
+ expect(live[index].getSnapshot().data, context).toStrictEqual(want);
265
+ // A query nobody subscribes to is rebuilt from scratch, a second path that must agree
266
+ const fresh = build(spec, spec.limit === undefined ? 1000 : undefined);
267
+ expect(fresh.getSnapshot().data, `${context}\n(fresh read)`).toStrictEqual(want);
268
+ });
269
+ };
270
+
271
+ const runStep = () => {
272
+ const key = random.pick(KEYS);
273
+ const action = random.int(0, 9);
274
+ runtime.batch(() => {
275
+ if (action <= 2) {
276
+ const row = randomRow(random, key);
277
+ log.push(`server write ${JSON.stringify(row)}`);
278
+ server.set(key, row);
279
+ runtimeCollection.writeServerRows([row], true, stamp());
280
+ } else if (action <= 4) {
281
+ const changes = randomChanges(random, key);
282
+ log.push(`server update ${JSON.stringify(changes)}`);
283
+ if (server.has(key)) {
284
+ server.set(key, { ...server.get(key)!, ...changes });
285
+ }
286
+ runtimeCollection.writeServerRows([changes], false, stamp());
287
+ } else if (action === 5) {
288
+ log.push(`server delete ${key}`);
289
+ server.delete(key);
290
+ store.remove(key, stamp());
291
+ } else if (action <= 8) {
292
+ layerCounter += 1;
293
+ const type = random.pick(["insert", "update", "delete"] as const);
294
+ const values: Record<string, unknown> = { insert: randomRow, update: randomChanges, delete: () => ({}) }[type](
295
+ random,
296
+ key,
297
+ );
298
+ const layer: Layer = { id: `l${layerCounter}`, key, type, values };
299
+ log.push(`layer ${layer.id} ${type} ${JSON.stringify(values)}`);
300
+ layers.push(layer);
301
+ store.addLayer({ ...layer });
302
+ } else if (layers.length > 0) {
303
+ const layer = random.pick(layers);
304
+ log.push(`drop layer ${layer.id}`);
305
+ layers = layers.filter((item) => item !== layer);
306
+ store.removeLayer(layer.id);
307
+ }
308
+ });
309
+ check();
310
+ };
311
+ Array.from({ length: steps }).forEach(runStep);
312
+ unsubscribes.forEach((unsubscribe) => unsubscribe());
313
+ runtime.destroy();
314
+ };
315
+
316
+ describe("db [ Model ] live queries against a naive oracle", () => {
317
+ it.each(Array.from({ length: 150 }, (_, index) => index + 1))("seed %i", (seed) => {
318
+ runSeed(seed, 40);
319
+ });
320
+ });
@@ -0,0 +1,113 @@
1
+ /* oxlint-disable no-useless-undefined -- comparing with undefined is the behavior under test */
2
+ import { and, eq, gt, gte, inArray, lt, lte, not, or } from "@hyper-fetch/db";
3
+ import type { RowRefs } from "@hyper-fetch/db";
4
+
5
+ import {
6
+ compareValues,
7
+ evaluate,
8
+ getExpressionFields,
9
+ isEqualValue,
10
+ splitAnd,
11
+ stableStringify,
12
+ } from "../../../src/operators/operators.utils";
13
+
14
+ type TestRow = { id: number; title: string; deleted: number | null; a: number; b: number; c: number };
15
+
16
+ const refs = new Proxy({}, { get: (_target, field) => ({ kind: "field", field }) }) as RowRefs<TestRow>;
17
+
18
+ describe("Operators", () => {
19
+ describe("compareValues", () => {
20
+ it("sorts NaN after every number, consistently in both directions", () => {
21
+ expect(compareValues(Number.NaN, 5)).toBe(1);
22
+ expect(compareValues(5, Number.NaN)).toBe(-1);
23
+ expect(compareValues(Number.NaN, Number.NaN)).toBe(0);
24
+ expect([3, Number.NaN, -1].toSorted(compareValues)).toStrictEqual([-1, 3, Number.NaN]);
25
+ });
26
+
27
+ it("sorts empty values first", () => {
28
+ expect(compareValues(null, undefined)).toBe(0);
29
+ expect(compareValues(null, 1)).toBe(-1);
30
+ expect(compareValues(1, undefined)).toBe(1);
31
+ });
32
+
33
+ it("compares strings by code point, whatever their length", () => {
34
+ expect(compareValues("a", "b")).toBe(-1);
35
+ expect(compareValues("b", "a")).toBe(1);
36
+ expect(compareValues("ab", "a")).toBe(1);
37
+ expect(compareValues("a", "ab")).toBe(-1);
38
+ expect(compareValues("same", "same")).toBe(0);
39
+ expect(compareValues("😀", "￿")).toBe(1);
40
+ });
41
+
42
+ it("compares dates by instant and values of different types by type name", () => {
43
+ expect(compareValues(new Date(1), new Date(2))).toBe(-1);
44
+ expect(compareValues(new Date(2), new Date(2))).toBe(0);
45
+ expect(compareValues(1, "1")).toBe(-1);
46
+ expect(compareValues(2, 1)).toBe(1);
47
+ expect(compareValues(Number.NaN, Number.NaN)).toBe(0);
48
+ });
49
+
50
+ it("treats dates of the same instant as equal", () => {
51
+ expect(isEqualValue(new Date(5), new Date(5))).toBeTrue();
52
+ expect(isEqualValue(Number.NaN, Number.NaN)).toBeTrue();
53
+ expect(isEqualValue(1, "1")).toBeFalse();
54
+ });
55
+ });
56
+
57
+ describe("evaluate", () => {
58
+ const row = { id: 2, title: "b", deleted: null };
59
+
60
+ it("evaluates every comparison", () => {
61
+ expect(evaluate(eq(refs.id, 2).node, row)).toBeTrue();
62
+ expect(evaluate(inArray(refs.id, [1, 3]).node, row)).toBeFalse();
63
+ expect(evaluate(gt(refs.id, 1).node, row)).toBeTrue();
64
+ expect(evaluate(gte(refs.id, 2).node, row)).toBeTrue();
65
+ expect(evaluate(lt(refs.id, 2).node, row)).toBeFalse();
66
+ expect(evaluate(lte(refs.id, 2).node, row)).toBeTrue();
67
+ });
68
+
69
+ it("never matches an empty value with a range comparison", () => {
70
+ ([gt, gte, lt, lte] as const).forEach((operator) => {
71
+ expect(evaluate(operator(refs.deleted, 1).node, row)).toBeFalse();
72
+ });
73
+ });
74
+
75
+ it("evaluates and, or and not", () => {
76
+ expect(evaluate(and(eq(refs.id, 2), eq(refs.title, "b")).node, row)).toBeTrue();
77
+ expect(evaluate(or(eq(refs.id, 3), eq(refs.title, "b")).node, row)).toBeTrue();
78
+ expect(evaluate(not(eq(refs.id, 2)).node, row)).toBeFalse();
79
+ });
80
+ });
81
+
82
+ describe("expression helpers", () => {
83
+ it("splits a query at its top-level and, flattening nested ones", () => {
84
+ const node = and(eq(refs.a, 1), and(eq(refs.b, 2), or(eq(refs.c, 3)))).node;
85
+ expect(splitAnd(node).map((item) => item.op)).toStrictEqual(["eq", "eq", "or"]);
86
+ expect(splitAnd(undefined)).toStrictEqual([]);
87
+ });
88
+
89
+ it("lists the fields an expression reads", () => {
90
+ const node = and(eq(refs.a, 1), or(eq(refs.b, 2), not(eq(refs.c, 3)))).node;
91
+ expect(getExpressionFields(node)).toStrictEqual(["a", "b", "c"]);
92
+ });
93
+
94
+ it("stringifies values structurally", () => {
95
+ expect(stableStringify({ b: [new Date(1)], a: 1 })).toBe(stableStringify({ a: 1, b: [new Date(1)] }));
96
+ expect(stableStringify(undefined)).toBe('{"$undefined":true}');
97
+ // Values JSON cannot tell apart stay apart
98
+ const values = [
99
+ 10n,
100
+ Number.NaN,
101
+ Infinity,
102
+ -Infinity,
103
+ null,
104
+ undefined,
105
+ new Map([[1, 2]]),
106
+ new Map([[1, 3]]),
107
+ new Set([1]),
108
+ ];
109
+ expect(new Set(values.map(stableStringify)).size).toBe(values.length);
110
+ expect(stableStringify(new Date(3))).toBe('{"$date":3}');
111
+ });
112
+ });
113
+ });
@@ -0,0 +1,185 @@
1
+ import type { ListenerInstance } from "@hyper-fetch/sockets";
2
+
3
+ import { DbRuntime } from "../../../src/db/db.runtime";
4
+ import { Tabs } from "../../../src/persistence/tabs";
5
+ import { SyncSubscription } from "../../../src/sync/sync";
6
+ import { applyListenerPatches, applyRequestPatches, createId } from "../../../src/utils/request.utils";
7
+ import { createHttpClient, createListeners, createSocket } from "../../utils/fixtures";
8
+
9
+ describe("Request patches", () => {
10
+ const client = createHttpClient();
11
+ const request = client.createRequest<{
12
+ response: unknown;
13
+ payload: unknown;
14
+ queryParams?: Record<string, number> | string;
15
+ }>()({
16
+ endpoint: "/items/:itemId",
17
+ method: "POST",
18
+ });
19
+
20
+ it("merges params, object query params and object payloads into what the request has", () => {
21
+ const patched = applyRequestPatches(request, [
22
+ { params: { itemId: 1 }, queryParams: { a: 1 }, payload: { a: 1 } },
23
+ { queryParams: { b: 2 }, payload: { b: 2 } },
24
+ {},
25
+ ]);
26
+ expect(patched.params).toStrictEqual({ itemId: 1 });
27
+ expect(patched.queryParams).toStrictEqual({ a: 1, b: 2 });
28
+ expect(patched.payload).toStrictEqual({ a: 1, b: 2 });
29
+ });
30
+
31
+ it("adds up array query params, such as Firestore constraints", () => {
32
+ const patched = applyRequestPatches(request, [{ payload: [1] }, { payload: [2] }]);
33
+ expect(patched.payload).toStrictEqual([1, 2]);
34
+ });
35
+
36
+ it("replaces string query params and values that are not objects", () => {
37
+ const patched = applyRequestPatches(request, [
38
+ { queryParams: { a: 1 }, payload: [1] },
39
+ { queryParams: "raw=1", payload: "text" },
40
+ ]);
41
+ expect(patched.queryParams).toBe("raw=1");
42
+ expect(patched.payload).toBe("text");
43
+ });
44
+
45
+ it("applies listener patches", () => {
46
+ const { onPostChanged } = createListeners(createSocket());
47
+ const patched = applyListenerPatches(onPostChanged as unknown as ListenerInstance, [
48
+ { params: { teamId: 1 } },
49
+ { payload: { a: 1 } },
50
+ { payload: { b: 2 }, queryParams: { limit: 1 } },
51
+ {},
52
+ ]);
53
+ expect(patched.topic).toBe("teams/1/posts/changed");
54
+ expect(patched.payload).toStrictEqual({ a: 1, b: 2 });
55
+ expect(patched.queryParams).toStrictEqual({ limit: 1 });
56
+ });
57
+
58
+ it("creates ids without crypto.randomUUID", () => {
59
+ vi.stubGlobal("crypto", {});
60
+ const first = createId();
61
+ const second = createId();
62
+ vi.unstubAllGlobals();
63
+ expect(first).not.toBe(second);
64
+ expect(createId()).toMatch(/^[0-9a-f-]{36}$/);
65
+ });
66
+ });
67
+
68
+ describe("Tabs", () => {
69
+ it("leads at once without Web Locks and works without a channel", () => {
70
+ vi.stubGlobal("BroadcastChannel", void 0);
71
+ const onLeader = vi.fn();
72
+ const tabs = new Tabs("db", undefined, { onLeader, onMessage: vi.fn() });
73
+ vi.unstubAllGlobals();
74
+ tabs.start();
75
+ tabs.post({ type: "leader" });
76
+ expect(onLeader).toHaveBeenCalledOnce();
77
+ expect(tabs.isLeader).toBeTrue();
78
+ tabs.close();
79
+ expect(tabs.isLeader).toBeFalse();
80
+ expect(() => tabs.post({ type: "leader" })).not.toThrow();
81
+ });
82
+
83
+ it("does not post to a channel it closed", () => {
84
+ const channel = new BroadcastChannel("db-closed");
85
+ const tabs = new Tabs("db", { channel: channel as never }, { onLeader: vi.fn(), onMessage: vi.fn() });
86
+ tabs.start();
87
+ tabs.close();
88
+ expect(() => tabs.post({ type: "leader" })).not.toThrow();
89
+ });
90
+
91
+ it("uses the Web Locks of the environment", () => {
92
+ const request = vi.fn(() => Promise.resolve());
93
+ vi.stubGlobal("navigator", { locks: { request } });
94
+ const tabs = new Tabs("db", undefined, { onLeader: vi.fn(), onMessage: vi.fn() });
95
+ vi.unstubAllGlobals();
96
+ tabs.start();
97
+ expect(request).toHaveBeenCalledWith("db:leader", expect.any(Function));
98
+ tabs.close();
99
+ });
100
+
101
+ it("leads only once it holds the lock, and releases it on close", async () => {
102
+ let grant: (() => Promise<unknown>) | undefined;
103
+ const locks = {
104
+ request: (_name: string, callback: () => Promise<unknown>) => {
105
+ grant = callback;
106
+ return Promise.resolve();
107
+ },
108
+ };
109
+ const onLeader = vi.fn();
110
+ const tabs = new Tabs("db", { locks }, { onLeader, onMessage: vi.fn() });
111
+ tabs.start();
112
+ expect(onLeader).not.toHaveBeenCalled();
113
+ const held = grant!();
114
+ expect(onLeader).toHaveBeenCalledOnce();
115
+ tabs.close();
116
+ await expect(held).resolves.toBeUndefined();
117
+ });
118
+ });
119
+
120
+ describe("SyncSubscription", () => {
121
+ const createFakeListener = () => {
122
+ const lifecycle: { onStart?: () => void; onEnd?: () => void; callback?: (event: { data: unknown }) => void } = {};
123
+ const unsubscribe = vi.fn();
124
+ const listener = {
125
+ topic: "topic",
126
+ socket: { adapter: { connected: true } },
127
+ listen: (callback: (event: { data: unknown }) => void, options: { onStart: () => void; onEnd: () => void }) => {
128
+ lifecycle.callback = callback;
129
+ lifecycle.onStart = options.onStart;
130
+ lifecycle.onEnd = options.onEnd;
131
+ return unsubscribe;
132
+ },
133
+ };
134
+ return { listener: listener as unknown as ListenerInstance, lifecycle, unsubscribe };
135
+ };
136
+
137
+ it("restarts after the server ended the subscription and buffers until every user loaded", () => {
138
+ const { listener, lifecycle, unsubscribe } = createFakeListener();
139
+ const applied: unknown[] = [];
140
+ const host = {
141
+ tick: () => 1,
142
+ applySyncMessage: (_sync: unknown, message: unknown) => applied.push(message),
143
+ onLiveChange: vi.fn(),
144
+ onRemove: vi.fn(),
145
+ };
146
+ const subscription = new SyncSubscription({ id: "id", sync: { listener, type: "update" }, listener, host });
147
+ const first = {};
148
+ const second = {};
149
+ subscription.addUser(first);
150
+ lifecycle.onStart!();
151
+ expect(subscription.isLive()).toBeTrue();
152
+ lifecycle.onEnd!();
153
+ expect(subscription.isLive()).toBeFalse();
154
+ expect(host.onLiveChange).toHaveBeenCalledTimes(2);
155
+
156
+ subscription.addUser(second);
157
+ subscription.beginLoad(first);
158
+ subscription.beginLoad(second);
159
+ lifecycle.callback!({ data: "buffered" });
160
+ subscription.endLoad(first);
161
+ expect(applied).toStrictEqual([]);
162
+ subscription.endLoad(second);
163
+ expect(applied).toStrictEqual(["buffered"]);
164
+
165
+ subscription.removeUser(first);
166
+ expect(host.onRemove).not.toHaveBeenCalled();
167
+ subscription.removeUser(second);
168
+ expect(unsubscribe).toHaveBeenCalledOnce();
169
+ expect(host.onRemove).toHaveBeenCalledWith(subscription);
170
+ });
171
+
172
+ it("clears the timers of sync waits when the db is destroyed", () => {
173
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
174
+ try {
175
+ const runtime = new DbRuntime({});
176
+ const wait = runtime.waitForSync({ collection: "post", key: 1, since: 0, timeout: 10_000 });
177
+ expect(wait).toBeInstanceOf(Promise);
178
+ expect(vi.getTimerCount()).toBe(1);
179
+ runtime.destroy();
180
+ expect(vi.getTimerCount()).toBe(0);
181
+ } finally {
182
+ vi.useRealTimers();
183
+ }
184
+ });
185
+ });
@@ -0,0 +1,73 @@
1
+ import { createSerializer } from "@hyper-fetch/db";
2
+
3
+ describe("db [ Serializer ]", () => {
4
+ const serializer = createSerializer();
5
+ const roundTrip = (value: unknown) => serializer.parse(serializer.stringify(value));
6
+
7
+ it("brings back values JSON loses", () => {
8
+ const value = {
9
+ date: new Date("2026-11-21T10:00:00.000Z"),
10
+ big: 12_345_678_901_234_567_890n,
11
+ map: new Map<unknown, unknown>([
12
+ [1, "one"],
13
+ ["nested", new Set([new Date(0)])],
14
+ ]),
15
+ set: new Set(["a", "b"]),
16
+ missing: undefined,
17
+ nan: Number.NaN,
18
+ inf: Infinity,
19
+ negInf: -Infinity,
20
+ list: [undefined, 1, null, "x"],
21
+ invalid: new Date(Number.NaN),
22
+ };
23
+ const restored = roundTrip(value) as typeof value;
24
+ expect(restored).toStrictEqual(value);
25
+ expect(restored.date).toBeInstanceOf(Date);
26
+ expect(Object.keys(restored)).toContain("missing");
27
+ });
28
+
29
+ it("keeps absent fields absent and keeps numeric and string keys apart", () => {
30
+ const restored = roundTrip({
31
+ rows: [
32
+ [1, { id: 1 }],
33
+ ["1", { id: "1" }],
34
+ ],
35
+ only: { a: 1 },
36
+ }) as {
37
+ rows: [unknown, unknown][];
38
+ only: object;
39
+ };
40
+ expect(restored.rows.map(([key]) => typeof key)).toStrictEqual(["number", "string"]);
41
+ expect(Object.keys(restored.only)).toStrictEqual(["a"]);
42
+ });
43
+
44
+ it("never reads a plain object that has the tag key as a tagged value", () => {
45
+ const value = { $hf: "Date", v: 1, other: { $hf: "undefined" } };
46
+ expect(roundTrip(value)).toStrictEqual(value);
47
+ });
48
+
49
+ it("stores other types through codecs and fails clearly for an unknown tag", () => {
50
+ class Money {
51
+ constructor(readonly cents: number) {}
52
+ }
53
+ const withCodec = createSerializer([
54
+ {
55
+ name: "Money",
56
+ test: (value) => value instanceof Money,
57
+ encode: (value) => (value as Money).cents,
58
+ decode: (value) => new Money(value as number),
59
+ },
60
+ ]);
61
+ const restored = withCodec.parse(withCodec.stringify({ price: new Money(250) })) as { price: Money };
62
+ expect(restored.price).toBeInstanceOf(Money);
63
+ expect(restored.price.cents).toBe(250);
64
+ expect(() => serializer.parse(withCodec.stringify(new Money(1)))).toThrow(
65
+ 'No codec decodes stored values tagged "Money"',
66
+ );
67
+ });
68
+
69
+ it("leaves plain JSON as it is", () => {
70
+ expect(serializer.stringify({ a: [1, "b", true, null] })).toBe('{"a":[1,"b",true,null]}');
71
+ expect(roundTrip(Object.create(null))).toStrictEqual({});
72
+ });
73
+ });