@spooky-sync/core 0.0.1-canary.13 → 0.0.1-canary.130

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 (90) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +1171 -372
  3. package/dist/index.js +5716 -1278
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/sqlite-worker.d.ts +1 -0
  7. package/dist/sqlite-worker.js +107 -0
  8. package/dist/types.d.ts +746 -0
  9. package/package.json +39 -8
  10. package/skills/sp00ky-core/SKILL.md +258 -0
  11. package/skills/sp00ky-core/references/auth.md +98 -0
  12. package/skills/sp00ky-core/references/config.md +76 -0
  13. package/src/build-globals.d.ts +12 -0
  14. package/src/events/events.test.ts +2 -1
  15. package/src/events/index.ts +3 -0
  16. package/src/index.ts +9 -2
  17. package/src/modules/auth/events/index.ts +2 -1
  18. package/src/modules/auth/index.ts +59 -20
  19. package/src/modules/cache/index.ts +77 -32
  20. package/src/modules/cache/types.ts +2 -2
  21. package/src/modules/crdt/crdt-field.ts +288 -0
  22. package/src/modules/crdt/crdt-hydration.test.ts +206 -0
  23. package/src/modules/crdt/index.ts +357 -0
  24. package/src/modules/data/data.hydration.test.ts +150 -0
  25. package/src/modules/data/data.rebind.test.ts +147 -0
  26. package/src/modules/data/data.recurring.test.ts +137 -0
  27. package/src/modules/data/data.status.test.ts +249 -0
  28. package/src/modules/data/index.ts +1228 -127
  29. package/src/modules/data/window-query.test.ts +52 -0
  30. package/src/modules/data/window-query.ts +154 -0
  31. package/src/modules/devtools/index.ts +191 -30
  32. package/src/modules/devtools/versions.test.ts +74 -0
  33. package/src/modules/devtools/versions.ts +81 -0
  34. package/src/modules/feature-flag/index.test.ts +120 -0
  35. package/src/modules/feature-flag/index.ts +209 -0
  36. package/src/modules/ref-tables.test.ts +91 -0
  37. package/src/modules/ref-tables.ts +88 -0
  38. package/src/modules/sync/engine.ts +101 -37
  39. package/src/modules/sync/events/index.ts +9 -2
  40. package/src/modules/sync/queue/queue-down.ts +12 -5
  41. package/src/modules/sync/queue/queue-up.ts +29 -14
  42. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  43. package/src/modules/sync/scheduler.ts +73 -7
  44. package/src/modules/sync/sync.health.test.ts +149 -0
  45. package/src/modules/sync/sync.subquery.test.ts +82 -0
  46. package/src/modules/sync/sync.ts +1017 -62
  47. package/src/modules/sync/utils.test.ts +269 -2
  48. package/src/modules/sync/utils.ts +182 -17
  49. package/src/otel/index.ts +127 -0
  50. package/src/services/database/cache-engine.ts +143 -0
  51. package/src/services/database/database.ts +11 -11
  52. package/src/services/database/engine-factory.ts +32 -0
  53. package/src/services/database/events/index.ts +2 -1
  54. package/src/services/database/index.ts +6 -0
  55. package/src/services/database/local-migrator.ts +28 -27
  56. package/src/services/database/local.test.ts +64 -0
  57. package/src/services/database/local.ts +452 -66
  58. package/src/services/database/plan-render.test.ts +133 -0
  59. package/src/services/database/plan-render.ts +100 -0
  60. package/src/services/database/relation-resolver.test.ts +413 -0
  61. package/src/services/database/relation-resolver.ts +0 -0
  62. package/src/services/database/remote.ts +13 -13
  63. package/src/services/database/sqlite-cache-engine.test.ts +85 -0
  64. package/src/services/database/sqlite-cache-engine.ts +699 -0
  65. package/src/services/database/sqlite-worker.ts +116 -0
  66. package/src/services/database/surql-translate.ts +291 -0
  67. package/src/services/database/surreal-cache-engine.ts +122 -0
  68. package/src/services/logger/index.ts +6 -101
  69. package/src/services/persistence/localstorage.ts +2 -2
  70. package/src/services/persistence/resilient.ts +41 -0
  71. package/src/services/persistence/surrealdb.ts +10 -10
  72. package/src/services/stream-processor/index.ts +295 -38
  73. package/src/services/stream-processor/permissions.test.ts +47 -0
  74. package/src/services/stream-processor/permissions.ts +53 -0
  75. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  76. package/src/services/stream-processor/stream-processor.reset.test.ts +104 -0
  77. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  78. package/src/services/stream-processor/wasm-types.ts +18 -2
  79. package/src/sp00ky.auth-order.test.ts +92 -0
  80. package/src/sp00ky.init-query.test.ts +185 -0
  81. package/src/sp00ky.ts +1016 -0
  82. package/src/types.ts +258 -15
  83. package/src/utils/error-classification.test.ts +44 -0
  84. package/src/utils/error-classification.ts +7 -0
  85. package/src/utils/index.ts +35 -13
  86. package/src/utils/parser.ts +3 -2
  87. package/src/utils/surql.ts +24 -15
  88. package/src/utils/withRetry.test.ts +1 -1
  89. package/tsdown.config.ts +77 -1
  90. package/src/spooky.ts +0 -392
