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

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,439 @@
1
+ import { a as renderOrderSql, i as projectedDataSql, l as resolveRelations, n as openDb, o as renderWhereSql, r as project, s as reviveRow, u as stableKey } from "./sqlite-open.js";
2
+ import sqlite3InitModule from "@sqlite.org/sqlite-wasm";
3
+
4
+ //#region src/services/database/sqlite-lock-verify.ts
5
+ const LOCK_VERIFY_TIMEOUT_MS = 2e3;
6
+ async function verifyLockStillHeld$1(locks, name, fence, timeoutMs = LOCK_VERIFY_TIMEOUT_MS, warn = () => {}) {
7
+ if (!locks || !name || typeof locks.query !== "function") return;
8
+ let timer;
9
+ try {
10
+ const state = await Promise.race([locks.query(), new Promise((resolve) => {
11
+ timer = setTimeout(() => resolve(null), timeoutMs);
12
+ })]);
13
+ if (state === null) {
14
+ warn(`lock verification did not answer within ${timeoutMs}ms; trusting the steal callback`);
15
+ return;
16
+ }
17
+ if (!(state.held ?? []).some((l) => l.name === name)) await fence("lock missing after suspected freeze");
18
+ } catch {} finally {
19
+ if (timer) clearTimeout(timer);
20
+ }
21
+ }
22
+
23
+ //#endregion
24
+ //#region src/services/database/sqlite-select.ts
25
+ function ensureTable(db, table) {
26
+ if (db.knownTables.has(table)) return;
27
+ db.run(`CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`);
28
+ db.knownTables.add(table);
29
+ }
30
+ function execRows(db, sql, bind) {
31
+ return db.exec(sql, bind).map((r) => reviveRow(r.data));
32
+ }
33
+ /** Mirrors the engine's `selectByIds`: fetch by primary id, preserving `ids`
34
+ * order unless an ORDER BY overrides it. */
35
+ function selectByIds(db, table, ids, opts) {
36
+ if (ids.length === 0) return [];
37
+ ensureTable(db, table);
38
+ const keys = ids.map(stableKey);
39
+ const placeholders = keys.map(() => "?").join(", ");
40
+ const bind = [];
41
+ const dataCol = opts?.select ? projectedDataSql(opts.select, bind) : "data";
42
+ bind.push(...keys);
43
+ let sql = `SELECT ${dataCol} FROM "${table}" WHERE id IN (${placeholders})`;
44
+ if (opts?.orderBy && opts.orderBy.length > 0) sql += renderOrderSql(opts.orderBy);
45
+ let rows = execRows(db, sql, bind);
46
+ if (!opts?.orderBy || opts.orderBy.length === 0) {
47
+ const pos = new Map(keys.map((k, i) => [k, i]));
48
+ rows = rows.sort((a, b) => (pos.get(stableKey(a.id)) ?? 0) - (pos.get(stableKey(b.id)) ?? 0));
49
+ }
50
+ return rows;
51
+ }
52
+ /** Mirrors the engine's `fetchRelation` SQL exactly. */
53
+ function fetchRelation(db, req) {
54
+ ensureTable(db, req.table);
55
+ const keys = req.keys.map(stableKey);
56
+ const placeholders = keys.map(() => "?").join(", ");
57
+ const bind = [...keys];
58
+ const lhs = req.matchField === "id" ? "id" : `json_extract(data, '$.${req.matchField}')`;
59
+ let sql = `SELECT data FROM "${req.table}" WHERE ${lhs} IN (${placeholders})`;
60
+ if (req.where && req.where.length > 0) sql += ` AND ${renderWhereSql(req.where, bind, {})}`;
61
+ if (req.orderBy && req.orderBy.length > 0) sql += renderOrderSql(req.orderBy);
62
+ const rows = execRows(db, sql, bind);
63
+ return req.select ? rows.map((r) => project(r, req.select)) : rows;
64
+ }
65
+ async function executeSelect(plan, params, db) {
66
+ const counter = { n: 0 };
67
+ const fetcher = { fetchRelation: (req) => {
68
+ counter.n++;
69
+ return Promise.resolve(fetchRelation(db, req));
70
+ } };
71
+ if (plan.ids) {
72
+ const rows = selectByIds(db, plan.table, plan.ids, {
73
+ select: plan.select,
74
+ orderBy: plan.orderBy
75
+ });
76
+ await resolveRelations(rows, plan.relations, fetcher);
77
+ return {
78
+ rows,
79
+ relationFetches: counter.n
80
+ };
81
+ }
82
+ ensureTable(db, plan.table);
83
+ const bind = [];
84
+ let sql = `SELECT ${plan.select ? projectedDataSql(plan.select, bind) : "data"} FROM "${plan.table}"`;
85
+ if (plan.where && plan.where.length > 0) sql += ` WHERE ${renderWhereSql(plan.where, bind, params)}`;
86
+ if (plan.orderBy && plan.orderBy.length > 0) sql += renderOrderSql(plan.orderBy);
87
+ else sql += ` ORDER BY id`;
88
+ if (plan.limit !== void 0) sql += ` LIMIT ${Number(plan.limit)}`;
89
+ if (plan.offset !== void 0) sql += ` OFFSET ${Number(plan.offset)}`;
90
+ const rows = execRows(db, sql, bind);
91
+ await resolveRelations(rows, plan.relations, fetcher);
92
+ return {
93
+ rows,
94
+ relationFetches: counter.n
95
+ };
96
+ }
97
+
98
+ //#endregion
99
+ //#region src/services/database/sqlite-worker.ts
100
+ /**
101
+ * Dedicated Web Worker that owns the SQLite-WASM handle. All DB access is
102
+ * funnelled through here (the main thread never touches the wasm module), which
103
+ * is also what the OPFS VFS requires — file access must happen off the main
104
+ * thread. Persistence uses the **OPFS SAHPool VFS**: durable, and (unlike the
105
+ * classic OPFS VFS) it does NOT require COOP/COEP cross-origin isolation
106
+ * headers, so host apps embedding the client need no server changes. When OPFS
107
+ * is unavailable it retries, then falls back to an in-memory DB and REPORTS the
108
+ * loss of durability (see `sqlite-open.ts`) instead of degrading silently.
109
+ *
110
+ * Message protocol (request/response keyed by `id`; replies go to the channel
111
+ * the request arrived on):
112
+ * { id, type: 'open', payload: { dbName, useOpfs, workerLockName? } }
113
+ * -> { id, ok, persisted, opfsError? }
114
+ * { id, type: 'exec', payload: { sql, bind } } -> { id, ok, rows }
115
+ * { id, type: 'run', payload: { sql, bind } } -> { id, ok }
116
+ * { id, type: 'batch', payload: [{ sql, bind }] } (atomic BEGIN/COMMIT)
117
+ * { id, type: 'select', payload: { plan, params } } -> { id, ok, rows, relationFetches }
118
+ * { id, type: 'close' }
119
+ * { id, type: 'shutdown' } (owner only: close + pauseVfs + self.close)
120
+ * { id, type: 'relock', payload: { workerLockName } } (owner only)
121
+ * { id, type: 'add-client', payload: { clientId } } + ev.ports[0] (owner only)
122
+ * { id, type: 'remove-client', payload: { clientId } } (owner only)
123
+ *
124
+ * Multi-client (shared-tabs mode): the OWNER (the leader tab's engine) speaks
125
+ * on the worker's own channel and controls the lifecycle. Follower tabs get a
126
+ * MessagePort each (`add-client`) and may only issue data ops
127
+ * (exec/run/batch/select). Every op, from any channel, runs through ONE op
128
+ * chain so an async `select` from one client can never interleave with another
129
+ * client's `batch` at the VFS layer.
130
+ *
131
+ * Leader fencing (shared-tabs mode): `open` may carry `workerLockName`, a Web
132
+ * Lock this worker acquires BEFORE opening the pool and holds for the DB's
133
+ * lifetime. The name is unique per leadership, so the lock being gone has
134
+ * exactly one meaning: the broker stole it because this tab was presumed dead
135
+ * (usually frozen). When that happens the worker FENCES itself: closes the DB,
136
+ * releases the OPFS sync access handles (pauseVfs), tells the owner, and
137
+ * refuses every further op. A frozen-then-thawed ex-leader therefore can never
138
+ * write the durable file after a new leader took over. The thaw gate below
139
+ * closes the wake-up ordering race where a queued write could run before the
140
+ * lock-loss callback fires.
141
+ *
142
+ * `select` executes a whole QueryPlan — table creation, base select, the full
143
+ * `.related()` tree (shared `resolveRelations`), and JSON row parsing — in ONE
144
+ * round-trip, returning structured-clone row objects. This is the first-load
145
+ * hot path; the per-statement ops remain for the write/shim paths.
146
+ */
147
+ let db = null;
148
+ let pool = null;
149
+ /** Once fenced, every op is refused and the DB stays closed. Terminal. */
150
+ let fenced = false;
151
+ /** The per-leadership lock currently held (null = no fencing active). A
152
+ * relock (same-leader re-promotion after a broker restart) briefly holds two
153
+ * locks: the new one is installed here first, then the old one's own release
154
+ * is called, so there is no window where neither is held. */
155
+ let currentLock = null;
156
+ function workerLocks() {
157
+ const nav = globalThis.navigator;
158
+ return nav?.locks && typeof nav.locks.request === "function" ? nav.locks : null;
159
+ }
160
+ /**
161
+ * Acquire `name` exclusively without waiting. Resolves with a handle when
162
+ * granted, null when someone else holds it. If the request settles while the
163
+ * holder still believes it owns the lock, the broker stole it: fence.
164
+ */
165
+ function acquireWorkerLock(name) {
166
+ const locks = workerLocks();
167
+ if (!locks) return Promise.resolve({
168
+ name,
169
+ release() {}
170
+ });
171
+ return new Promise((resolve) => {
172
+ let granted = false;
173
+ let intentional = false;
174
+ let releaseGrant = null;
175
+ locks.request(name, {
176
+ mode: "exclusive",
177
+ ifAvailable: true
178
+ }, (lock) => {
179
+ if (!lock) {
180
+ resolve(null);
181
+ return;
182
+ }
183
+ granted = true;
184
+ resolve({
185
+ name,
186
+ release() {
187
+ intentional = true;
188
+ releaseGrant?.();
189
+ }
190
+ });
191
+ return new Promise((release) => {
192
+ releaseGrant = release;
193
+ });
194
+ }).then(() => {
195
+ if (granted && !intentional) fence("worker lock stolen");
196
+ }, () => {
197
+ if (granted && !intentional) fence("worker lock request failed");
198
+ });
199
+ });
200
+ }
201
+ function releaseHeldLock() {
202
+ currentLock?.release();
203
+ currentLock = null;
204
+ }
205
+ /**
206
+ * Terminal teardown after leadership loss. Closing the DB first makes
207
+ * pauseVfs legal (it throws while files are open); pausing releases the sync
208
+ * access handles so the NEW leader's open succeeds without waiting for this
209
+ * worker to be garbage collected.
210
+ */
211
+ async function fence(reason) {
212
+ if (fenced) return;
213
+ fenced = true;
214
+ console.error(`[sp00ky] sqlite worker fenced (${reason}): leadership was taken over, closing the database and refusing further ops.`);
215
+ try {
216
+ db?.close();
217
+ } catch {}
218
+ db = null;
219
+ try {
220
+ pool?.pauseVfs?.();
221
+ } catch {}
222
+ pool = null;
223
+ try {
224
+ self.postMessage({
225
+ type: "lock-lost",
226
+ reason
227
+ });
228
+ } catch {}
229
+ releaseHeldLock();
230
+ self.close();
231
+ }
232
+ /**
233
+ * A frozen tab's worker resumes with its message queue intact, and a queued
234
+ * write could run BEFORE the lock-steal callback fires. Both the 1s interval
235
+ * and every op call `noteTick()`; whichever runs first after a long gap kicks
236
+ * off a lock verification, and ops await it before touching the DB. The gap
237
+ * threshold must stay BELOW the broker's pong timeout: a freeze shorter than
238
+ * the threshold cannot have triggered a steal yet, so skipping the check for
239
+ * small gaps is safe.
240
+ */
241
+ const FREEZE_SUSPECT_MS = 1e4;
242
+ let lastTickAt = performance.now();
243
+ let thawVerification = null;
244
+ function noteTick() {
245
+ const now = performance.now();
246
+ const gap = now - lastTickAt;
247
+ lastTickAt = now;
248
+ if (gap > FREEZE_SUSPECT_MS && currentLock && !fenced && !thawVerification) thawVerification = verifyLockStillHeld().finally(() => {
249
+ thawVerification = null;
250
+ });
251
+ }
252
+ setInterval(noteTick, 1e3);
253
+ function verifyLockStillHeld() {
254
+ return verifyLockStillHeld$1(workerLocks(), currentLock?.name, (reason) => fence(reason), void 0, (msg) => console.warn(`[sqlite-worker] ${msg}`));
255
+ }
256
+ async function open(dbName, useOpfs, systemTables = [], workerLockName, openOptions) {
257
+ if (workerLockName) {
258
+ const handle = await acquireWorkerLock(workerLockName);
259
+ if (!handle) throw new Error("worker-lock-unavailable");
260
+ releaseHeldLock();
261
+ currentLock = handle;
262
+ }
263
+ const result = await openDb(await sqlite3InitModule(), dbName, useOpfs, openOptions ?? {});
264
+ db = result.db;
265
+ pool = result.pool ?? null;
266
+ for (const t of systemTables) db.exec({ sql: `CREATE TABLE IF NOT EXISTS "${t}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)` });
267
+ try {
268
+ db.exec({ sql: "PRAGMA busy_timeout = 5000; PRAGMA cache_size = -32000;" });
269
+ } catch {}
270
+ return {
271
+ persisted: result.persisted,
272
+ opfsError: result.opfsError
273
+ };
274
+ }
275
+ function closeDb() {
276
+ db?.close();
277
+ db = null;
278
+ pool = null;
279
+ selectDb.knownTables.clear();
280
+ releaseHeldLock();
281
+ }
282
+ function exec(sql, bind) {
283
+ if (!db) throw new Error("sqlite: DB not open");
284
+ return db.exec({
285
+ sql,
286
+ bind,
287
+ rowMode: "object",
288
+ returnValue: "resultRows"
289
+ });
290
+ }
291
+ function run(sql, bind) {
292
+ if (!db) throw new Error("sqlite: DB not open");
293
+ db.exec({
294
+ sql,
295
+ bind
296
+ });
297
+ }
298
+ function batch(stmts) {
299
+ if (!db) throw new Error("sqlite: DB not open");
300
+ db.exec({ sql: "BEGIN" });
301
+ try {
302
+ for (const s of stmts) db.exec({
303
+ sql: s.sql,
304
+ bind: s.bind
305
+ });
306
+ db.exec({ sql: "COMMIT" });
307
+ } catch (e) {
308
+ try {
309
+ db.exec({ sql: "ROLLBACK" });
310
+ } catch {}
311
+ throw e;
312
+ }
313
+ }
314
+ /** DB handle for `executeSelect` (see `sqlite-select.ts`, the unit-testable
315
+ * plan executor). `knownTables` is cleared on open/close, which covers both
316
+ * the solo fresh-worker path and the shared-mode same-worker bucket switch. */
317
+ const selectDb = {
318
+ exec: (sql, bind) => exec(sql, bind),
319
+ run,
320
+ knownTables: /* @__PURE__ */ new Set()
321
+ };
322
+ /** Follower client ports, keyed by the clientId the owner assigned. */
323
+ const clients = /* @__PURE__ */ new Map();
324
+ /** Data ops a follower client port may issue; lifecycle stays owner-only. */
325
+ const CLIENT_OPS = new Set([
326
+ "exec",
327
+ "run",
328
+ "batch",
329
+ "select"
330
+ ]);
331
+ /**
332
+ * ONE chain for every op from every channel. The handlers for `open` and
333
+ * `select` are async; without this, a follower's select could interleave with
334
+ * the owner's batch mid-transaction at the VFS layer. (Solo mode kept this
335
+ * invariant on the main thread via the engine's opQueue; with multiple client
336
+ * ports only the worker can.)
337
+ */
338
+ let opChain = Promise.resolve();
339
+ async function handle(type, payload, source) {
340
+ if (fenced) throw new Error("sqlite: fenced, leadership was taken over");
341
+ if (source === "client" && !CLIENT_OPS.has(type)) throw new Error(`sqlite worker: op ${type} is not allowed on a client port`);
342
+ switch (type) {
343
+ case "open":
344
+ selectDb.knownTables.clear();
345
+ {
346
+ const result = await open(payload.dbName, payload.useOpfs, payload.systemTables, payload.workerLockName, payload.openOptions);
347
+ for (const t of payload.systemTables ?? []) selectDb.knownTables.add(t);
348
+ return result;
349
+ }
350
+ case "relock": {
351
+ const handle = await acquireWorkerLock(payload.workerLockName);
352
+ if (!handle) throw new Error("worker-lock-unavailable");
353
+ releaseHeldLock();
354
+ currentLock = handle;
355
+ return {};
356
+ }
357
+ case "select": return executeSelect(payload.plan, payload.params ?? {}, selectDb);
358
+ case "exec": return { rows: exec(payload.sql, payload.bind) };
359
+ case "run":
360
+ run(payload.sql, payload.bind);
361
+ return {};
362
+ case "batch":
363
+ batch(payload);
364
+ return {};
365
+ case "close":
366
+ closeDb();
367
+ return {};
368
+ case "shutdown":
369
+ try {
370
+ db?.close();
371
+ } catch {}
372
+ db = null;
373
+ try {
374
+ pool?.pauseVfs?.();
375
+ } catch {}
376
+ pool = null;
377
+ releaseHeldLock();
378
+ queueMicrotask(() => self.close());
379
+ return {};
380
+ case "remove-client":
381
+ clients.get(payload.clientId)?.close();
382
+ clients.delete(payload.clientId);
383
+ return {};
384
+ default: throw new Error(`sqlite worker: unknown message ${type}`);
385
+ }
386
+ }
387
+ function dispatch(target, data, source) {
388
+ const { id, type, payload } = data ?? {};
389
+ noteTick();
390
+ const t0 = performance.now();
391
+ const runOp = async () => {
392
+ try {
393
+ if (thawVerification) await thawVerification;
394
+ const result = await handle(type, payload, source);
395
+ target.postMessage({
396
+ id,
397
+ ok: true,
398
+ wt: performance.now() - t0,
399
+ ...result
400
+ });
401
+ } catch (err) {
402
+ target.postMessage({
403
+ id,
404
+ ok: false,
405
+ error: err instanceof Error ? err.message : String(err)
406
+ });
407
+ }
408
+ };
409
+ opChain = opChain.then(runOp, runOp);
410
+ }
411
+ self.onmessage = (ev) => {
412
+ const data = ev.data ?? {};
413
+ if (data.type === "add-client") {
414
+ const port = ev.ports?.[0];
415
+ const clientId = data.payload?.clientId;
416
+ if (!port || !clientId) {
417
+ self.postMessage({
418
+ id: data.id,
419
+ ok: false,
420
+ error: "sqlite worker: add-client needs a clientId and a transferred port"
421
+ });
422
+ return;
423
+ }
424
+ clients.get(clientId)?.close();
425
+ clients.set(clientId, port);
426
+ port.onmessage = (pe) => dispatch(port, pe.data, "client");
427
+ port.start?.();
428
+ self.postMessage({
429
+ id: data.id,
430
+ ok: true,
431
+ wt: 0
432
+ });
433
+ return;
434
+ }
435
+ dispatch(self, data, "owner");
436
+ };
437
+
438
+ //#endregion
439
+ export { };
@@ -0,0 +1,8 @@
1
+ //#region src/services/tabs/tabs-broker-worker.d.ts
2
+ /** Attach a connecting tab's port. Exported for the node test harness, which
3
+ * drives the broker with fake MessagePort pairs instead of a SharedWorker. */
4
+ declare function handleConnect(port: MessagePort): void;
5
+ /** Test-only: wipe module state so each test starts with a fresh broker. */
6
+ declare function __resetBrokerForTests(): void;
7
+ //#endregion
8
+ export { __resetBrokerForTests, handleConnect };