@spooky-sync/core 0.0.1-canary.21 → 0.0.1-canary.210

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 (163) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2514 -58
  3. package/dist/index.js +12561 -2449
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +303 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +439 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +472 -0
  11. package/dist/types.d.ts +751 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +36 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/auth.local-first.test.ts +101 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +127 -24
  27. package/src/modules/cache/cache.relay.test.ts +95 -0
  28. package/src/modules/cache/index.ts +163 -43
  29. package/src/modules/cache/types.ts +2 -2
  30. package/src/modules/crdt/crdt-field.ts +294 -0
  31. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  32. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  33. package/src/modules/crdt/index.ts +463 -0
  34. package/src/modules/crdt/loro-loader.ts +25 -0
  35. package/src/modules/data/data.hydration.test.ts +142 -0
  36. package/src/modules/data/data.membership.test.ts +523 -0
  37. package/src/modules/data/data.notify-table.test.ts +41 -0
  38. package/src/modules/data/data.pending-ids.test.ts +199 -0
  39. package/src/modules/data/data.rebind.test.ts +170 -0
  40. package/src/modules/data/data.rematerialize.test.ts +114 -0
  41. package/src/modules/data/data.run.test.ts +113 -0
  42. package/src/modules/data/data.settled-writes.test.ts +206 -0
  43. package/src/modules/data/data.status.test.ts +249 -0
  44. package/src/modules/data/id-set-plan.test.ts +122 -0
  45. package/src/modules/data/index.ts +1815 -151
  46. package/src/modules/data/mutation-id.test.ts +25 -0
  47. package/src/modules/data/mutation-id.ts +35 -0
  48. package/src/modules/data/window-query.test.ts +52 -0
  49. package/src/modules/data/window-query.ts +194 -0
  50. package/src/modules/devtools/flags.ts +349 -0
  51. package/src/modules/devtools/index.ts +450 -46
  52. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  53. package/src/modules/devtools/state-shape.test.ts +146 -0
  54. package/src/modules/devtools/storage-info.test.ts +79 -0
  55. package/src/modules/devtools/storage-info.ts +168 -0
  56. package/src/modules/devtools/versions.test.ts +74 -0
  57. package/src/modules/devtools/versions.ts +110 -0
  58. package/src/modules/feature-flag/index.test.ts +251 -0
  59. package/src/modules/feature-flag/index.ts +308 -0
  60. package/src/modules/ref-tables.test.ts +91 -0
  61. package/src/modules/ref-tables.ts +88 -0
  62. package/src/modules/sync/engine.ts +164 -82
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +180 -0
  65. package/src/modules/sync/queue/queue-down.ts +80 -13
  66. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  67. package/src/modules/sync/queue/queue-up.ts +241 -57
  68. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  69. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  70. package/src/modules/sync/scheduler.ts +215 -13
  71. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  72. package/src/modules/sync/sync.health.test.ts +149 -0
  73. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  74. package/src/modules/sync/sync.live-removal.test.ts +175 -0
  75. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  76. package/src/modules/sync/sync.subquery.test.ts +82 -0
  77. package/src/modules/sync/sync.tabs.test.ts +249 -0
  78. package/src/modules/sync/sync.ts +1726 -99
  79. package/src/modules/sync/utils.test.ts +269 -2
  80. package/src/modules/sync/utils.ts +201 -17
  81. package/src/otel/index.ts +13 -10
  82. package/src/services/blobs/blob-cache.test.ts +359 -0
  83. package/src/services/blobs/blob-cache.ts +603 -0
  84. package/src/services/blobs/blob-manifest.ts +227 -0
  85. package/src/services/blobs/blob-store.test.ts +77 -0
  86. package/src/services/blobs/blob-store.ts +359 -0
  87. package/src/services/blobs/blob.fixture.ts +90 -0
  88. package/src/services/blobs/index.ts +70 -0
  89. package/src/services/database/cache-engine.ts +193 -0
  90. package/src/services/database/connection-supervisor.test.ts +289 -0
  91. package/src/services/database/connection-supervisor.ts +415 -0
  92. package/src/services/database/database.query-timeout.test.ts +83 -0
  93. package/src/services/database/database.ts +41 -12
  94. package/src/services/database/engine-factory.ts +33 -0
  95. package/src/services/database/errors.ts +34 -0
  96. package/src/services/database/events/index.ts +2 -1
  97. package/src/services/database/index.ts +7 -0
  98. package/src/services/database/local-migrator.ts +30 -27
  99. package/src/services/database/local.test.ts +64 -0
  100. package/src/services/database/local.ts +484 -67
  101. package/src/services/database/plan-render.test.ts +159 -0
  102. package/src/services/database/plan-render.ts +108 -0
  103. package/src/services/database/relation-resolver.test.ts +413 -0
  104. package/src/services/database/relation-resolver.ts +0 -0
  105. package/src/services/database/remote.ts +110 -14
  106. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  107. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  108. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  109. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  110. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  111. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  112. package/src/services/database/sqlite-lock-verify.ts +45 -0
  113. package/src/services/database/sqlite-open.test.ts +150 -0
  114. package/src/services/database/sqlite-open.ts +164 -0
  115. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  116. package/src/services/database/sqlite-plan-sql.ts +138 -0
  117. package/src/services/database/sqlite-projection.test.ts +99 -0
  118. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  119. package/src/services/database/sqlite-select.test.ts +246 -0
  120. package/src/services/database/sqlite-select.ts +131 -0
  121. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  122. package/src/services/database/sqlite-transport.ts +224 -0
  123. package/src/services/database/sqlite-worker.ts +437 -0
  124. package/src/services/database/surql-translate.ts +416 -0
  125. package/src/services/database/surreal-cache-engine.ts +161 -0
  126. package/src/services/logger/index.ts +3 -2
  127. package/src/services/persistence/localstorage.ts +2 -2
  128. package/src/services/persistence/resilient.ts +11 -4
  129. package/src/services/persistence/surrealdb.ts +10 -10
  130. package/src/services/stream-processor/index.ts +796 -84
  131. package/src/services/stream-processor/permissions.test.ts +47 -0
  132. package/src/services/stream-processor/permissions.ts +53 -0
  133. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  134. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  135. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  136. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  137. package/src/services/stream-processor/wasm-types.ts +59 -3
  138. package/src/services/tabs/broker-client.ts +283 -0
  139. package/src/services/tabs/broker.test.ts +327 -0
  140. package/src/services/tabs/coordinator.test.ts +365 -0
  141. package/src/services/tabs/coordinator.ts +633 -0
  142. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  143. package/src/services/tabs/leader-locks.ts +75 -0
  144. package/src/services/tabs/protocol.ts +258 -0
  145. package/src/services/tabs/support.ts +36 -0
  146. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  147. package/src/sp00ky.auth-order.test.ts +92 -0
  148. package/src/sp00ky.init-query.test.ts +183 -0
  149. package/src/sp00ky.local-first.test.ts +60 -0
  150. package/src/sp00ky.ts +1693 -0
  151. package/src/types.ts +528 -13
  152. package/src/utils/blurhash.ts +90 -0
  153. package/src/utils/error-classification.test.ts +44 -0
  154. package/src/utils/error-classification.ts +7 -0
  155. package/src/utils/index.ts +79 -13
  156. package/src/utils/parser.test.ts +49 -120
  157. package/src/utils/parser.ts +32 -2
  158. package/src/utils/semver.test.ts +32 -0
  159. package/src/utils/semver.ts +30 -0
  160. package/src/utils/surql.ts +30 -18
  161. package/src/utils/withRetry.test.ts +1 -1
  162. package/tsdown.config.ts +86 -1
  163. package/src/spooky.ts +0 -395