@@ -0,0 +1,699 @@
1
+ import { applyPatch, type Operation } from 'fast-json-patch';
2
+ import type { QueryPlan, WhereNode, WhereComparison } from '@spooky-sync/query-builder';
3
+ import type { Logger } from '../logger/index';
4
+ import type { Sp00kyConfig } from '../../types';
5
+ import type { SealedQuery } from '../../utils/surql';
6
+ import { resolveRelations, stableKey } from './relation-resolver';
7
+ import {
8
+ createDatabaseEventSystem,
9
+ DatabaseEventTypes,
10
+ type DatabaseEventSystem,
11
+ } from './events/index';
12
+ import { StaleEpochError } from './local';
13
+ import { translateSurql, tableOf, setPath, getPath, type SqlOp } from './surql-translate';
14
+ import type { EngineTx, Id, LocalStore, OrderBy, RelationFetch, Row } from './cache-engine';
15
+
16
+ /**
17
+ * The statement result a pure-write op contributes to a query's results array.
18
+ * Single source of truth shared by the per-op path (`execOp`) and the batched
19
+ * fast path in `query()`, so the two can never diverge: a caller that reads a
20
+ * statement's output sees the same shape whether or not the transaction took the
21
+ * batch fast path. In particular `create()` compiles to an all-upsert tx
22
+ * (`createSet` + `createMutation`) and reads `resultIndex:0` for the new row and
23
+ * its id — the fast path previously returned empty arrays there, so the row (and
24
+ * its id) was lost and the reconcile crashed in `encodeRecordId`.
25
+ *
26
+ * An upsert echoes the written row (`{...data, id}`) with no read-back — the
27
+ * full merged row is only materialized for a LET-wrapped upsert (see the 'let'
28
+ * case). delete/deleteAll yield `[]`; noop yields `null`.
29
+ */
30
+ export function pureWriteOpResult(op: SqlOp): unknown {
31
+ switch (op.kind) {
32
+ case 'upsert':
33
+ return { ...op.data, id: stableKey(op.id) };
34
+ case 'noop':
35
+ return null;
36
+ default:
37
+ return [];
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Local cache backend on official SQLite-WASM in a dedicated Worker (see
43
+ * `sqlite-worker.ts`), with OPFS SAHPool persistence. Storage model: one table
44
+ * per schema table, `id TEXT PRIMARY KEY, data TEXT` where `data` is the row as
45
+ * JSON. Filtering/ordering use `json_extract`. Relations are decomposed by the
46
+ * shared {@link resolveRelations} — identical to the SurrealDB backend.
47
+ *
48
+ * Value normalization (JSON round-trip):
49
+ * - `Uint8Array`/bytes → `{ "__u8": <base64> }` (CRDT snapshots survive).
50
+ * - Record links / ids → their `table:id` string form (so `json_extract`
51
+ * comparisons and `IN` matching are consistent). NOTE: link fields therefore
52
+ * read back as strings, not `RecordId` instances — the one shape difference
53
+ * from the SurrealDB backend, to be closed with schema-driven revival + an
54
+ * oracle E2E in the browser.
55
+ */
56
+ export class SqliteCacheEngine implements LocalStore {
57
+ private worker: Worker | null = null;
58
+ private seq = 0;
59
+ private pending = new Map<number, { resolve: (v: any) => void; reject: (e: any) => void }>();
60
+ private storeEpoch = 0;
61
+ private knownTables = new Set<string>();
62
+ private useOpfs: boolean;
63
+ private events: DatabaseEventSystem = createDatabaseEventSystem();
64
+ private bucketId = 'anon';
65
+ /** Schemaless — tables are created lazily on first write; no migrator. */
66
+ readonly usesSurqlSchema = false;
67
+
68
+ constructor(
69
+ private config: Sp00kyConfig<any>['database'],
70
+ private logger: Logger,
71
+ opts: { useOpfs?: boolean } = {}
72
+ ) {
73
+ this.useOpfs = opts.useOpfs ?? true;
74
+ }
75
+
76
+ get epoch(): number {
77
+ return this.storeEpoch;
78
+ }
79
+
80
+ get currentBucketId(): string {
81
+ return this.bucketId;
82
+ }
83
+
84
+ getConfig(): Sp00kyConfig<any>['database'] {
85
+ return this.config;
86
+ }
87
+
88
+ getEvents(): DatabaseEventSystem {
89
+ return this.events;
90
+ }
91
+
92
+ getClient(): unknown {
93
+ throw new Error('SqliteCacheEngine has no SurrealDB client (getClient is unavailable).');
94
+ }
95
+
96
+ /** LocalStore alias; SQLite has no in-flight gate, so this maps to a rebuild. */
97
+ switchStore(bucketId: string): Promise<void> {
98
+ return this.switchBucket(bucketId);
99
+ }
100
+
101
+ /** SQLite has no switch gate window; the epoch bump alone fences stale writes. */
102
+ beginSwitch(): () => void {
103
+ return () => {};
104
+ }
105
+
106
+ // ---- worker plumbing -----------------------------------------------------
107
+
108
+ private spawnWorker(): Worker {
109
+ // Source references the `.ts` so the monorepo's src-bundling consumers
110
+ // (e.g. the example app, which aliases `@spooky-sync/core` to `src`) resolve
111
+ // it — Vite handles `.ts` workers. For the published package, the tsdown
112
+ // build rewrites this to `./sqlite-worker.js` (the top-level emitted entry;
113
+ // see tsdown.config.ts), which the flat `dist/index.js` resolves. The worker
114
+ // (+ `@sqlite.org/sqlite-wasm`) still loads lazily — only when `localEngine:
115
+ // 'sqlite'` is used.
116
+ const worker = new Worker(new URL('./sqlite-worker.ts', import.meta.url), { type: 'module' });
117
+ worker.onmessage = (ev: MessageEvent) => {
118
+ const { id, ok, error, ...rest } = ev.data ?? {};
119
+ const p = this.pending.get(id);
120
+ if (!p) return;
121
+ this.pending.delete(id);
122
+ if (ok) p.resolve(rest);
123
+ else p.reject(new Error(error));
124
+ };
125
+ // Surface a worker crash (wasm abort / OOM) instead of leaving every pending
126
+ // call hung forever — reject them all with a clear error.
127
+ const failAll = (msg: string) => {
128
+ const err = new Error(`SQLite worker crashed: ${msg}`);
129
+ this.logger.error(
130
+ { err, Category: 'sp00ky-client::SqliteCacheEngine::worker' },
131
+ 'Worker error'
132
+ );
133
+ for (const [, p] of this.pending) p.reject(err);
134
+ this.pending.clear();
135
+ };
136
+ worker.onerror = (e: ErrorEvent) => failAll(e.message || 'onerror');
137
+ worker.onmessageerror = () => failAll('messageerror');
138
+ return worker;
139
+ }
140
+
141
+ /** Serializes every worker op so reads/writes never overlap at the VFS layer
142
+ * (overlapping ops trip SQLITE_BUSY). Mirrors the SurrealDB engine's
143
+ * single-flight query queue. */
144
+ private opQueue: Promise<unknown> = Promise.resolve();
145
+
146
+ private call<T = any>(type: string, payload?: unknown): Promise<T> {
147
+ const run = () => this.rawCall<T>(type, payload);
148
+ const result = this.opQueue.then(run, run);
149
+ // Keep the chain alive regardless of individual failures.
150
+ this.opQueue = result.then(
151
+ () => undefined,
152
+ () => undefined
153
+ );
154
+ return result;
155
+ }
156
+
157
+ private rawCall<T = any>(type: string, payload?: unknown): Promise<T> {
158
+ if (!this.worker) throw new Error('SqliteCacheEngine: not connected');
159
+ const id = ++this.seq;
160
+ // --- instrumentation: live, inspectable via `globalThis.__sqliteStats` ---
161
+ const s = getStats();
162
+ s.roundTrips++;
163
+ s.byType[type] = (s.byType[type] ?? 0) + 1;
164
+ if (type === 'batch' && Array.isArray(payload)) {
165
+ s.batchStatements += payload.length;
166
+ s.maxBatch = Math.max(s.maxBatch, payload.length);
167
+ }
168
+ s.inFlight++;
169
+ s.maxInFlight = Math.max(s.maxInFlight, s.inFlight);
170
+ const done = () => {
171
+ s.inFlight--;
172
+ };
173
+ return new Promise<T>((resolve, reject) => {
174
+ this.pending.set(id, {
175
+ resolve: (v: T) => {
176
+ done();
177
+ resolve(v);
178
+ },
179
+ reject: (e: unknown) => {
180
+ done();
181
+ reject(e);
182
+ },
183
+ });
184
+ this.worker!.postMessage({ id, type, payload });
185
+ });
186
+ }
187
+
188
+ async connect(bucketId: string): Promise<void> {
189
+ this.worker = this.spawnWorker();
190
+ const { persisted } = await this.call<{ persisted: boolean }>('open', {
191
+ dbName: bucketId,
192
+ useOpfs: this.useOpfs,
193
+ });
194
+ this.knownTables.clear();
195
+ this.bucketId = bucketId;
196
+ this.logger.info(
197
+ { bucketId, persisted, Category: 'sp00ky-client::SqliteCacheEngine::connect' },
198
+ persisted ? 'SQLite OPFS store opened' : 'SQLite in-memory store opened (no OPFS)'
199
+ );
200
+ }
201
+
202
+ async switchBucket(bucketId: string): Promise<void> {
203
+ this.storeEpoch++;
204
+ if (this.worker) {
205
+ try {
206
+ await this.call('close');
207
+ } catch {
208
+ /* ignore */
209
+ }
210
+ this.worker.terminate();
211
+ this.worker = null;
212
+ }
213
+ await this.connect(bucketId);
214
+ }
215
+
216
+ async close(): Promise<void> {
217
+ if (!this.worker) return;
218
+ try {
219
+ await this.call('close');
220
+ } catch {
221
+ /* ignore */
222
+ }
223
+ this.worker.terminate();
224
+ this.worker = null;
225
+ }
226
+
227
+ private async ensureTable(table: string): Promise<void> {
228
+ if (this.knownTables.has(table)) return;
229
+ await this.call('run', {
230
+ sql: `CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
231
+ });
232
+ this.knownTables.add(table);
233
+ }
234
+
235
+ private async execRows(sql: string, bind: unknown[]): Promise<Row[]> {
236
+ const { rows } = await this.call<{ rows: { data: string }[] }>('exec', { sql, bind });
237
+ return (rows ?? []).map((r) => reviveRow(r.data));
238
+ }
239
+
240
+ // ---- reads ---------------------------------------------------------------
241
+
242
+ async select(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<Row[]> {
243
+ // Window materialization: base rows are exactly `plan.ids`, ordered.
244
+ if (plan.ids) {
245
+ const result = await this.selectByIds(plan.table, plan.ids, {
246
+ select: plan.select,
247
+ orderBy: plan.orderBy,
248
+ });
249
+ await resolveRelations(result, plan.relations, this);
250
+ return result;
251
+ }
252
+ await this.ensureTable(plan.table);
253
+ const bind: unknown[] = [];
254
+ const proj = 'data';
255
+ let sql = `SELECT ${proj} FROM "${plan.table}"`;
256
+ if (plan.where && plan.where.length > 0) {
257
+ sql += ` WHERE ${renderWhereSql(plan.where, bind, params)}`;
258
+ }
259
+ if (plan.orderBy && plan.orderBy.length > 0) sql += renderOrderSql(plan.orderBy);
260
+ if (plan.limit !== undefined) sql += ` LIMIT ${Number(plan.limit)}`;
261
+ if (plan.offset !== undefined) sql += ` OFFSET ${Number(plan.offset)}`;
262
+ const rows = await this.execRows(sql, bind);
263
+ // Optional projection trimming to match `SELECT <fields>`.
264
+ const projected = plan.select ? rows.map((r) => project(r, plan.select!)) : rows;
265
+ await resolveRelations(projected, plan.relations, this);
266
+ return projected;
267
+ }
268
+
269
+ async fetchRelation(req: RelationFetch): Promise<Row[]> {
270
+ await this.ensureTable(req.table);
271
+ const keys = req.keys.map(stableKey);
272
+ const placeholders = keys.map(() => '?').join(', ');
273
+ const bind: unknown[] = [...keys];
274
+ const lhs = req.matchField === 'id' ? 'id' : `json_extract(data, '$.${req.matchField}')`;
275
+ let sql = `SELECT data FROM "${req.table}" WHERE ${lhs} IN (${placeholders})`;
276
+ if (req.where && req.where.length > 0) {
277
+ sql += ` AND ${renderWhereSql(req.where, bind, {})}`;
278
+ }
279
+ if (req.orderBy && req.orderBy.length > 0) sql += renderOrderSql(req.orderBy);
280
+ const rows = await this.execRows(sql, bind);
281
+ return req.select ? rows.map((r) => project(r, req.select!)) : rows;
282
+ }
283
+
284
+ async selectByIds(
285
+ table: string,
286
+ ids: Id[],
287
+ opts?: { select?: string[]; orderBy?: OrderBy }
288
+ ): Promise<Row[]> {
289
+ if (ids.length === 0) return [];
290
+ await this.ensureTable(table);
291
+ const keys = ids.map(stableKey);
292
+ const placeholders = keys.map(() => '?').join(', ');
293
+ let sql = `SELECT data FROM "${table}" WHERE id IN (${placeholders})`;
294
+ if (opts?.orderBy && opts.orderBy.length > 0) sql += renderOrderSql(opts.orderBy);
295
+ let rows = await this.execRows(sql, keys);
296
+ if (!opts?.orderBy || opts.orderBy.length === 0) {
297
+ const pos = new Map(keys.map((k, i) => [k, i]));
298
+ rows = rows.sort((a, b) => (pos.get(stableKey(a.id)) ?? 0) - (pos.get(stableKey(b.id)) ?? 0));
299
+ }
300
+ return opts?.select ? rows.map((r) => project(r, opts.select!)) : rows;
301
+ }
302
+
303
+ async getById(table: string, id: Id): Promise<Row | null> {
304
+ await this.ensureTable(table);
305
+ const rows = await this.execRows(`SELECT data FROM "${table}" WHERE id = ?`, [stableKey(id)]);
306
+ return rows[0] ?? null;
307
+ }
308
+
309
+ // ---- writes --------------------------------------------------------------
310
+
311
+ async upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void> {
312
+ await this.ensureTable(table);
313
+ const key = stableKey(id);
314
+ if (mode === 'merge') {
315
+ // Merge in-SQL via json_patch (RFC7396 = MERGE semantics): on insert store
316
+ // the row, on conflict shallow-merge. Serialize once, reuse for VALUES and
317
+ // the patch. No read-modify-write round-trip. (RFC7396: null deletes key.)
318
+ const full = serializeRow({ ...data, id: key });
319
+ await this.call('run', {
320
+ sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
321
+ bind: [key, full, full],
322
+ });
323
+ return;
324
+ }
325
+ await this.call('run', {
326
+ sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`,
327
+ bind: [key, serializeRow({ ...data, id: key })],
328
+ });
329
+ }
330
+
331
+ async patch(table: string, id: Id, patches: unknown[]): Promise<void> {
332
+ // RFC6902 (fast-json-patch) applied read-modify-write — SQLite's json_patch
333
+ // is RFC7396 merge-patch and would misinterpret op arrays.
334
+ const existing = (await this.getById(table, id)) ?? { id: stableKey(id) };
335
+ const next = applyPatch(existing, patches as Operation[]).newDocument as Row;
336
+ await this.upsert(table, id, next, 'replace');
337
+ }
338
+
339
+ async delete(table: string, id: Id): Promise<void> {
340
+ await this.ensureTable(table);
341
+ await this.call('run', { sql: `DELETE FROM "${table}" WHERE id = ?`, bind: [stableKey(id)] });
342
+ }
343
+
344
+ // ---- SurrealQL-vocabulary shim (LocalStore compatibility) ---------------
345
+
346
+ /**
347
+ * Execute a raw SurrealQL statement by translating the client's bounded
348
+ * vocabulary to verbs (see `surql-translate.ts`). Returns results shaped like
349
+ * SurrealDB's `.query()` (one element per statement; a tx prepends a `null`
350
+ * begin-result so `surql.seal` extraction lines up). Epoch-fences writes.
351
+ */
352
+ async query<T extends unknown[]>(
353
+ sql: string,
354
+ vars: Record<string, unknown> = {},
355
+ opts?: { epoch?: number }
356
+ ): Promise<T> {
357
+ if (opts?.epoch !== undefined && opts.epoch !== this.storeEpoch) throw new StaleEpochError();
358
+ const start = performance.now();
359
+ try {
360
+ const { transaction, ops } = translateSurql(sql, vars);
361
+ let shaped: unknown[];
362
+ // FAST PATH: a pure-write transaction (bulk sync-down is one
363
+ // `tx([upsertMerge…])`) compiles to a SINGLE worker `batch` message run in
364
+ // one SQLite transaction — instead of 1-2 worker round-trips PER row. This
365
+ // is the dominant sync-down cost; per-op execution here caused the churn
366
+ // OOM. Mixed txs (LET/RETURN single-record mutations) keep the per-op path.
367
+ if (
368
+ transaction &&
369
+ ops.every(
370
+ (o) =>
371
+ o.kind === 'upsert' ||
372
+ o.kind === 'delete' ||
373
+ o.kind === 'deleteAll' ||
374
+ o.kind === 'noop'
375
+ )
376
+ ) {
377
+ await this.runWriteBatch(ops);
378
+ // Shape each statement's result the SAME as the per-op path (`execOp`),
379
+ // so a caller reading a statement's output still works after taking the
380
+ // batch fast path. A single `create()` compiles to an all-upsert tx
381
+ // (createSet + createMutation) and reads `resultIndex:0` for the new
382
+ // row + its id; returning empty arrays here dropped that row (id became
383
+ // undefined → the reconcile crashed in `encodeRecordId`). The
384
+ // single-batch write is kept — this only rebuilds the return value.
385
+ shaped = [null, ...ops.map(pureWriteOpResult)];
386
+ } else {
387
+ const results: unknown[] = [];
388
+ // Per-query scope holds `LET $var = (...)` bindings for later statements
389
+ // (e.g. `RETURN { target: $updated }`).
390
+ const scope: Record<string, unknown> = {};
391
+ for (const op of ops) results.push(await this.execOp(op, scope, vars));
392
+ shaped = transaction ? [null, ...results] : results;
393
+ }
394
+ this.events.emit(DatabaseEventTypes.LocalQuery, {
395
+ query: sql,
396
+ vars,
397
+ duration: performance.now() - start,
398
+ success: true,
399
+ timestamp: Date.now(),
400
+ });
401
+ return shaped as unknown as T;
402
+ } catch (err) {
403
+ this.events.emit(DatabaseEventTypes.LocalQuery, {
404
+ query: sql,
405
+ vars,
406
+ duration: performance.now() - start,
407
+ success: false,
408
+ error: err instanceof Error ? err.message : String(err),
409
+ timestamp: Date.now(),
410
+ });
411
+ throw err;
412
+ }
413
+ }
414
+
415
+ async execute<R>(
416
+ query: SealedQuery<R>,
417
+ vars?: Record<string, unknown>,
418
+ opts?: { epoch?: number }
419
+ ): Promise<R> {
420
+ const raw = await this.query<unknown[]>(query.sql, vars, opts);
421
+ return query.extract(raw);
422
+ }
423
+
424
+ queryUngated<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T> {
425
+ return this.query<T>(sql, vars);
426
+ }
427
+
428
+ private async execOp(
429
+ op: SqlOp,
430
+ scope: Record<string, unknown>,
431
+ vars: Record<string, unknown>
432
+ ): Promise<unknown> {
433
+ switch (op.kind) {
434
+ case 'getById': {
435
+ const row = await this.getById(tableOf(op.id), op.id);
436
+ if (op.value) return row ? (row[op.value] ?? null) : null;
437
+ return row ? (op.select ? project(row, op.select) : row) : null;
438
+ }
439
+ case 'selectByIds': {
440
+ if (op.ids.length === 0) return [];
441
+ let rows = await this.selectByIds(tableOf(op.ids[0]), op.ids, {
442
+ select: op.select,
443
+ orderBy: op.orderBy,
444
+ });
445
+ if (op.value) return rows.map((r) => r[op.value!]);
446
+ return rows;
447
+ }
448
+ case 'selectTable': {
449
+ const rows = await this.rawSelectTable(op.table, op.where, op.orderBy);
450
+ if (op.value) return rows.map((r) => r[op.value!]);
451
+ return op.select ? rows.map((r) => project(r, op.select!)) : rows;
452
+ }
453
+ case 'upsert':
454
+ await this.upsert(tableOf(op.id), op.id, op.data, op.mode);
455
+ // Cheap return — no read-back. The full merged row is only needed by a
456
+ // LET-wrapped upsert, which reads it back in the 'let' case below. This
457
+ // avoids an extra worker round-trip + full-row parse on EVERY sync-down
458
+ // write (the hot path under rapid churn). Shared with the batch fast
459
+ // path so the two never drift.
460
+ return pureWriteOpResult(op);
461
+ case 'updateSet': {
462
+ const existing = (await this.getById(tableOf(op.id), op.id)) ?? { id: stableKey(op.id) };
463
+ for (const { path, op: setOp, value } of op.sets) {
464
+ if (setOp === '+=' || setOp === '-=') {
465
+ const cur = Number(getPath(existing, path) ?? 0);
466
+ const delta = Number(value ?? 0);
467
+ setPath(existing, path, setOp === '+=' ? cur + delta : cur - delta);
468
+ } else {
469
+ setPath(existing, path, value);
470
+ }
471
+ }
472
+ await this.upsert(tableOf(op.id), op.id, existing, 'replace');
473
+ return op.returnNone ? null : existing;
474
+ }
475
+ case 'delete':
476
+ await this.delete(tableOf(op.id), op.id);
477
+ return pureWriteOpResult(op);
478
+ case 'deleteAll':
479
+ await this.ensureTable(op.table);
480
+ await this.call('run', { sql: `DELETE FROM "${op.table}"` });
481
+ return pureWriteOpResult(op);
482
+ case 'let': {
483
+ let result = await this.execOp(op.inner, scope, vars);
484
+ // A LET-bound UPSERT must expose the FULL merged row (e.g.
485
+ // `RETURN { target: $updated }`), so read it back here — only here,
486
+ // not on every upsert.
487
+ if (op.inner.kind === 'upsert') {
488
+ result = (await this.getById(tableOf(op.inner.id), op.inner.id)) ?? result;
489
+ }
490
+ scope[op.var] = result;
491
+ return result;
492
+ }
493
+ case 'return': {
494
+ const obj: Row = {};
495
+ for (const { key, var: v } of op.entries) {
496
+ obj[key] = v in scope ? scope[v] : vars[v];
497
+ }
498
+ return obj;
499
+ }
500
+ case 'noop':
501
+ return pureWriteOpResult(op);
502
+ }
503
+ }
504
+
505
+ /**
506
+ * Compile a pure-write op list to ONE worker `batch` (single SQLite
507
+ * transaction). Ensures each touched table exists, then one statement per op.
508
+ * Merges happen in-SQL via json_patch — no read-back round-trips.
509
+ */
510
+ private async runWriteBatch(ops: SqlOp[]): Promise<void> {
511
+ const stmts: { sql: string; bind?: unknown[] }[] = [];
512
+ const tables = new Set<string>();
513
+ const ensure = (t: string) => {
514
+ if (!tables.has(t)) {
515
+ tables.add(t);
516
+ this.knownTables.add(t);
517
+ stmts.push({
518
+ sql: `CREATE TABLE IF NOT EXISTS "${t}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
519
+ });
520
+ }
521
+ };
522
+ for (const op of ops) {
523
+ if (op.kind === 'upsert') {
524
+ const t = tableOf(op.id);
525
+ const key = stableKey(op.id);
526
+ ensure(t);
527
+ if (op.mode === 'merge') {
528
+ // Serialize ONCE and reuse for both VALUES (fresh insert) and the
529
+ // json_patch (merge). Patching with `id` is a harmless no-op set, so
530
+ // the full row doubles as the delta — halves per-row stringify cost.
531
+ const full = serializeRow({ ...op.data, id: key });
532
+ stmts.push({
533
+ sql: `INSERT INTO "${t}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
534
+ bind: [key, full, full],
535
+ });
536
+ } else {
537
+ stmts.push({
538
+ sql: `INSERT INTO "${t}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`,
539
+ bind: [key, serializeRow({ ...op.data, id: key })],
540
+ });
541
+ }
542
+ } else if (op.kind === 'delete') {
543
+ const t = tableOf(op.id);
544
+ ensure(t);
545
+ stmts.push({ sql: `DELETE FROM "${t}" WHERE id = ?`, bind: [stableKey(op.id)] });
546
+ } else if (op.kind === 'deleteAll') {
547
+ ensure(op.table);
548
+ stmts.push({ sql: `DELETE FROM "${op.table}"` });
549
+ }
550
+ }
551
+ if (stmts.length > 0) await this.call('batch', stmts);
552
+ }
553
+
554
+ private async rawSelectTable(
555
+ table: string,
556
+ where?: WhereNode[],
557
+ orderBy?: OrderBy
558
+ ): Promise<Row[]> {
559
+ await this.ensureTable(table);
560
+ const bind: unknown[] = [];
561
+ let sql = `SELECT data FROM "${table}"`;
562
+ if (where && where.length > 0) sql += ` WHERE ${renderWhereSql(where, bind, {})}`;
563
+ if (orderBy && orderBy.length > 0) sql += renderOrderSql(orderBy);
564
+ return this.execRows(sql, bind);
565
+ }
566
+
567
+ async transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T> {
568
+ // Verbs run in order on the single worker message channel. `patch` needs a
569
+ // read-modify-write round-trip, so a single BEGIN/COMMIT batch cannot wrap
570
+ // the whole closure; sequential execution is sufficient for the current
571
+ // single-record write sites.
572
+ const tx: EngineTx = {
573
+ upsert: (t, id, data, mode) => this.upsert(t, id, data, mode),
574
+ patch: (t, id, p) => this.patch(t, id, p),
575
+ delete: (t, id) => this.delete(t, id),
576
+ };
577
+ return fn(tx);
578
+ }
579
+ }
580
+
581
+ // ==================== instrumentation ====================
582
+
583
+ interface SqliteStats {
584
+ roundTrips: number;
585
+ batchStatements: number;
586
+ maxBatch: number;
587
+ inFlight: number;
588
+ maxInFlight: number;
589
+ byType: Record<string, number>;
590
+ }
591
+
592
+ /** Live stats, inspectable in the browser console via `__sqliteStats`. Counts
593
+ * worker round-trips (the sync-down cost driver), batch sizes, and queue depth
594
+ * (`maxInFlight`) so a churn OOM can be measured rather than guessed. */
595
+ function getStats(): SqliteStats {
596
+ const g = globalThis as unknown as { __sqliteStats?: SqliteStats };
597
+ if (!g.__sqliteStats) {
598
+ g.__sqliteStats = {
599
+ roundTrips: 0,
600
+ batchStatements: 0,
601
+ maxBatch: 0,
602
+ inFlight: 0,
603
+ maxInFlight: 0,
604
+ byType: {},
605
+ };
606
+ }
607
+ return g.__sqliteStats;
608
+ }
609
+
610
+ // ==================== SQL rendering ====================
611
+
612
+ function renderOrderSql(orderBy: OrderBy): string {
613
+ return ` ORDER BY ${orderBy
614
+ .map(([f, d]) => `json_extract(data, '$.${f}') ${d === 'desc' ? 'DESC' : 'ASC'}`)
615
+ .join(', ')}`;
616
+ }
617
+
618
+ function comparisonSql(
619
+ c: WhereComparison,
620
+ bind: unknown[],
621
+ params: Record<string, unknown>
622
+ ): string {
623
+ const lhs = c.field === 'id' ? 'id' : `json_extract(data, '$.${c.field}')`;
624
+ const value = c.paramRef ? params[c.paramRef] : c.value;
625
+ bind.push(scalar(value));
626
+ const op = c.op === '!=' ? '!=' : c.op;
627
+ return c.swap ? `? ${op} ${lhs}` : `${lhs} ${op} ?`;
628
+ }
629
+
630
+ function renderWhereSql(
631
+ nodes: WhereNode[],
632
+ bind: unknown[],
633
+ params: Record<string, unknown>
634
+ ): string {
635
+ return nodes
636
+ .map((node) => {
637
+ if ('or' in node) {
638
+ return `(${node.or.map((c) => comparisonSql(c, bind, params)).join(' OR ')})`;
639
+ }
640
+ return comparisonSql(node, bind, params);
641
+ })
642
+ .join(' AND ');
643
+ }
644
+
645
+ // ==================== value (de)serialization ====================
646
+
647
+ /** A comparable scalar for SQL binding: record links → `table:id`, everything
648
+ * else passed through (numbers/strings/bools). */
649
+ function scalar(value: unknown): unknown {
650
+ if (value == null) return null;
651
+ if (typeof value === 'object') return stableKey(value);
652
+ return value;
653
+ }
654
+
655
+ function serializeRow(row: Row): string {
656
+ return JSON.stringify(row, (_k, v) => {
657
+ if (v instanceof Uint8Array) return { __u8: toBase64(v) };
658
+ if (v && typeof v === 'object') {
659
+ const rid = v as { tb?: unknown; id?: unknown };
660
+ if (rid.tb !== undefined && rid.id !== undefined) return stableKey(v);
661
+ }
662
+ return v;
663
+ });
664
+ }
665
+
666
+ function reviveRow(json: string): Row {
667
+ // Fast path: the per-key reviver is only needed to rebuild `Uint8Array`s from
668
+ // `{__u8}` tags. Most rows (e.g. game bodies) have none — a plain parse avoids
669
+ // invoking a JS callback for every key of every row on the read hot path.
670
+ if (json.indexOf('"__u8"') === -1) return JSON.parse(json);
671
+ return JSON.parse(json, (_k, v) => {
672
+ if (v && typeof v === 'object' && typeof (v as any).__u8 === 'string') {
673
+ return fromBase64((v as any).__u8);
674
+ }
675
+ return v;
676
+ });
677
+ }
678
+
679
+ function project(row: Row, fields: string[]): Row {
680
+ const out: Row = {};
681
+ for (const f of ['id', ...fields]) if (f in row) out[f] = row[f];
682
+ return out;
683
+ }
684
+
685
+ function toBase64(bytes: Uint8Array): string {
686
+ let bin = '';
687
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
688
+ return typeof btoa !== 'undefined' ? btoa(bin) : Buffer.from(bytes).toString('base64');
689
+ }
690
+
691
+ function fromBase64(b64: string): Uint8Array {
692
+ if (typeof atob !== 'undefined') {
693
+ const bin = atob(b64);
694
+ const out = new Uint8Array(bin.length);
695
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
696
+ return out;
697
+ }
698
+ return new Uint8Array(Buffer.from(b64, 'base64'));
699
+ }