@@ -0,0 +1,1358 @@
1
+ import { applyPatch, type Operation } from 'fast-json-patch';
2
+ import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
3
+ import { withTimeout } from '../../utils/index';
4
+ import type { QueryPlan, RelationPlan, WhereNode } from '@spooky-sync/query-builder';
5
+ import {
6
+ renderOrderSql,
7
+ renderWhereSql,
8
+ reviveRow,
9
+ serializeRow,
10
+ project,
11
+ projectedDataSql,
12
+ } from './sqlite-plan-sql';
13
+ import type { Logger } from '../logger/index';
14
+ import type { Sp00kyConfig, StorageHealth } from '../../types';
15
+ import type { SnapshotMeta, StoredSnapshot } from './cache-engine';
16
+ import type { SealedQuery } from '../../utils/surql';
17
+ import { resolveRelations, stableKey } from './relation-resolver';
18
+ import {
19
+ createDatabaseEventSystem,
20
+ DatabaseEventTypes,
21
+ type DatabaseEventSystem,
22
+ } from './events/index';
23
+ import { StaleEpochError } from './local';
24
+ import { translateSurql, tableOf, setPath, getPath, type SqlOp } from './surql-translate';
25
+ import {
26
+ BrokerPortClosedError,
27
+ PortSqliteTransport,
28
+ WorkerSqliteTransport,
29
+ type SqliteTransport,
30
+ } from './sqlite-transport';
31
+ import { PROMOTION_OPEN_OPTIONS } from './sqlite-open';
32
+ import type { EngineTx, Id, LocalStore, OrderBy, RelationFetch, Row } from './cache-engine';
33
+ import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-info';
34
+
35
+ /**
36
+ * The statement result a pure-write op contributes to a query's results array.
37
+ * Single source of truth shared by the per-op path (`execOp`) and the batched
38
+ * fast path in `query()`, so the two can never diverge: a caller that reads a
39
+ * statement's output sees the same shape whether or not the transaction took the
40
+ * batch fast path. In particular `create()` compiles to an all-upsert tx
41
+ * (`createSet` + `createMutation`) and reads `resultIndex:0` for the new row and
42
+ * its id — the fast path previously returned empty arrays there, so the row (and
43
+ * its id) was lost and the reconcile crashed in `encodeRecordId`.
44
+ *
45
+ * An upsert echoes the written row (`{...data, id}`) with no read-back — the
46
+ * full merged row is only materialized for a LET-wrapped upsert (see the 'let'
47
+ * case). delete/deleteAll yield `[]`; noop yields `null`.
48
+ */
49
+ /**
50
+ * The `_00_*` internal tables the client relies on. The LocalMigrator DEFINEs
51
+ * them, but every DEFINE lowers to a noop on the SQLite engine, so they must be
52
+ * created physically at open (see `openInternal`) or a read-before-first-write
53
+ * on a fresh bucket throws "no such table". Keep in sync with the systemSchema
54
+ * block in `local-migrator.ts`.
55
+ */
56
+ const SNAPSHOT_TABLE = '_00_circuit_snapshot';
57
+
58
+ const SYSTEM_TABLES = [
59
+ '_00_stream_processor_state',
60
+ // In-browser circuit snapshot: one BLOB row (`circuit`) + a JSON meta row.
61
+ // Excluded from DevTools' table listing, since its data column is not JSON.
62
+ '_00_circuit_snapshot',
63
+ '_00_query',
64
+ '_00_preload',
65
+ '_00_window',
66
+ '_00_schema',
67
+ '_00_pending_mutations',
68
+ // Blob cache manifest. Read before its first write on every boot (reconcile
69
+ // asks for the ids it found in OPFS), so it has to exist up front like the
70
+ // rest — otherwise the very first reconcile throws and the cache runs cold.
71
+ '_00_blob',
72
+ // Server-written, synced-down meta tables (see meta_tables_client.surql).
73
+ // DEFINE is a noop on this engine, so without seeding them here their synced
74
+ // rows have no local table to land in: feature flags silently fall back to
75
+ // defaults and app-release update notifications never show.
76
+ '_00_user_feature',
77
+ '_00_app_release',
78
+ ] as const;
79
+
80
+ export function pureWriteOpResult(op: SqlOp): unknown {
81
+ switch (op.kind) {
82
+ case 'upsert':
83
+ return { ...op.data, id: stableKey(op.id) };
84
+ case 'noop':
85
+ return null;
86
+ default:
87
+ return [];
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Local cache backend on official SQLite-WASM in a dedicated Worker (see
93
+ * `sqlite-worker.ts`), with OPFS SAHPool persistence. Storage model: one table
94
+ * per schema table, `id TEXT PRIMARY KEY, data TEXT` where `data` is the row as
95
+ * JSON. Filtering/ordering use `json_extract`. Relations are decomposed by the
96
+ * shared {@link resolveRelations} — identical to the SurrealDB backend.
97
+ *
98
+ * Value normalization (JSON round-trip):
99
+ * - `Uint8Array`/bytes → `{ "__u8": <base64> }` (CRDT snapshots survive).
100
+ * - Record links / ids → their `table:id` string form (so `json_extract`
101
+ * comparisons and `IN` matching are consistent). NOTE: link fields therefore
102
+ * read back as strings, not `RecordId` instances — the one shape difference
103
+ * from the SurrealDB backend, to be closed with schema-driven revival + an
104
+ * oracle E2E in the browser.
105
+ */
106
+ export class SqliteCacheEngine implements LocalStore {
107
+ /** The wire to the SQLite worker: an owned dedicated Worker (solo/leader) or
108
+ * a MessagePort into another tab's worker (follower). See sqlite-transport. */
109
+ private transport: SqliteTransport | null = null;
110
+ private storeEpoch = 0;
111
+ private knownTables = new Set<string>();
112
+ private useOpfs: boolean;
113
+ /** Whether `select` runs as one worker round-trip (plan executed in-worker).
114
+ * Flipped off at runtime if the worker script predates the `select` op
115
+ * (stale cached bundle) — degrade to the legacy multi-hop path, don't break. */
116
+ private workerSelect: boolean;
117
+ /** What `workerSelect` was at construction, so DevTools can tell a runtime
118
+ * downgrade (configured true, effective false) from a configured-off. */
119
+ private workerSelectConfigured: boolean;
120
+ private events: DatabaseEventSystem = createDatabaseEventSystem();
121
+ private bucketId = 'anon';
122
+ /** Deadline for one worker round trip; see `localOpTimeoutMs`. */
123
+ private readonly localOpTimeoutMs: number;
124
+ /** Durability of the local store, set on every open. A plain Set of callbacks
125
+ * rather than a `DatabaseEventSystem` event: this changes at most once per
126
+ * open, and the typed event map is about query traffic. */
127
+ private storageHealthValue: StorageHealth = { status: 'unknown', fallback: false };
128
+ private storageHealthSubs = new Set<(health: StorageHealth) => void>();
129
+ /** Schemaless — tables are created lazily on first write; no migrator. */
130
+ readonly usesSurqlSchema = false;
131
+
132
+ readonly engineKind = 'sqlite' as const;
133
+
134
+ /** Shared-tabs mode: the engine's transport is swapped at runtime by the
135
+ * TabsCoordinator (owner worker as leader, leader's port as follower). */
136
+ private shared: boolean;
137
+ /** Leaderless parking (shared mode): ops entering the opQueue await this
138
+ * gate until a new role lands or the timeout rejects them. */
139
+ private roleGate: { promise: Promise<void>; release: () => void } | null = null;
140
+ private roleGateTimer: ReturnType<typeof setTimeout> | null = null;
141
+
142
+ constructor(
143
+ private config: Sp00kyConfig<any>['database'],
144
+ private logger: Logger,
145
+ opts: { useOpfs?: boolean; workerSelect?: boolean; shared?: boolean } = {}
146
+ ) {
147
+ this.localOpTimeoutMs = Math.max(0, config.localOpTimeoutMs ?? DEFAULT_LOCAL_OP_TIMEOUT_MS);
148
+ this.useOpfs = opts.useOpfs ?? true;
149
+ this.workerSelect = opts.workerSelect ?? config.workerSelect ?? true;
150
+ this.workerSelectConfigured = this.workerSelect;
151
+ this.shared = opts.shared ?? false;
152
+ }
153
+
154
+ get epoch(): number {
155
+ return this.storeEpoch;
156
+ }
157
+
158
+ get currentBucketId(): string {
159
+ return this.bucketId;
160
+ }
161
+
162
+ get storageHealth(): StorageHealth {
163
+ return this.storageHealthValue;
164
+ }
165
+
166
+ /** Fires immediately with the current snapshot (the store opens during
167
+ * `connect()`, before app components mount, so a late subscriber must still
168
+ * learn a fallback happened), then on every change. */
169
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void {
170
+ cb(this.storageHealthValue);
171
+ this.storageHealthSubs.add(cb);
172
+ return () => {
173
+ this.storageHealthSubs.delete(cb);
174
+ };
175
+ }
176
+
177
+ private setStorageHealth(health: StorageHealth): void {
178
+ this.storageHealthValue = health;
179
+ for (const cb of this.storageHealthSubs) cb(health);
180
+ }
181
+
182
+ getConfig(): Sp00kyConfig<any>['database'] {
183
+ return this.config;
184
+ }
185
+
186
+ /**
187
+ * Storage numbers for the DevTools Storage tab. Uses {@link call} so the
188
+ * reads serialize with regular traffic (no SQLITE_BUSY). Never throws — the
189
+ * worker may be mid bucket-switch; a failure lands in `error` instead.
190
+ */
191
+ async getStorageDiagnostics(opts?: { tableCounts?: boolean }): Promise<EngineStorageDiagnostics> {
192
+ const diag: EngineStorageDiagnostics = {
193
+ engine: 'sqlite',
194
+ bucketId: this.bucketId,
195
+ useOpfs: this.useOpfs,
196
+ workerSelectConfigured: this.workerSelectConfigured,
197
+ workerSelectEffective: this.workerSelect,
198
+ };
199
+ try {
200
+ const { rows } = await this.call<{ rows: { bytes: number; freelist: number }[] }>('exec', {
201
+ sql:
202
+ 'SELECT (SELECT * FROM pragma_page_count()) * (SELECT * FROM pragma_page_size()) AS bytes, ' +
203
+ '(SELECT * FROM pragma_freelist_count()) * (SELECT * FROM pragma_page_size()) AS freelist',
204
+ });
205
+ diag.dbSizeBytes = rows?.[0]?.bytes;
206
+ diag.freelistBytes = rows?.[0]?.freelist;
207
+ if (opts?.tableCounts) {
208
+ const { rows: tables } = await this.call<{ rows: { name: string }[] }>('exec', {
209
+ sql: "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name",
210
+ });
211
+ const names = (tables ?? []).map((r) => r.name).filter((n) => n !== SNAPSHOT_TABLE);
212
+ if (names.length) {
213
+ // Names come from sqlite_master itself; double-quoting is enough.
214
+ const sql = names
215
+ .map((n) => `SELECT '${n.replace(/'/g, "''")}' AS t, COUNT(*) AS n FROM "${n.replace(/"/g, '""')}"`)
216
+ .join(' UNION ALL ');
217
+ const { rows: counts } = await this.call<{ rows: { t: string; n: number }[] }>('exec', {
218
+ sql,
219
+ });
220
+ diag.tableCounts = (counts ?? []).map((r) => ({ table: r.t, rows: r.n }));
221
+ } else {
222
+ diag.tableCounts = [];
223
+ }
224
+ }
225
+ } catch (e) {
226
+ diag.error = e instanceof Error ? e.message : String(e);
227
+ }
228
+ return diag;
229
+ }
230
+
231
+ getEvents(): DatabaseEventSystem {
232
+ return this.events;
233
+ }
234
+
235
+ getClient(): unknown {
236
+ throw new Error('SqliteCacheEngine has no SurrealDB client (getClient is unavailable).');
237
+ }
238
+
239
+ /** LocalStore alias; SQLite has no in-flight gate, so this maps to a rebuild. */
240
+ switchStore(bucketId: string): Promise<void> {
241
+ return this.switchBucket(bucketId);
242
+ }
243
+
244
+ /** SQLite has no switch gate window; the epoch bump alone fences stale writes. */
245
+ beginSwitch(): () => void {
246
+ return () => {};
247
+ }
248
+
249
+ // ---- worker plumbing -----------------------------------------------------
250
+
251
+ /** Serializes every worker op so reads/writes never overlap at the VFS layer
252
+ * (overlapping ops trip SQLITE_BUSY). Mirrors the SurrealDB engine's
253
+ * single-flight query queue. (The worker keeps its own chain too, for
254
+ * multi-client mode; this one additionally provides the queue-wait stat and
255
+ * the boot/switch atomicity below.) */
256
+ private opQueue: Promise<unknown> = Promise.resolve();
257
+
258
+ private call<T = any>(type: string, payload?: unknown): Promise<T> {
259
+ const enqueuedAt = performance.now();
260
+ const run = async () => {
261
+ // Leaderless window (shared mode): park behind the role gate instead of
262
+ // failing; a new leader releases it, the timeout rejects it.
263
+ if (this.roleGate) await this.roleGate.promise;
264
+ // Time spent waiting behind other ops in the queue, not doing work.
265
+ getStats().queueWaitMs += performance.now() - enqueuedAt;
266
+ return this.rawCall<T>(type, payload);
267
+ };
268
+ const result = this.opQueue.then(run, run);
269
+ // Keep the chain alive regardless of individual failures.
270
+ this.opQueue = result.then(
271
+ () => undefined,
272
+ () => undefined
273
+ );
274
+ return result;
275
+ }
276
+
277
+ /**
278
+ * Ops dispatched to the worker and not yet answered. Role transitions run on
279
+ * their own chain (see {@link transitionChain}), so they can start while the
280
+ * opQueue still has an op at the worker; tearing the transport down under it
281
+ * would reject that op — and its caller may be a query whose only fetch this
282
+ * was. {@link drainInFlight} lets a deliberate teardown wait them out.
283
+ */
284
+ private inFlightCalls = new Set<Promise<unknown>>();
285
+
286
+ /** Wait for dispatched ops to answer before a deliberate transport teardown.
287
+ * Bounded: a wedged worker must not block the role change forever. */
288
+ private async drainInFlight(timeoutMs = 2_000): Promise<void> {
289
+ if (this.inFlightCalls.size === 0) return;
290
+ const settled = Promise.all([...this.inFlightCalls].map((p) => p.catch(() => undefined)));
291
+ let timer: ReturnType<typeof setTimeout> | undefined;
292
+ try {
293
+ await Promise.race([
294
+ settled,
295
+ new Promise<void>((resolve) => {
296
+ timer = setTimeout(resolve, timeoutMs);
297
+ }),
298
+ ]);
299
+ } finally {
300
+ if (timer) clearTimeout(timer);
301
+ }
302
+ }
303
+
304
+ private rawCall<T = any>(type: string, payload?: unknown): Promise<T> {
305
+ if (!this.transport) throw new Error('SqliteCacheEngine: not connected');
306
+ // --- instrumentation: live, inspectable via `globalThis.__sqliteStats` ---
307
+ const s = getStats();
308
+ s.roundTrips++;
309
+ s.byType[type] = (s.byType[type] ?? 0) + 1;
310
+ if (type === 'batch' && Array.isArray(payload)) {
311
+ s.batchStatements += payload.length;
312
+ s.maxBatch = Math.max(s.maxBatch, payload.length);
313
+ }
314
+ s.inFlight++;
315
+ s.maxInFlight = Math.max(s.maxInFlight, s.inFlight);
316
+ if (this.transport.kind === 'port') s.proxiedOps = (s.proxiedOps ?? 0) + 1;
317
+ const sentAt = performance.now();
318
+ // Track the dispatch, not the returned promise: attaching a handler to
319
+ // `result` would mark it handled and swallow the unhandled-rejection
320
+ // reports that surface a caller which forgot to catch.
321
+ let settle!: () => void;
322
+ const tracked = new Promise<void>((res) => {
323
+ settle = res;
324
+ });
325
+ this.inFlightCalls.add(tracked);
326
+ const finish = () => {
327
+ this.inFlightCalls.delete(tracked);
328
+ settle();
329
+ };
330
+ // Deadline per op. The transport parks a call until the worker replies,
331
+ // and a worker starved behind a long op (or wedged on an unbounded lock
332
+ // check) answered never; every caller up the stack then waited forever.
333
+ // Reject the CALLER only: the op is still queued in the worker and its
334
+ // late reply is dropped by the transport (no pending entry left to
335
+ // resolve). Deliberately no teardown here - a slow worker is not a dead
336
+ // one, and killing it mid-write would cost more than the wait.
337
+ const timeoutMs = this.localOpTimeoutMs;
338
+ const result = withTimeout(
339
+ this.transport.call<T>(type, payload),
340
+ timeoutMs,
341
+ () => new LocalOpTimeoutError(type, timeoutMs)
342
+ ).then(
343
+ (v: T) => {
344
+ finish();
345
+ s.inFlight--;
346
+ // Split the round-trip: `wt` is time inside the worker's handler,
347
+ // the remainder is postMessage + scheduling overhead.
348
+ const wt = (v as { wt?: unknown } | null)?.wt;
349
+ if (typeof wt === 'number') {
350
+ s.workerMs += wt;
351
+ s.rpcOverheadMs += Math.max(0, performance.now() - sentAt - wt);
352
+ }
353
+ return v;
354
+ },
355
+ (e: unknown) => {
356
+ finish();
357
+ s.inFlight--;
358
+ if (e instanceof LocalOpTimeoutError) {
359
+ s.timeouts = (s.timeouts ?? 0) + 1;
360
+ this.logger.error(
361
+ { type, timeoutMs, Category: 'sp00ky-client::SqliteCacheEngine::rawCall' },
362
+ 'Local store op did not answer within its deadline; rejecting the caller'
363
+ );
364
+ }
365
+ throw e;
366
+ }
367
+ );
368
+ return result;
369
+ }
370
+
371
+ /**
372
+ * Spawn the worker and open `bucketId`'s DB. Uses {@link rawCall} (NOT
373
+ * {@link call}) so it can run as the body of an already-queued opQueue entry
374
+ * without re-queuing onto itself. Callers must run it through the opQueue.
375
+ */
376
+ /** Seam for tests: swap in a fake transport instead of a real Worker. */
377
+ protected createTransport(): SqliteTransport {
378
+ return new WorkerSqliteTransport(this.logger);
379
+ }
380
+
381
+ private async openInternal(
382
+ bucketId: string,
383
+ extras?: {
384
+ workerLockName?: string;
385
+ openOptions?: { maxAttempts?: number; backoffMs?: number[]; disallowMemoryFallback?: boolean };
386
+ }
387
+ ): Promise<void> {
388
+ if (!this.transport || this.transport.kind !== 'worker' || !this.transport.connected) {
389
+ this.transport = this.createTransport();
390
+ if (this.transport instanceof WorkerSqliteTransport) {
391
+ // The worker fencing itself (leadership stolen from a frozen tab that
392
+ // thawed) is a leader-loss: park ops until the broker re-adopts us.
393
+ this.transport.onLockLost = (reason) => {
394
+ this.transport = null;
395
+ this.storeEpoch++;
396
+ this.openRoleGate(`worker fenced: ${reason}`);
397
+ };
398
+ }
399
+ }
400
+ // Seed the `_00_*` system tables as part of `open` (worker-side, one round
401
+ // trip). The LocalMigrator DEFINEs them, but `translateSurql` lowers every
402
+ // DEFINE to a noop on this engine (SQLite has no DDL vocabulary), so
403
+ // provisioning never actually creates them — they were only made lazily on
404
+ // first WRITE. A fresh bucket (e.g. right after signup) that READS one first
405
+ // (the sync layer selects `_00_query` before any row lands) hit
406
+ // "no such table: _00_query" and the client wedged on "Loading database".
407
+ // Creating them inside `open` guarantees any access order is safe without
408
+ // adding ops to the engine's queue.
409
+ // `opfsError` is absent from a worker bundle older than this field, which
410
+ // just reads as "no reason given" rather than breaking the open.
411
+ const { persisted, opfsError } = await this.rawCall<{
412
+ persisted: boolean;
413
+ opfsError?: string;
414
+ }>('open', {
415
+ dbName: bucketId,
416
+ useOpfs: this.useOpfs,
417
+ systemTables: SYSTEM_TABLES,
418
+ ...(extras?.workerLockName ? { workerLockName: extras.workerLockName } : {}),
419
+ ...(extras?.openOptions ? { openOptions: extras.openOptions } : {}),
420
+ });
421
+ this.knownTables.clear();
422
+ for (const t of SYSTEM_TABLES) this.knownTables.add(t);
423
+ this.bucketId = bucketId;
424
+ // Durability was requested but could not be had: the store is in RAM, so it
425
+ // loses local writes on reload and can OOM a wasm-heavy renderer. Report it
426
+ // (the worker also console.errors, since host apps may run pino at `fatal`)
427
+ // and publish it so the app can warn the user.
428
+ const fellBack = this.useOpfs && !persisted;
429
+ // Omit `error` rather than setting it to `undefined`: the devtools
430
+ // serializer renders an undefined value as the STRING 'undefined'.
431
+ const health: StorageHealth = {
432
+ status: persisted ? 'persistent' : 'memory',
433
+ fallback: fellBack,
434
+ };
435
+ if (fellBack && opfsError) health.error = opfsError;
436
+ if (this.shared) health.role = this.roleLabel;
437
+ this.setStorageHealth(health);
438
+ const stats = getStats();
439
+ stats.persisted = persisted;
440
+ if (fellBack && opfsError) stats.opfsError = opfsError;
441
+ else delete stats.opfsError;
442
+ if (fellBack) {
443
+ this.logger.error(
444
+ { bucketId, opfsError, Category: 'sp00ky-client::SqliteCacheEngine::connect' },
445
+ 'SQLite OPFS persistence failed; store is IN MEMORY and will not survive reload'
446
+ );
447
+ } else {
448
+ this.logger.info(
449
+ { bucketId, persisted, Category: 'sp00ky-client::SqliteCacheEngine::connect' },
450
+ persisted ? 'SQLite OPFS store opened' : 'SQLite in-memory store opened (as configured)'
451
+ );
452
+ }
453
+ }
454
+
455
+ /** Enqueue `fn` as a single serialized opQueue entry (mirrors {@link call}'s
456
+ * chaining) so it can't interleave with reads/writes at the worker. */
457
+ private enqueue<T>(fn: () => Promise<T>): Promise<T> {
458
+ const result = this.opQueue.then(fn, fn);
459
+ this.opQueue = result.then(
460
+ () => undefined,
461
+ () => undefined
462
+ );
463
+ return result;
464
+ }
465
+
466
+ async connect(bucketId: string): Promise<void> {
467
+ // Serialize through the opQueue so an op racing boot can't dispatch to a
468
+ // half-open worker.
469
+ await this.enqueue(() => this.openInternal(bucketId));
470
+ }
471
+
472
+ async switchBucket(bucketId: string): Promise<void> {
473
+ this.storeEpoch++;
474
+ // Run close → terminate → reopen as ONE opQueue entry. Previously `close`
475
+ // and the new `open` were separate entries, so a query's `exec` (e.g. the
476
+ // query re-registration fired by an auth/bucket change) could slot in
477
+ // between and dispatch to the just-closed worker → "sqlite: DB not open".
478
+ // As a single entry, every other op runs fully before the close or after
479
+ // the reopen — never against a closed DB.
480
+ await this.enqueue(async () => {
481
+ if (this.transport) {
482
+ try {
483
+ await this.rawCall('close');
484
+ } catch {
485
+ /* ignore */
486
+ }
487
+ this.transport.close('bucket switch');
488
+ this.transport = null;
489
+ }
490
+ await this.openInternal(bucketId);
491
+ });
492
+ }
493
+
494
+ async close(): Promise<void> {
495
+ if (!this.transport) return;
496
+ try {
497
+ await this.call('close');
498
+ } catch {
499
+ /* ignore */
500
+ }
501
+ this.transport.close('engine closed');
502
+ this.transport = null;
503
+ }
504
+
505
+ // ---- shared-tabs role modes ------------------------------------------------
506
+ // The TabsCoordinator drives these; solo mode never touches them. The engine
507
+ // object is never replaced across role changes, so `storeEpoch` stays one
508
+ // monotonic per-tab counter and every existing fencing consumer keeps
509
+ // working unchanged.
510
+
511
+ /** Which role the current transport represents, for StorageHealth. */
512
+ private roleLabel: 'leader' | 'follower' | 'solo' = 'solo';
513
+ /** True once this engine has had a usable store at least once; role changes
514
+ * after that point invalidate in-flight reads and must bump the epoch. */
515
+ private hadStore = false;
516
+
517
+ /**
518
+ * Role transitions run on their OWN chain, never on the opQueue: parked ops
519
+ * sit INSIDE opQueue entries waiting for the role gate, so a transition
520
+ * queued behind them could never run to release them (deadlock). Transitions
521
+ * are safe off-queue because in-flight ops on a dead transport were already
522
+ * rejected, parked ops only resume after the transition completes, and the
523
+ * worker serializes everything worker-side anyway.
524
+ */
525
+ private transitionChain: Promise<unknown> = Promise.resolve();
526
+
527
+ private chainTransition<T>(fn: () => Promise<T>): Promise<T> {
528
+ const result = this.transitionChain.then(fn, fn);
529
+ this.transitionChain = result.then(
530
+ () => undefined,
531
+ () => undefined
532
+ );
533
+ return result;
534
+ }
535
+
536
+ private openRoleGate(reason: string): void {
537
+ if (this.roleGate) return;
538
+ let release!: () => void;
539
+ let rejectFn!: (e: Error) => void;
540
+ const promise = new Promise<void>((res, rej) => {
541
+ release = res;
542
+ rejectFn = rej;
543
+ });
544
+ // Swallow the timeout rejection for waiters that already resolved.
545
+ promise.catch(() => {});
546
+ this.roleGate = { promise, release };
547
+ this.roleGateTimer = setTimeout(() => {
548
+ // Nothing adopted us in time: reject the parked ops (retryable) and drop
549
+ // the gate so later calls fail fast with 'not connected'.
550
+ rejectFn(new BrokerPortClosedError(`no leader adopted this tab: ${reason}`));
551
+ this.roleGate = null;
552
+ this.roleGateTimer = null;
553
+ }, 20_000);
554
+ }
555
+
556
+ private closeRoleGate(): void {
557
+ if (this.roleGateTimer) clearTimeout(this.roleGateTimer);
558
+ this.roleGateTimer = null;
559
+ this.roleGate?.release();
560
+ this.roleGate = null;
561
+ }
562
+
563
+ /**
564
+ * Become the store owner (leader). Boot and failover share this path; a
565
+ * failover (a previous transport existed) bumps the epoch FIRST so every
566
+ * in-flight chain that captured the old epoch fences itself. `resumeHeld`
567
+ * keeps the live worker after a broker restart and only rolls the
568
+ * per-leadership lock forward.
569
+ */
570
+ async adoptOwner(
571
+ bucketId: string,
572
+ opts: {
573
+ workerLockName: string;
574
+ allowMemoryFallback: boolean;
575
+ resumeHeld: boolean;
576
+ }
577
+ ): Promise<StorageHealth> {
578
+ this.roleLabel = 'leader';
579
+ return this.chainTransition(async () => {
580
+ if (
581
+ opts.resumeHeld &&
582
+ this.transport?.kind === 'worker' &&
583
+ this.transport.connected &&
584
+ this.bucketId === bucketId
585
+ ) {
586
+ await this.rawCall('relock', { workerLockName: opts.workerLockName });
587
+ this.closeRoleGate();
588
+ return this.storageHealthValue;
589
+ }
590
+ if (this.transport) await this.drainInFlight();
591
+ if (this.hadStore) this.storeEpoch++;
592
+ if (this.transport) {
593
+ try {
594
+ if (this.transport.kind === 'worker') await this.rawCall('close');
595
+ } catch {
596
+ /* ignore */
597
+ }
598
+ this.transport.close('adopting ownership', new BrokerPortClosedError('adopting ownership'));
599
+ this.transport = null;
600
+ }
601
+ await this.openInternal(bucketId, {
602
+ workerLockName: opts.workerLockName,
603
+ openOptions: {
604
+ ...PROMOTION_OPEN_OPTIONS,
605
+ disallowMemoryFallback: !opts.allowMemoryFallback,
606
+ },
607
+ });
608
+ // Leader wipe-on-pool-open: local `_00_query` rows from earlier sessions
609
+ // are dead (query hashes are session-salted) and this is the one moment
610
+ // no other tab is attached, so clearing here replaces the per-switch
611
+ // DELETE that solo mode does in doSwitchBucket. Followers never wipe.
612
+ try {
613
+ await this.rawCall('run', { sql: 'DELETE FROM "_00_query"' });
614
+ } catch {
615
+ /* fresh bucket: table just seeded, nothing to wipe */
616
+ }
617
+ getStats().roleChanges = (getStats().roleChanges ?? 0) + 1;
618
+ this.hadStore = true;
619
+ this.closeRoleGate();
620
+ return this.storageHealthValue;
621
+ });
622
+ }
623
+
624
+ /** Attach to a leader's worker through `dbPort` (follower). */
625
+ async adoptAttached(
626
+ dbPort: MessagePort,
627
+ snapshot: { bucketId: string; storageHealth: StorageHealth },
628
+ onPortDead: (reason: string) => void
629
+ ): Promise<void> {
630
+ this.roleLabel = 'follower';
631
+ return this.chainTransition(async () => {
632
+ if (this.transport) await this.drainInFlight();
633
+ if (this.hadStore) this.storeEpoch++;
634
+ this.transport?.close(
635
+ 'adopting leader port',
636
+ new BrokerPortClosedError('adopting leader port')
637
+ );
638
+ this.transport = new PortSqliteTransport(dbPort, onPortDead, this.logger);
639
+ this.bucketId = snapshot.bucketId;
640
+ // The shared store exists and is seeded; mirror the owner's bookkeeping.
641
+ this.knownTables.clear();
642
+ for (const t of SYSTEM_TABLES) this.knownTables.add(t);
643
+ const health: StorageHealth = { ...snapshot.storageHealth, role: 'follower' };
644
+ this.setStorageHealth(health);
645
+ const stats = getStats();
646
+ stats.persisted = snapshot.storageHealth.status === 'persistent';
647
+ stats.roleChanges = (stats.roleChanges ?? 0) + 1;
648
+ delete stats.opfsError;
649
+ this.hadStore = true;
650
+ this.closeRoleGate();
651
+ });
652
+ }
653
+
654
+ /** Demoted while owning the store (zombie thaw, stale promotion): tear the
655
+ * worker down so its OPFS handles free up, then park until re-adopted. */
656
+ async releaseOwnership(): Promise<void> {
657
+ await this.chainTransition(async () => {
658
+ if (this.transport) {
659
+ // Let ops already at the worker answer first. Without this they die
660
+ // with the transport — a bucket switch (moveToBucket → teardownLeader)
661
+ // runs while the opQueue may still have a query's fetch in flight, and
662
+ // that fetch's caller is not necessarily prepared to retry.
663
+ await this.drainInFlight();
664
+ try {
665
+ if (this.transport.kind === 'worker') {
666
+ await (this.transport as WorkerSqliteTransport).shutdown();
667
+ }
668
+ } catch {
669
+ /* worker may already be fenced/dead */
670
+ }
671
+ // Anything still pending (drain timed out) is a deliberate teardown,
672
+ // not a crash: fail it the way a follower's lost port does, so the
673
+ // error text is honest and callers can treat it as retryable.
674
+ this.transport.close(
675
+ 'ownership released',
676
+ new BrokerPortClosedError('ownership released')
677
+ );
678
+ this.transport = null;
679
+ }
680
+ this.storeEpoch++;
681
+ this.openRoleGate('ownership released');
682
+ });
683
+ }
684
+
685
+ /** The leader (or its port) died. Called from the port-dead callback and the
686
+ * coordinator; NOT enqueued, so in-flight ops reject immediately instead of
687
+ * waiting behind whatever is stuck. */
688
+ onLeaderLost(reason: string): void {
689
+ if (this.transport?.kind === 'port') {
690
+ this.transport.close(reason);
691
+ this.transport = null;
692
+ }
693
+ this.storeEpoch++;
694
+ this.openRoleGate(reason);
695
+ }
696
+
697
+ /** Leader side: forward a follower's dbPort into the owned worker. */
698
+ async exposeClientPort(clientId: string, port: MessagePort): Promise<void> {
699
+ if (this.transport?.kind !== 'worker') {
700
+ throw new Error('SqliteCacheEngine: not the store owner');
701
+ }
702
+ await (this.transport as WorkerSqliteTransport).addClientPort(clientId, port);
703
+ }
704
+
705
+ async removeClientPort(clientId: string): Promise<void> {
706
+ if (this.transport?.kind !== 'worker') return;
707
+ await (this.transport as WorkerSqliteTransport).removeClientPort(clientId);
708
+ }
709
+
710
+ /** Graceful pagehide as owner: release OPFS handles NOW so the next leader
711
+ * does not race the browser's worker GC. */
712
+ async shutdownOwnedWorker(): Promise<void> {
713
+ if (this.transport?.kind !== 'worker') return;
714
+ try {
715
+ await (this.transport as WorkerSqliteTransport).shutdown();
716
+ } catch {
717
+ /* ignore */
718
+ }
719
+ this.transport.close('shutdown');
720
+ this.transport = null;
721
+ }
722
+
723
+ private async ensureTable(table: string): Promise<void> {
724
+ if (this.knownTables.has(table)) return;
725
+ await this.call('run', {
726
+ sql: `CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
727
+ });
728
+ this.knownTables.add(table);
729
+ }
730
+
731
+ private async execRows(sql: string, bind: unknown[]): Promise<Row[]> {
732
+ const { rows } = await this.call<{ rows: { data: string }[] }>('exec', { sql, bind });
733
+ const s = getStats();
734
+ const t0 = performance.now();
735
+ const out = (rows ?? []).map((r) => {
736
+ s.bytesParsed += r.data.length;
737
+ return reviveRow(r.data);
738
+ });
739
+ s.parseMs += performance.now() - t0;
740
+ s.rowsParsed += out.length;
741
+ return out;
742
+ }
743
+
744
+ // ---- reads ---------------------------------------------------------------
745
+
746
+ async select(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<Row[]> {
747
+ if (this.workerSelect) {
748
+ // ONE round-trip: the worker executes the whole plan (table creation,
749
+ // base select, relation tree, JSON parse) and returns structured-clone
750
+ // rows. The legacy path below pays a postMessage hop per table/relation
751
+ // level plus main-thread parsing — the dominant first-load cost.
752
+ //
753
+ // Normalize before postMessage: class-instance VALUES (RecordId & co) →
754
+ // their `stableKey` string. structuredClone strips a class instance to a
755
+ // bare plain object — and surrealdb's RecordId keeps its data behind
756
+ // getters (no own properties), so it clones to `{}`: the worker would
757
+ // filter on garbage. Applies to params AND to values baked inside the
758
+ // plan (where nodes, relation sub-wheres, window ids).
759
+ // Param KEYS must pass through untouched — `comparisonSql` resolves
760
+ // `paramRef` via hasOwnProperty, and a dropped key silently falls back to
761
+ // the baked literal (the crossed-results class fixed in aa4af79b).
762
+ const normPlan = normalizePlanForClone(plan);
763
+ const normParams: Record<string, unknown> = {};
764
+ for (const [k, v] of Object.entries(params)) normParams[k] = toCloneSafe(v);
765
+ try {
766
+ const res = await this.call<{ rows: Row[]; relationFetches?: number }>('select', {
767
+ plan: normPlan,
768
+ params: normParams,
769
+ });
770
+ getStats().relationFetches += res.relationFetches ?? 0;
771
+ return res.rows ?? [];
772
+ } catch (err) {
773
+ // Stale worker script without the 'select' op: fall back for good.
774
+ if (err instanceof Error && err.message.includes('unknown message')) {
775
+ this.workerSelect = false;
776
+ this.logger.warn(
777
+ { err, Category: 'sp00ky-client::SqliteCacheEngine::select' },
778
+ 'Worker lacks select op (stale script?) — falling back to multi-hop select'
779
+ );
780
+ } else {
781
+ throw err;
782
+ }
783
+ }
784
+ }
785
+ return this.selectLegacy(plan, params);
786
+ }
787
+
788
+ /** Pre-worker-select path: one worker round-trip per table/relation level,
789
+ * rows parsed on the main thread. Kept as the `workerSelect:false` escape
790
+ * hatch and the stale-worker fallback. */
791
+ private async selectLegacy(
792
+ plan: QueryPlan,
793
+ params: Record<string, unknown> = {}
794
+ ): Promise<Row[]> {
795
+ // Window materialization: base rows are exactly `plan.ids`, ordered.
796
+ if (plan.ids) {
797
+ const result = await this.selectByIds(plan.table, plan.ids, {
798
+ select: plan.select,
799
+ orderBy: plan.orderBy,
800
+ });
801
+ await resolveRelations(result, plan.relations, this);
802
+ return result;
803
+ }
804
+ await this.ensureTable(plan.table);
805
+ const bind: unknown[] = [];
806
+ // Projection binds land in the SELECT clause, ahead of any WHERE binds.
807
+ const proj = plan.select ? projectedDataSql(plan.select, bind) : 'data';
808
+ let sql = `SELECT ${proj} FROM "${plan.table}"`;
809
+ if (plan.where && plan.where.length > 0) {
810
+ sql += ` WHERE ${renderWhereSql(plan.where, bind, params)}`;
811
+ }
812
+ if (plan.orderBy && plan.orderBy.length > 0) sql += renderOrderSql(plan.orderBy);
813
+ // Deterministic fallback, in parity with `sqlite-select.ts`: without it an
814
+ // unordered query renders in insertion order here and in membership order
815
+ // after the server answers, which reshuffles the list on screen.
816
+ else sql += ` ORDER BY id`;
817
+ if (plan.limit !== undefined) sql += ` LIMIT ${Number(plan.limit)}`;
818
+ if (plan.offset !== undefined) sql += ` OFFSET ${Number(plan.offset)}`;
819
+ const rows = await this.execRows(sql, bind);
820
+ await resolveRelations(rows, plan.relations, this);
821
+ return rows;
822
+ }
823
+
824
+ async fetchRelation(req: RelationFetch): Promise<Row[]> {
825
+ getStats().relationFetches++;
826
+ await this.ensureTable(req.table);
827
+ const keys = req.keys.map(stableKey);
828
+ const placeholders = keys.map(() => '?').join(', ');
829
+ const bind: unknown[] = [...keys];
830
+ const lhs = req.matchField === 'id' ? 'id' : `json_extract(data, '$.${req.matchField}')`;
831
+ let sql = `SELECT data FROM "${req.table}" WHERE ${lhs} IN (${placeholders})`;
832
+ if (req.where && req.where.length > 0) {
833
+ sql += ` AND ${renderWhereSql(req.where, bind, {})}`;
834
+ }
835
+ if (req.orderBy && req.orderBy.length > 0) sql += renderOrderSql(req.orderBy);
836
+ const rows = await this.execRows(sql, bind);
837
+ return req.select ? rows.map((r) => project(r, req.select!)) : rows;
838
+ }
839
+
840
+ async selectByIds(
841
+ table: string,
842
+ ids: Id[],
843
+ opts?: { select?: string[]; orderBy?: OrderBy }
844
+ ): Promise<Row[]> {
845
+ if (ids.length === 0) return [];
846
+ await this.ensureTable(table);
847
+ const keys = ids.map(stableKey);
848
+ const placeholders = keys.map(() => '?').join(', ');
849
+ // Projection binds land in the SELECT clause, so they go first. Must stay
850
+ // byte-identical to the worker path in sqlite-select.ts.
851
+ const bind: unknown[] = [];
852
+ const dataCol = opts?.select ? projectedDataSql(opts.select, bind) : 'data';
853
+ bind.push(...keys);
854
+ let sql = `SELECT ${dataCol} FROM "${table}" WHERE id IN (${placeholders})`;
855
+ if (opts?.orderBy && opts.orderBy.length > 0) sql += renderOrderSql(opts.orderBy);
856
+ let rows = await this.execRows(sql, bind);
857
+ if (!opts?.orderBy || opts.orderBy.length === 0) {
858
+ const pos = new Map(keys.map((k, i) => [k, i]));
859
+ rows = rows.sort((a, b) => (pos.get(stableKey(a.id)) ?? 0) - (pos.get(stableKey(b.id)) ?? 0));
860
+ }
861
+ return rows;
862
+ }
863
+
864
+ async getById(table: string, id: Id): Promise<Row | null> {
865
+ await this.ensureTable(table);
866
+ const rows = await this.execRows(`SELECT data FROM "${table}" WHERE id = ?`, [stableKey(id)]);
867
+ return rows[0] ?? null;
868
+ }
869
+
870
+ /**
871
+ * `(id, _00_rv)` of every row per table, straight off the worker: no body
872
+ * parse, one round trip per table. A table that does not exist yet reads as
873
+ * empty rather than failing the whole scan.
874
+ */
875
+ async scanVersions(tables: string[]): Promise<Record<string, [string, number][]>> {
876
+ const out: Record<string, [string, number][]> = {};
877
+ for (const table of tables) {
878
+ try {
879
+ const { rows } = await this.call<{ rows: { id: string; rv: unknown }[] }>('exec', {
880
+ sql: `SELECT id, json_extract(data, '$._00_rv') AS rv FROM "${table.replace(/"/g, '""')}"`,
881
+ });
882
+ out[table] = (rows ?? []).map((r) => [r.id, Number(r.rv) || 0]);
883
+ } catch {
884
+ out[table] = [];
885
+ }
886
+ }
887
+ return out;
888
+ }
889
+
890
+ async getSnapshot(key: string): Promise<StoredSnapshot | null> {
891
+ const { rows } = await this.call<{ rows: { id: string; data: unknown }[] }>('exec', {
892
+ sql: `SELECT id, data FROM "${SNAPSHOT_TABLE}" WHERE id IN (?, ?)`,
893
+ bind: [key, `${key}:meta`],
894
+ });
895
+ let bytes: Uint8Array | null = null;
896
+ let meta: SnapshotMeta | null = null;
897
+ for (const r of rows ?? []) {
898
+ if (r.id === key) {
899
+ if (r.data instanceof Uint8Array) bytes = r.data;
900
+ else if (r.data instanceof ArrayBuffer) bytes = new Uint8Array(r.data);
901
+ else if (typeof r.data === 'string') bytes = new TextEncoder().encode(r.data);
902
+ } else if (typeof r.data === 'string') {
903
+ try {
904
+ meta = JSON.parse(r.data) as SnapshotMeta;
905
+ } catch {
906
+ meta = null;
907
+ }
908
+ }
909
+ }
910
+ return bytes && meta ? { bytes, meta } : null;
911
+ }
912
+
913
+ async putSnapshot(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void> {
914
+ // One transaction, so a reader never sees new bytes with old meta.
915
+ await this.call('batch', [
916
+ {
917
+ sql: `INSERT OR REPLACE INTO "${SNAPSHOT_TABLE}" (id, data) VALUES (?, ?)`,
918
+ bind: [key, bytes],
919
+ },
920
+ {
921
+ sql: `INSERT OR REPLACE INTO "${SNAPSHOT_TABLE}" (id, data) VALUES (?, ?)`,
922
+ bind: [`${key}:meta`, JSON.stringify(meta)],
923
+ },
924
+ ]);
925
+ }
926
+
927
+ async deleteSnapshot(key: string): Promise<void> {
928
+ await this.call('run', {
929
+ sql: `DELETE FROM "${SNAPSHOT_TABLE}" WHERE id IN (?, ?)`,
930
+ bind: [key, `${key}:meta`],
931
+ });
932
+ }
933
+
934
+ // ---- writes --------------------------------------------------------------
935
+
936
+ async upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void> {
937
+ await this.ensureTable(table);
938
+ const key = stableKey(id);
939
+ if (mode === 'merge') {
940
+ // Merge in-SQL via json_patch (RFC7396 = MERGE semantics): on insert store
941
+ // the row, on conflict shallow-merge. Serialize once, reuse for VALUES and
942
+ // the patch. No read-modify-write round-trip. (RFC7396: null deletes key.)
943
+ const full = serializeRow({ ...data, id: key });
944
+ await this.call('run', {
945
+ sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
946
+ bind: [key, full, full],
947
+ });
948
+ return;
949
+ }
950
+ await this.call('run', {
951
+ sql: `INSERT INTO "${table}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`,
952
+ bind: [key, serializeRow({ ...data, id: key })],
953
+ });
954
+ }
955
+
956
+ async patch(table: string, id: Id, patches: unknown[]): Promise<void> {
957
+ // RFC6902 (fast-json-patch) applied read-modify-write — SQLite's json_patch
958
+ // is RFC7396 merge-patch and would misinterpret op arrays.
959
+ const existing = (await this.getById(table, id)) ?? { id: stableKey(id) };
960
+ const next = applyPatch(existing, patches as Operation[]).newDocument as Row;
961
+ await this.upsert(table, id, next, 'replace');
962
+ }
963
+
964
+ async delete(table: string, id: Id): Promise<void> {
965
+ await this.ensureTable(table);
966
+ await this.call('run', { sql: `DELETE FROM "${table}" WHERE id = ?`, bind: [stableKey(id)] });
967
+ }
968
+
969
+ // ---- SurrealQL-vocabulary shim (LocalStore compatibility) ---------------
970
+
971
+ /**
972
+ * Execute a raw SurrealQL statement by translating the client's bounded
973
+ * vocabulary to verbs (see `surql-translate.ts`). Returns results shaped like
974
+ * SurrealDB's `.query()` (one element per statement; a tx prepends a `null`
975
+ * begin-result so `surql.seal` extraction lines up). Epoch-fences writes.
976
+ */
977
+ async query<T extends unknown[]>(
978
+ sql: string,
979
+ vars: Record<string, unknown> = {},
980
+ opts?: { epoch?: number }
981
+ ): Promise<T> {
982
+ if (opts?.epoch !== undefined && opts.epoch !== this.storeEpoch) throw new StaleEpochError();
983
+ const start = performance.now();
984
+ try {
985
+ const { transaction, ops } = translateSurql(sql, vars);
986
+ let shaped: unknown[];
987
+ // FAST PATH: a pure-write transaction (bulk sync-down is one
988
+ // `tx([upsertMerge…])`) compiles to a SINGLE worker `batch` message run in
989
+ // one SQLite transaction — instead of 1-2 worker round-trips PER row. This
990
+ // is the dominant sync-down cost; per-op execution here caused the churn
991
+ // OOM. Mixed txs (LET/RETURN single-record mutations) keep the per-op path.
992
+ if (
993
+ transaction &&
994
+ ops.every(
995
+ (o) =>
996
+ o.kind === 'upsert' ||
997
+ o.kind === 'delete' ||
998
+ o.kind === 'deleteAll' ||
999
+ o.kind === 'noop'
1000
+ )
1001
+ ) {
1002
+ await this.runWriteBatch(ops);
1003
+ // Shape each statement's result the SAME as the per-op path (`execOp`),
1004
+ // so a caller reading a statement's output still works after taking the
1005
+ // batch fast path. A single `create()` compiles to an all-upsert tx
1006
+ // (createSet + createMutation) and reads `resultIndex:0` for the new
1007
+ // row + its id; returning empty arrays here dropped that row (id became
1008
+ // undefined → the reconcile crashed in `encodeRecordId`). The
1009
+ // single-batch write is kept — this only rebuilds the return value.
1010
+ shaped = [null, ...ops.map(pureWriteOpResult)];
1011
+ } else {
1012
+ const results: unknown[] = [];
1013
+ // Per-query scope holds `LET $var = (...)` bindings for later statements
1014
+ // (e.g. `RETURN { target: $updated }`).
1015
+ const scope: Record<string, unknown> = {};
1016
+ for (const op of ops) results.push(await this.execOp(op, scope, vars));
1017
+ shaped = transaction ? [null, ...results] : results;
1018
+ }
1019
+ this.events.emit(DatabaseEventTypes.LocalQuery, {
1020
+ query: sql,
1021
+ vars,
1022
+ duration: performance.now() - start,
1023
+ success: true,
1024
+ timestamp: Date.now(),
1025
+ });
1026
+ return shaped as unknown as T;
1027
+ } catch (err) {
1028
+ this.events.emit(DatabaseEventTypes.LocalQuery, {
1029
+ query: sql,
1030
+ vars,
1031
+ duration: performance.now() - start,
1032
+ success: false,
1033
+ error: err instanceof Error ? err.message : String(err),
1034
+ timestamp: Date.now(),
1035
+ });
1036
+ throw err;
1037
+ }
1038
+ }
1039
+
1040
+ async execute<R>(
1041
+ query: SealedQuery<R>,
1042
+ vars?: Record<string, unknown>,
1043
+ opts?: { epoch?: number }
1044
+ ): Promise<R> {
1045
+ const raw = await this.query<unknown[]>(query.sql, vars, opts);
1046
+ return query.extract(raw);
1047
+ }
1048
+
1049
+ queryUngated<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T> {
1050
+ return this.query<T>(sql, vars);
1051
+ }
1052
+
1053
+ private async execOp(
1054
+ op: SqlOp,
1055
+ scope: Record<string, unknown>,
1056
+ vars: Record<string, unknown>
1057
+ ): Promise<unknown> {
1058
+ switch (op.kind) {
1059
+ case 'getById': {
1060
+ const row = await this.getById(tableOf(op.id), op.id);
1061
+ if (op.value) return row ? (row[op.value] ?? null) : null;
1062
+ return row ? (op.select ? project(row, op.select) : row) : null;
1063
+ }
1064
+ case 'selectByIds': {
1065
+ if (op.ids.length === 0) return [];
1066
+ let rows = await this.selectByIds(tableOf(op.ids[0]), op.ids, {
1067
+ select: op.select,
1068
+ orderBy: op.orderBy,
1069
+ });
1070
+ // Windowed in JS, not SQL: the id list is already the whole result set,
1071
+ // and its order is restored after the fetch (see selectByIds).
1072
+ if (op.start !== undefined || op.limit !== undefined) {
1073
+ const from = op.start ?? 0;
1074
+ rows = rows.slice(from, op.limit === undefined ? undefined : from + op.limit);
1075
+ }
1076
+ if (op.value) return rows.map((r) => r[op.value!]);
1077
+ return rows;
1078
+ }
1079
+ case 'selectTable': {
1080
+ const rows = await this.rawSelectTable(op.table, op.where, op.orderBy, {
1081
+ limit: op.limit,
1082
+ start: op.start,
1083
+ });
1084
+ if (op.value) return rows.map((r) => r[op.value!]);
1085
+ return op.select ? rows.map((r) => project(r, op.select!)) : rows;
1086
+ }
1087
+ case 'count': {
1088
+ await this.ensureTable(op.table);
1089
+ const bind: unknown[] = [];
1090
+ let sql = `SELECT COUNT(*) AS n FROM "${op.table}"`;
1091
+ if (op.where && op.where.length > 0) sql += ` WHERE ${renderWhereSql(op.where, bind, {})}`;
1092
+ const { rows } = await this.call<{ rows: { n: number }[] }>('exec', { sql, bind });
1093
+ // `GROUP ALL` collapses to a single `{ count }` row on SurrealDB; match
1094
+ // it exactly so callers can read `rows[0].count` on either engine.
1095
+ return [{ count: rows?.[0]?.n ?? 0 }];
1096
+ }
1097
+ case 'infoForDb': {
1098
+ const { rows } = await this.call<{ rows: { name: string }[] }>('exec', {
1099
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
1100
+ });
1101
+ // SurrealDB answers with the DEFINE statement per table. Nothing here
1102
+ // parses it (the DevTools explorer only reads the keys), so a truthful
1103
+ // schemaless stand-in beats inventing field definitions.
1104
+ const tables: Record<string, string> = {};
1105
+ for (const r of rows ?? []) tables[r.name] = `DEFINE TABLE ${r.name} SCHEMALESS`;
1106
+ return { tables, analyzers: {}, functions: {}, params: {}, users: {} };
1107
+ }
1108
+ case 'upsert':
1109
+ await this.upsert(tableOf(op.id), op.id, op.data, op.mode);
1110
+ // Cheap return — no read-back. The full merged row is only needed by a
1111
+ // LET-wrapped upsert, which reads it back in the 'let' case below. This
1112
+ // avoids an extra worker round-trip + full-row parse on EVERY sync-down
1113
+ // write (the hot path under rapid churn). Shared with the batch fast
1114
+ // path so the two never drift.
1115
+ return pureWriteOpResult(op);
1116
+ case 'updateSet': {
1117
+ const existing = (await this.getById(tableOf(op.id), op.id)) ?? { id: stableKey(op.id) };
1118
+ for (const { path, op: setOp, value } of op.sets) {
1119
+ if (setOp === '+=' || setOp === '-=') {
1120
+ const cur = Number(getPath(existing, path) ?? 0);
1121
+ const delta = Number(value ?? 0);
1122
+ setPath(existing, path, setOp === '+=' ? cur + delta : cur - delta);
1123
+ } else {
1124
+ setPath(existing, path, value);
1125
+ }
1126
+ }
1127
+ await this.upsert(tableOf(op.id), op.id, existing, 'replace');
1128
+ return op.returnNone ? null : existing;
1129
+ }
1130
+ case 'delete':
1131
+ await this.delete(tableOf(op.id), op.id);
1132
+ return pureWriteOpResult(op);
1133
+ case 'deleteAll':
1134
+ await this.ensureTable(op.table);
1135
+ await this.call('run', { sql: `DELETE FROM "${op.table}"` });
1136
+ return pureWriteOpResult(op);
1137
+ case 'let': {
1138
+ let result = await this.execOp(op.inner, scope, vars);
1139
+ // A LET-bound UPSERT must expose the FULL merged row (e.g.
1140
+ // `RETURN { target: $updated }`), so read it back here — only here,
1141
+ // not on every upsert.
1142
+ if (op.inner.kind === 'upsert') {
1143
+ result = (await this.getById(tableOf(op.inner.id), op.inner.id)) ?? result;
1144
+ }
1145
+ scope[op.var] = result;
1146
+ return result;
1147
+ }
1148
+ case 'return': {
1149
+ const obj: Row = {};
1150
+ for (const { key, var: v } of op.entries) {
1151
+ obj[key] = v in scope ? scope[v] : vars[v];
1152
+ }
1153
+ return obj;
1154
+ }
1155
+ case 'noop':
1156
+ return pureWriteOpResult(op);
1157
+ }
1158
+ }
1159
+
1160
+ /**
1161
+ * Compile a pure-write op list to ONE worker `batch` (single SQLite
1162
+ * transaction). Ensures each touched table exists, then one statement per op.
1163
+ * Merges happen in-SQL via json_patch — no read-back round-trips.
1164
+ */
1165
+ private async runWriteBatch(ops: SqlOp[]): Promise<void> {
1166
+ const stmts: { sql: string; bind?: unknown[] }[] = [];
1167
+ const tables = new Set<string>();
1168
+ const ensure = (t: string) => {
1169
+ if (!tables.has(t)) {
1170
+ tables.add(t);
1171
+ this.knownTables.add(t);
1172
+ stmts.push({
1173
+ sql: `CREATE TABLE IF NOT EXISTS "${t}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
1174
+ });
1175
+ }
1176
+ };
1177
+ for (const op of ops) {
1178
+ if (op.kind === 'upsert') {
1179
+ const t = tableOf(op.id);
1180
+ const key = stableKey(op.id);
1181
+ ensure(t);
1182
+ if (op.mode === 'merge') {
1183
+ // Serialize ONCE and reuse for both VALUES (fresh insert) and the
1184
+ // json_patch (merge). Patching with `id` is a harmless no-op set, so
1185
+ // the full row doubles as the delta — halves per-row stringify cost.
1186
+ const full = serializeRow({ ...op.data, id: key });
1187
+ stmts.push({
1188
+ sql: `INSERT INTO "${t}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = json_patch(data, ?)`,
1189
+ bind: [key, full, full],
1190
+ });
1191
+ } else {
1192
+ stmts.push({
1193
+ sql: `INSERT INTO "${t}"(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`,
1194
+ bind: [key, serializeRow({ ...op.data, id: key })],
1195
+ });
1196
+ }
1197
+ } else if (op.kind === 'delete') {
1198
+ const t = tableOf(op.id);
1199
+ ensure(t);
1200
+ stmts.push({ sql: `DELETE FROM "${t}" WHERE id = ?`, bind: [stableKey(op.id)] });
1201
+ } else if (op.kind === 'deleteAll') {
1202
+ ensure(op.table);
1203
+ stmts.push({ sql: `DELETE FROM "${op.table}"` });
1204
+ }
1205
+ }
1206
+ if (stmts.length > 0) await this.call('batch', stmts);
1207
+ }
1208
+
1209
+ private async rawSelectTable(
1210
+ table: string,
1211
+ where?: WhereNode[],
1212
+ orderBy?: OrderBy,
1213
+ window?: { limit?: number; start?: number }
1214
+ ): Promise<Row[]> {
1215
+ await this.ensureTable(table);
1216
+ const bind: unknown[] = [];
1217
+ let sql = `SELECT data FROM "${table}"`;
1218
+ if (where && where.length > 0) sql += ` WHERE ${renderWhereSql(where, bind, {})}`;
1219
+ if (orderBy && orderBy.length > 0) sql += renderOrderSql(orderBy);
1220
+ // SQLite has no bare OFFSET, so a START without a LIMIT needs `LIMIT -1`
1221
+ // (its documented "no limit" sentinel) to stay valid SQL.
1222
+ if (window?.limit !== undefined) sql += ` LIMIT ${Number(window.limit)}`;
1223
+ else if (window?.start !== undefined) sql += ' LIMIT -1';
1224
+ if (window?.start !== undefined) sql += ` OFFSET ${Number(window.start)}`;
1225
+ return this.execRows(sql, bind);
1226
+ }
1227
+
1228
+ async transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T> {
1229
+ // Verbs run in order on the single worker message channel. `patch` needs a
1230
+ // read-modify-write round-trip, so a single BEGIN/COMMIT batch cannot wrap
1231
+ // the whole closure; sequential execution is sufficient for the current
1232
+ // single-record write sites.
1233
+ const tx: EngineTx = {
1234
+ upsert: (t, id, data, mode) => this.upsert(t, id, data, mode),
1235
+ patch: (t, id, p) => this.patch(t, id, p),
1236
+ delete: (t, id) => this.delete(t, id),
1237
+ };
1238
+ return fn(tx);
1239
+ }
1240
+ }
1241
+
1242
+ // ==================== instrumentation ====================
1243
+
1244
+ interface SqliteStats {
1245
+ roundTrips: number;
1246
+ batchStatements: number;
1247
+ maxBatch: number;
1248
+ inFlight: number;
1249
+ maxInFlight: number;
1250
+ byType: Record<string, number>;
1251
+ /** Worker round trips that hit `localOpTimeoutMs` (see rawCall). */
1252
+ timeouts?: number;
1253
+ /** Time ops spent waiting behind the opQueue before dispatch. */
1254
+ queueWaitMs: number;
1255
+ /** Time inside the worker's message handler (actual SQLite work). */
1256
+ workerMs: number;
1257
+ /** Round-trip time minus workerMs: postMessage + scheduling overhead. */
1258
+ rpcOverheadMs: number;
1259
+ /** Main-thread JSON parse/revive of returned rows. */
1260
+ parseMs: number;
1261
+ rowsParsed: number;
1262
+ bytesParsed: number;
1263
+ /** Relation-resolver fan-out fetches (one worker round-trip each). */
1264
+ relationFetches: number;
1265
+ /** Whether the open store is OPFS-backed. `false` here with an `opfsError`
1266
+ * means the whole dataset is sitting in RAM. Optional so it stays absent
1267
+ * until the first open (and is skipped by the backfill loop below). */
1268
+ persisted?: boolean;
1269
+ /** Why OPFS persistence failed, when it did. */
1270
+ opfsError?: string;
1271
+ /** Shared-tabs follower: ops that crossed the leader's MessagePort. */
1272
+ proxiedOps?: number;
1273
+ /** Times this tab's engine changed hands (promotions + attachments). */
1274
+ roleChanges?: number;
1275
+ }
1276
+
1277
+ const EMPTY_STATS: SqliteStats = {
1278
+ roundTrips: 0,
1279
+ batchStatements: 0,
1280
+ maxBatch: 0,
1281
+ inFlight: 0,
1282
+ maxInFlight: 0,
1283
+ byType: {},
1284
+ queueWaitMs: 0,
1285
+ workerMs: 0,
1286
+ rpcOverheadMs: 0,
1287
+ parseMs: 0,
1288
+ rowsParsed: 0,
1289
+ bytesParsed: 0,
1290
+ relationFetches: 0,
1291
+ };
1292
+
1293
+ /** Live stats, inspectable in the browser console via `__sqliteStats`. Counts
1294
+ * worker round-trips (the sync-down cost driver), batch sizes, queue depth
1295
+ * (`maxInFlight`), and the latency split of each round-trip (queue wait vs
1296
+ * worker time vs RPC overhead vs main-thread row parsing) so first-load cost
1297
+ * can be measured rather than guessed. */
1298
+ function getStats(): SqliteStats {
1299
+ const g = globalThis as unknown as { __sqliteStats?: SqliteStats };
1300
+ if (!g.__sqliteStats) {
1301
+ g.__sqliteStats = { ...EMPTY_STATS, byType: {} };
1302
+ } else {
1303
+ // Backfill fields added since the object was created (HMR / older bundle).
1304
+ for (const [k, v] of Object.entries(EMPTY_STATS)) {
1305
+ if ((g.__sqliteStats as any)[k] === undefined) (g.__sqliteStats as any)[k] = v;
1306
+ }
1307
+ }
1308
+ return g.__sqliteStats;
1309
+ }
1310
+
1311
+ // SQL rendering + row (de)serialization live in `sqlite-plan-sql.ts`, shared
1312
+ // with the worker (worker-side plan execution renders the same SQL).
1313
+
1314
+ // ==================== structured-clone normalization ====================
1315
+
1316
+ /**
1317
+ * Make a bind/param value safe to cross the worker boundary. structuredClone
1318
+ * keeps plain data intact but strips a CLASS instance to a bare object — and
1319
+ * surrealdb's `RecordId` stores its fields behind getters (zero own
1320
+ * properties), so it clones to `{}`. Convert such instances to their
1321
+ * `stableKey` string (the exact value `scalar()` would bind on the main
1322
+ * thread), leave everything clone-representable untouched.
1323
+ */
1324
+ function toCloneSafe(v: unknown): unknown {
1325
+ if (v === null || typeof v !== 'object') return v;
1326
+ if (Array.isArray(v) || v instanceof Uint8Array || v instanceof Date) return v;
1327
+ const proto = Object.getPrototypeOf(v);
1328
+ if (proto === Object.prototype || proto === null) return v;
1329
+ return stableKey(v);
1330
+ }
1331
+
1332
+ function normalizeWhereForClone(nodes: WhereNode[] | undefined): WhereNode[] | undefined {
1333
+ if (!nodes) return nodes;
1334
+ return nodes.map((n) =>
1335
+ 'or' in n
1336
+ ? { or: n.or.map((c) => ({ ...c, value: toCloneSafe(c.value) })) }
1337
+ : { ...n, value: toCloneSafe(n.value) }
1338
+ );
1339
+ }
1340
+
1341
+ function normalizeRelationForClone(r: RelationPlan): RelationPlan {
1342
+ return {
1343
+ ...r,
1344
+ where: normalizeWhereForClone(r.where),
1345
+ relations: r.relations?.map(normalizeRelationForClone),
1346
+ };
1347
+ }
1348
+
1349
+ /** Normalize every baked value a plan carries (where trees, window ids) for
1350
+ * the postMessage to the worker's `select` op. */
1351
+ function normalizePlanForClone(plan: QueryPlan): QueryPlan {
1352
+ return {
1353
+ ...plan,
1354
+ ids: plan.ids?.map(stableKey),
1355
+ where: normalizeWhereForClone(plan.where),
1356
+ relations: plan.relations?.map(normalizeRelationForClone),
1357
+ };
1358
+ }