@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.10

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 (53) hide show
  1. package/AGENTS.md +4 -3
  2. package/dist/index.d.ts +169 -9
  3. package/dist/index.js +4512 -2338
  4. package/dist/rows-worker.d.ts +1 -0
  5. package/dist/rows-worker.js +2639 -0
  6. package/dist/sqlite-open.js +1 -1
  7. package/dist/sqlite-worker.js +1 -1
  8. package/dist/types.d.ts +129 -13
  9. package/package.json +9 -4
  10. package/scripts/check-worker-entries.mjs +15 -2
  11. package/skills/sp00ky-core/SKILL.md +2 -0
  12. package/src/client/bucket-handle.ts +21 -1
  13. package/src/client/eager-paint.test.ts +82 -0
  14. package/src/client/services.ts +4 -1
  15. package/src/client/sp00ky-client.test.ts +143 -1
  16. package/src/client/sp00ky-client.ts +157 -19
  17. package/src/index.ts +9 -0
  18. package/src/kernel/effects.ts +12 -2
  19. package/src/kernel/interpreter.test.ts +17 -0
  20. package/src/kernel/interpreter.ts +5 -2
  21. package/src/modules/channel/hub.test.ts +223 -0
  22. package/src/modules/channel/hub.ts +355 -0
  23. package/src/modules/channel/index.ts +358 -14
  24. package/src/modules/channel/room.test.ts +340 -0
  25. package/src/modules/channel/room.ts +367 -0
  26. package/src/modules/channel/rooms.fixture.ts +383 -0
  27. package/src/modules/channel/share.test.ts +535 -0
  28. package/src/modules/channel/webrtc.ts +2 -2
  29. package/src/modules/devtools/storage-info.ts +4 -3
  30. package/src/query/materialize.saga.test.ts +16 -0
  31. package/src/query/materialize.saga.ts +7 -26
  32. package/src/query/materialize.ts +79 -3
  33. package/src/query/register.saga.test.ts +61 -0
  34. package/src/query/register.saga.ts +39 -2
  35. package/src/services/database/cache-engine.ts +17 -3
  36. package/src/services/database/engine-factory.ts +7 -0
  37. package/src/services/database/index.ts +1 -0
  38. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  39. package/src/services/database/rows-cache-engine.ts +921 -0
  40. package/src/services/database/rows-exec.integration.test.ts +589 -0
  41. package/src/services/database/rows-exec.ts +1027 -0
  42. package/src/services/database/rows-prewarm.ts +225 -0
  43. package/src/services/database/rows-store.test.ts +635 -0
  44. package/src/services/database/rows-store.ts +1208 -0
  45. package/src/services/database/rows-transport.fixture.ts +151 -0
  46. package/src/services/database/rows-worker.ts +588 -0
  47. package/src/services/database/sqlite-cache-engine.test.ts +22 -1
  48. package/src/services/database/sqlite-cache-engine.ts +55 -34
  49. package/src/services/database/sqlite-transport.ts +7 -5
  50. package/src/services/tabs/support.ts +6 -4
  51. package/src/types.ts +39 -6
  52. package/tsdown.config.ts +42 -1
  53. package/vitest.config.ts +4 -0
@@ -1,4 +1,9 @@
1
- import { applyPatch, type Operation } from 'fast-json-patch';
1
+ // Default import, not `{ applyPatch }`: fast-json-patch 3.x is CommonJS for
2
+ // Node (its ESM build is reachable only through the `module` field bundlers
3
+ // read) and fills `module.exports` via Object.assign, which Node's CJS export
4
+ // lexer cannot see. A named import makes `dist/index.js` throw a SyntaxError on
5
+ // load in Node ESM (SSR, Vitest). Same pattern as `pino` in services/logger.
6
+ import jsonPatch, { type Operation } from 'fast-json-patch';
2
7
  import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
3
8
  import { withTimeout } from '../../utils/index';
4
9
  import type { QueryPlan, RelationPlan, WhereNode } from '@spooky-sync/query-builder';
@@ -55,7 +60,7 @@ import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-in
55
60
  * on a fresh bucket throws "no such table". Keep in sync with the systemSchema
56
61
  * block in `local-migrator.ts`.
57
62
  */
58
- const SNAPSHOT_TABLE = '_00_circuit_snapshot';
63
+ export const SNAPSHOT_TABLE = '_00_circuit_snapshot';
59
64
 
60
65
  const SYSTEM_TABLES = [
61
66
  '_00_stream_processor_state',
@@ -116,7 +121,7 @@ export class SqliteCacheEngine implements LocalStore {
116
121
  private transport: SqliteTransport | null = null;
117
122
  private storeEpoch = 0;
118
123
  private knownTables = new Set<string>();
119
- private useOpfs: boolean;
124
+ protected useOpfs: boolean;
120
125
  /** Whether `select` runs as one worker round-trip (plan executed in-worker).
121
126
  * Flipped off at runtime if the worker script predates the `select` op
122
127
  * (stale cached bundle) — degrade to the legacy multi-hop path, don't break. */
@@ -125,7 +130,7 @@ export class SqliteCacheEngine implements LocalStore {
125
130
  * downgrade (configured true, effective false) from a configured-off. */
126
131
  private workerSelectConfigured: boolean;
127
132
  private events: DatabaseEventSystem = createDatabaseEventSystem();
128
- private bucketId = 'anon';
133
+ protected bucketId = 'anon';
129
134
  /** Deadline for one worker round trip; see `localOpTimeoutMs`. */
130
135
  private readonly localOpTimeoutMs: number;
131
136
  /** Durability of the local store, set on every open. A plain Set of callbacks
@@ -136,19 +141,19 @@ export class SqliteCacheEngine implements LocalStore {
136
141
  /** Schemaless — tables are created lazily on first write; no migrator. */
137
142
  readonly usesSurqlSchema = false;
138
143
 
139
- readonly engineKind = 'sqlite' as const;
144
+ readonly engineKind: 'sqlite' | 'rows' = 'sqlite';
140
145
 
141
146
  /** Shared-tabs mode: the engine's transport is swapped at runtime by the
142
147
  * TabsCoordinator (owner worker as leader, leader's port as follower). */
143
- private shared: boolean;
148
+ protected shared: boolean;
144
149
  /** Leaderless parking (shared mode): ops entering the opQueue await this
145
150
  * gate until a new role lands or the timeout rejects them. */
146
151
  private roleGate: { promise: Promise<void>; release: () => void } | null = null;
147
152
  private roleGateTimer: ReturnType<typeof setTimeout> | null = null;
148
153
 
149
154
  constructor(
150
- private config: Sp00kyConfig<any>['database'],
151
- private logger: Logger,
155
+ protected config: Sp00kyConfig<any>['database'],
156
+ protected logger: Logger,
152
157
  opts: { useOpfs?: boolean; workerSelect?: boolean; shared?: boolean } = {}
153
158
  ) {
154
159
  this.localOpTimeoutMs = Math.max(0, config.localOpTimeoutMs ?? DEFAULT_LOCAL_OP_TIMEOUT_MS);
@@ -279,7 +284,7 @@ export class SqliteCacheEngine implements LocalStore {
279
284
  * the boot/switch atomicity below.) */
280
285
  private opQueue: Promise<unknown> = Promise.resolve();
281
286
 
282
- private call<T = any>(type: string, payload?: unknown): Promise<T> {
287
+ protected call<T = any>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
283
288
  const enqueuedAt = performance.now();
284
289
  const run = async () => {
285
290
  // Leaderless window (shared mode): park behind the role gate instead of
@@ -287,7 +292,7 @@ export class SqliteCacheEngine implements LocalStore {
287
292
  if (this.roleGate) await this.roleGate.promise;
288
293
  // Time spent waiting behind other ops in the queue, not doing work.
289
294
  getStats().queueWaitMs += performance.now() - enqueuedAt;
290
- return this.rawCall<T>(type, payload);
295
+ return this.rawCall<T>(type, payload, transfer);
291
296
  };
292
297
  const result = this.opQueue.then(run, run);
293
298
  // Keep the chain alive regardless of individual failures.
@@ -325,7 +330,7 @@ export class SqliteCacheEngine implements LocalStore {
325
330
  }
326
331
  }
327
332
 
328
- private rawCall<T = any>(type: string, payload?: unknown): Promise<T> {
333
+ protected rawCall<T = any>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
329
334
  if (!this.transport) throw new Error('SqliteCacheEngine: not connected');
330
335
  // --- instrumentation: live, inspectable via `globalThis.__sqliteStats` ---
331
336
  const s = getStats();
@@ -360,7 +365,7 @@ export class SqliteCacheEngine implements LocalStore {
360
365
  // one, and killing it mid-write would cost more than the wait.
361
366
  const timeoutMs = this.localOpTimeoutMs;
362
367
  const result = withTimeout(
363
- this.transport.call<T>(type, payload),
368
+ this.transport.call<T>(type, payload, transfer),
364
369
  timeoutMs,
365
370
  () => new LocalOpTimeoutError(type, timeoutMs)
366
371
  ).then(
@@ -735,7 +740,7 @@ export class SqliteCacheEngine implements LocalStore {
735
740
  this.transport = null;
736
741
  }
737
742
 
738
- private async ensureTable(table: string): Promise<void> {
743
+ protected async ensureTable(table: string): Promise<void> {
739
744
  if (this.knownTables.has(table)) return;
740
745
  await this.call('run', {
741
746
  sql: `CREATE TABLE IF NOT EXISTS "${table}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`,
@@ -758,7 +763,8 @@ export class SqliteCacheEngine implements LocalStore {
758
763
 
759
764
  // ---- reads ---------------------------------------------------------------
760
765
 
761
- async select(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<Row[]> {
766
+ // `_opts.paintKey` names the read for a store that keeps answers to paint from; this one keeps none.
767
+ async select(plan: QueryPlan, params: Record<string, unknown> = {}, _opts?: { paintKey?: string }): Promise<Row[]> {
762
768
  if (this.workerSelect) {
763
769
  // ONE round-trip: the worker executes the whole plan (table creation,
764
770
  // base select, relation tree, JSON parse) and returns structured-clone
@@ -998,7 +1004,7 @@ export class SqliteCacheEngine implements LocalStore {
998
1004
  // RFC6902 (fast-json-patch) applied read-modify-write — SQLite's json_patch
999
1005
  // is RFC7396 merge-patch and would misinterpret op arrays.
1000
1006
  const existing = (await this.getById(table, id)) ?? { id: stableKey(id) };
1001
- const next = applyPatch(existing, patches as Operation[]).newDocument as Row;
1007
+ const next = jsonPatch.applyPatch(existing, patches as Operation[]).newDocument as Row;
1002
1008
  await this.upsert(table, id, next, 'replace');
1003
1009
  }
1004
1010
 
@@ -1125,25 +1131,16 @@ export class SqliteCacheEngine implements LocalStore {
1125
1131
  if (op.value) return rows.map((r) => r[op.value!]);
1126
1132
  return op.select ? rows.map((r) => project(r, op.select!)) : rows;
1127
1133
  }
1128
- case 'count': {
1129
- await this.ensureTable(op.table);
1130
- const bind: unknown[] = [];
1131
- let sql = `SELECT COUNT(*) AS n FROM "${op.table}"`;
1132
- if (op.where && op.where.length > 0) sql += ` WHERE ${renderWhereSql(op.where, bind, {})}`;
1133
- const { rows } = await this.call<{ rows: { n: number }[] }>('exec', { sql, bind });
1134
+ case 'count':
1134
1135
  // `GROUP ALL` collapses to a single `{ count }` row on SurrealDB; match
1135
1136
  // it exactly so callers can read `rows[0].count` on either engine.
1136
- return [{ count: rows?.[0]?.n ?? 0 }];
1137
- }
1137
+ return [{ count: await this.countRows(op.table, op.where) }];
1138
1138
  case 'infoForDb': {
1139
- const { rows } = await this.call<{ rows: { name: string }[] }>('exec', {
1140
- sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
1141
- });
1142
1139
  // SurrealDB answers with the DEFINE statement per table. Nothing here
1143
1140
  // parses it (the DevTools explorer only reads the keys), so a truthful
1144
1141
  // schemaless stand-in beats inventing field definitions.
1145
1142
  const tables: Record<string, string> = {};
1146
- for (const r of rows ?? []) tables[r.name] = `DEFINE TABLE ${r.name} SCHEMALESS`;
1143
+ for (const name of await this.listTables()) tables[name] = `DEFINE TABLE ${name} SCHEMALESS`;
1147
1144
  return { tables, analyzers: {}, functions: {}, params: {}, users: {} };
1148
1145
  }
1149
1146
  case 'upsert':
@@ -1172,8 +1169,7 @@ export class SqliteCacheEngine implements LocalStore {
1172
1169
  await this.delete(tableOf(op.id), op.id);
1173
1170
  return pureWriteOpResult(op);
1174
1171
  case 'deleteAll':
1175
- await this.ensureTable(op.table);
1176
- await this.call('run', { sql: `DELETE FROM "${op.table}"` });
1172
+ await this.deleteAllRows(op.table);
1177
1173
  return pureWriteOpResult(op);
1178
1174
  case 'let': {
1179
1175
  let result = await this.execOp(op.inner, scope, vars);
@@ -1198,12 +1194,37 @@ export class SqliteCacheEngine implements LocalStore {
1198
1194
  }
1199
1195
  }
1200
1196
 
1197
+ // The three statements `execOp` needs beyond the verbs. Methods of their own
1198
+ // so an engine that stores rows differently (`RowsCacheEngine`) answers them
1199
+ // its own way.
1200
+
1201
+ protected async countRows(table: string, where?: WhereNode[]): Promise<number> {
1202
+ await this.ensureTable(table);
1203
+ const bind: unknown[] = [];
1204
+ let sql = `SELECT COUNT(*) AS n FROM "${table}"`;
1205
+ if (where && where.length > 0) sql += ` WHERE ${renderWhereSql(where, bind, {})}`;
1206
+ const { rows } = await this.call<{ rows: { n: number }[] }>('exec', { sql, bind });
1207
+ return rows?.[0]?.n ?? 0;
1208
+ }
1209
+
1210
+ protected async listTables(): Promise<string[]> {
1211
+ const { rows } = await this.call<{ rows: { name: string }[] }>('exec', {
1212
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
1213
+ });
1214
+ return (rows ?? []).map((r) => r.name);
1215
+ }
1216
+
1217
+ protected async deleteAllRows(table: string): Promise<void> {
1218
+ await this.ensureTable(table);
1219
+ await this.call('run', { sql: `DELETE FROM "${table}"` });
1220
+ }
1221
+
1201
1222
  /**
1202
1223
  * Compile a pure-write op list to ONE worker `batch` (single SQLite
1203
1224
  * transaction). Ensures each touched table exists, then one statement per op.
1204
1225
  * Merges happen in-SQL via json_patch — no read-back round-trips.
1205
1226
  */
1206
- private async runWriteBatch(ops: SqlOp[]): Promise<void> {
1227
+ protected async runWriteBatch(ops: SqlOp[]): Promise<void> {
1207
1228
  const stmts: { sql: string; bind?: unknown[] }[] = [];
1208
1229
  const tables = new Set<string>();
1209
1230
  const ensure = (t: string) => {
@@ -1249,7 +1270,7 @@ export class SqliteCacheEngine implements LocalStore {
1249
1270
  if (stmts.length > 0) await this.call('batch', stmts);
1250
1271
  }
1251
1272
 
1252
- private async rawSelectTable(
1273
+ protected async rawSelectTable(
1253
1274
  table: string,
1254
1275
  where?: WhereNode[],
1255
1276
  orderBy?: OrderBy,
@@ -1364,7 +1385,7 @@ function getStats(): SqliteStats {
1364
1385
  * `stableKey` string (the exact value `scalar()` would bind on the main
1365
1386
  * thread), leave everything clone-representable untouched.
1366
1387
  */
1367
- function toCloneSafe(v: unknown): unknown {
1388
+ export function toCloneSafe(v: unknown): unknown {
1368
1389
  if (v === null || typeof v !== 'object') return v;
1369
1390
  if (Array.isArray(v) || v instanceof Uint8Array || v instanceof Date) return v;
1370
1391
  const proto = Object.getPrototypeOf(v);
@@ -1372,7 +1393,7 @@ function toCloneSafe(v: unknown): unknown {
1372
1393
  return stableKey(v);
1373
1394
  }
1374
1395
 
1375
- function normalizeWhereForClone(nodes: WhereNode[] | undefined): WhereNode[] | undefined {
1396
+ export function normalizeWhereForClone(nodes: WhereNode[] | undefined): WhereNode[] | undefined {
1376
1397
  if (!nodes) return nodes;
1377
1398
  return nodes.map((n) =>
1378
1399
  'or' in n
@@ -1391,7 +1412,7 @@ function normalizeRelationForClone(r: RelationPlan): RelationPlan {
1391
1412
 
1392
1413
  /** Normalize every baked value a plan carries (where trees, window ids) for
1393
1414
  * the postMessage to the worker's `select` op. */
1394
- function normalizePlanForClone(plan: QueryPlan): QueryPlan {
1415
+ export function normalizePlanForClone(plan: QueryPlan): QueryPlan {
1395
1416
  return {
1396
1417
  ...plan,
1397
1418
  ids: plan.ids?.map(stableKey),
@@ -19,7 +19,8 @@ export interface SqliteTransport {
19
19
  readonly kind: 'worker' | 'port';
20
20
  /** True while the transport can carry a request. */
21
21
  readonly connected: boolean;
22
- call<T = unknown>(type: string, payload?: unknown): Promise<T>;
22
+ /** `transfer` hands the listed buffers over instead of copying them. */
23
+ call<T = unknown>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T>;
23
24
  /** Reject every pending request with `reason`. Safe to call repeatedly. */
24
25
  failAll(reason: string): void;
25
26
  /** failAll + release the underlying channel. Terminal. `err` overrides the
@@ -69,13 +70,13 @@ abstract class BaseTransport implements SqliteTransport {
69
70
  else p.reject(new Error(error));
70
71
  }
71
72
 
72
- call<T = unknown>(type: string, payload?: unknown): Promise<T> {
73
+ call<T = unknown>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
73
74
  if (this.closed) return Promise.reject(this.makeError('transport closed'));
74
75
  const id = ++this.seq;
75
76
  return new Promise<T>((resolve, reject) => {
76
77
  this.pending.set(id, { resolve, reject });
77
78
  try {
78
- this.post({ id, type, payload });
79
+ this.post({ id, type, payload }, transfer);
79
80
  } catch (e) {
80
81
  this.pending.delete(id);
81
82
  reject(e);
@@ -215,8 +216,9 @@ export class PortSqliteTransport extends BaseTransport {
215
216
  this.onPortDead(reason);
216
217
  }
217
218
 
218
- protected post(msg: unknown): void {
219
- this.port.postMessage(msg);
219
+ protected post(msg: unknown, transfer?: Transferable[]): void {
220
+ if (transfer) this.port.postMessage(msg, transfer);
221
+ else this.port.postMessage(msg);
220
222
  }
221
223
 
222
224
  protected makeError(reason: string): Error {
@@ -19,10 +19,12 @@ export type SharedTabsSupport =
19
19
 
20
20
  export function detectSharedTabsSupport(config: Sp00kyConfig<any>): SharedTabsSupport {
21
21
  if (config.sharedTabs !== true) return { supported: false, reason: 'flag-off' };
22
- // Shared-tabs only makes sense for the SQLite engine: it is the one whose
23
- // OPFS pool is single-holder. The SurrealDB engine and custom engines keep
24
- // their existing per-tab behavior.
25
- if (config.localEngine !== 'sqlite') return { supported: false, reason: 'engine-not-sqlite' };
22
+ // Shared-tabs only makes sense for the engines whose OPFS files are
23
+ // single-holder: SQLite and the row store. The SurrealDB engine and custom
24
+ // engines keep their existing per-tab behavior.
25
+ if (config.localEngine !== 'sqlite' && config.localEngine !== 'rows') {
26
+ return { supported: false, reason: 'engine-not-sqlite' };
27
+ }
26
28
  if (typeof window === 'undefined') return { supported: false, reason: 'not-browser' };
27
29
  if (typeof SharedWorker === 'undefined') return { supported: false, reason: 'no-shared-worker' };
28
30
  if (typeof MessageChannel === 'undefined') {
package/src/types.ts CHANGED
@@ -126,6 +126,8 @@ export interface LocalWorkers {
126
126
  surreal?: () => Worker;
127
127
  /** The SQLite engine's worker (`localEngine: 'sqlite'`): runs `@spooky-sync/core/sqlite-worker`. */
128
128
  sqlite?: () => Worker;
129
+ /** The row store's worker (`localEngine: 'rows'`): runs `@spooky-sync/core/rows-worker`. */
130
+ rows?: () => Worker;
129
131
  }
130
132
 
131
133
  /**
@@ -168,6 +170,28 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
168
170
  * failure the queue retries. `0` disables. Defaults to `60_000`.
169
171
  */
170
172
  queryTimeoutMs?: number;
173
+ /**
174
+ * `localEngine: 'rows'` only. Keep a copy of the rows the app reads at
175
+ * startup in localStorage (up to about 1 MB), so `peekSelect` / `peekByIds`
176
+ * can hand a screen what it showed last time before the store is open.
177
+ * Default `true` for a durable store; `false` turns it off.
178
+ */
179
+ paintCache?: boolean;
180
+ /**
181
+ * `localEngine: 'rows'` with `sharedTabs` only. Where a follower tab's
182
+ * reads are answered.
183
+ * - `'leader'` (default): by the leader tab's worker, over a port.
184
+ * - `'direct'`: by a worker of the follower's own that reads the store's
185
+ * file beside the leader. A read then never waits for the leader's
186
+ * work (a sync-down in another tab), and crosses no tab boundary.
187
+ * Writes still go to the leader. Needs shared OPFS access handles
188
+ * (Chrome 121+); elsewhere, and whenever its worker fails, a follower
189
+ * reads through the leader as before. The price: nothing but the
190
+ * leader's lock stands between two writers of the file, where the
191
+ * default has the browser refuse a second one, and each follower
192
+ * holds the store's index in memory.
193
+ */
194
+ followerReads?: 'leader' | 'direct';
171
195
  /**
172
196
  * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
173
197
  * or a query on the in-process surrealdb engine). Local ops are serialized
@@ -200,9 +224,13 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
200
224
  /**
201
225
  * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
202
226
  * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
203
- * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
204
- * is a passive queryable store — reactivity is driven by the remote SSP, not
205
- * this engine. See `services/database/cache-engine.ts`.
227
+ * OPFS persistence; `'rows'` (experimental) uses sp00ky's own row store in a
228
+ * Worker, also on OPFS: an append-only file per bucket with a flat index,
229
+ * built for this client's reads and writes and nothing else, and answering
230
+ * every query the way `'sqlite'` does; or pass a custom
231
+ * {@link LocalCacheEngine}. The local cache is a passive queryable store —
232
+ * reactivity is driven by the remote SSP, not this engine. See
233
+ * `services/database/cache-engine.ts` and `services/database/rows-store.ts`.
206
234
  */
207
235
  localEngine?: LocalEngineChoice;
208
236
  /**
@@ -233,7 +261,7 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
233
261
  };
234
262
  /**
235
263
  * Share ONE durable local store across all tabs of this origin (default
236
- * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
264
+ * `false`). Requires `localEngine: 'sqlite'` or `'rows'`. A SharedWorker broker elects a
237
265
  * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
238
266
  * worker and the sync loop, and follower tabs read/write the same store over
239
267
  * MessagePorts, so every tab is durable instead of only the first one.
@@ -252,8 +280,8 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
252
280
  /**
253
281
  * Persist the in-browser SSP circuit's store as a snapshot in the local
254
282
  * store, so a reload restores it and only steps in what changed since.
255
- * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
256
- * can hold the bytes) and `false` otherwise.
283
+ * Defaults to `true` under `localEngine: 'sqlite'` and `'rows'` (the
284
+ * OPFS-backed stores can hold the bytes) and `false` otherwise.
257
285
  *
258
286
  * Without a snapshot the circuit is primed by reading every cached row back
259
287
  * out of the local store; either way a reload never re-downloads the working
@@ -318,6 +346,11 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
318
346
  * apply. `iceServers` configures the default WebRTC transport (a public
319
347
  * STUN server when omitted; add TURN for networks that block direct
320
348
  * connections), `transport` replaces it.
349
+ *
350
+ * `share` sends this user's optimistic writes straight to their other
351
+ * devices, per table (`share: { tables: { game: true, note: (row) =>
352
+ * !row.draft } }`), through the room relay named by `relay` (the
353
+ * `sp00ky-relay` server, one socket per browser). Off unless set.
321
354
  */
322
355
  channels?: ChannelsConfig;
323
356
  /**
package/tsdown.config.ts CHANGED
@@ -61,15 +61,41 @@ const versionDefinePlugin = {
61
61
  const workerUrlPlugin = {
62
62
  name: 'sp00ky-worker-url',
63
63
  transform(code: string) {
64
- if (!code.includes('sqlite-worker.ts') && !code.includes('tabs-broker-worker.ts')) return null;
64
+ if (
65
+ !code.includes('sqlite-worker.ts') &&
66
+ !code.includes('rows-worker.ts') &&
67
+ !code.includes('tabs-broker-worker.ts')
68
+ ) {
69
+ return null;
70
+ }
65
71
  return code
66
72
  .split('sqlite-worker.ts')
67
73
  .join('sqlite-worker.js')
74
+ .split('rows-worker.ts')
75
+ .join('rows-worker.js')
68
76
  .split('tabs-broker-worker.ts')
69
77
  .join('tabs-broker-worker.js');
70
78
  },
71
79
  };
72
80
 
81
+ // V8 compiles a function the first time it is called, on the thread calling
82
+ // it. `//# allFunctionsCalledOnLoad` as a file's FIRST line (Chrome 136+) has
83
+ // the whole file compiled while it loads, off that thread, and kept in the
84
+ // code cache. Only for the row store's worker: a small file of which every
85
+ // function runs within its first requests, and which a page is waiting for.
86
+ // Measured: 0.6 to 1.5 ms off the worker's first `open`. An app's bundler
87
+ // that minifies the worker drops the comment; the docs say how to keep it.
88
+ const COMPILE_HINT = '//# allFunctionsCalledOnLoad\n';
89
+ const compileHintPlugin = {
90
+ name: 'sp00ky-compile-hint',
91
+ generateBundle(_options: unknown, bundle: Record<string, { type: string; code?: string }>) {
92
+ for (const [name, file] of Object.entries(bundle)) {
93
+ if (name !== 'rows-worker.js') continue;
94
+ if (file.type === 'chunk' && typeof file.code === 'string' && !file.code.startsWith(COMPILE_HINT)) file.code = COMPILE_HINT + file.code;
95
+ }
96
+ },
97
+ };
98
+
73
99
  export default defineConfig([
74
100
  {
75
101
  // `sqlite-worker` is emitted at `dist/sqlite-worker.js` (top level, NOT under
@@ -120,4 +146,19 @@ export default defineConfig([
120
146
  },
121
147
  plugins: [versionDefinePlugin],
122
148
  },
149
+ // The row store's worker (`localEngine: 'rows'`), at `dist/rows-worker.js`
150
+ // like the SQLite one. A build of its own so the file holds everything the
151
+ // worker runs and nothing else: the compile hint on its first line then
152
+ // covers the store and its queries, and no page ever loads hinted code.
153
+ {
154
+ entry: { 'rows-worker': 'src/services/database/rows-worker.ts' },
155
+ format: ['esm'],
156
+ dts: true,
157
+ clean: false,
158
+ hash: false,
159
+ outputOptions: {
160
+ chunkFileNames: (chunk: { name: string }) => (chunk.name === 'rows-worker.d' ? '[name].js' : 'rows-worker-[name].js'),
161
+ },
162
+ plugins: [versionDefinePlugin, compileHintPlugin],
163
+ },
123
164
  ]);
package/vitest.config.ts CHANGED
@@ -3,6 +3,9 @@ import { defineConfig } from 'vitest/config';
3
3
  // Thresholds start at the numbers the suite hits today and are ratcheted per
4
4
  // directory as the saga core lands (see the plan's commit 10). Exclusions:
5
5
  // *.fixture.ts / src/testing/** test-only harness code
6
+ // rows-worker.ts runs inside a Worker (OPFS sync access handles +
7
+ // Web Locks); its ops are `handleRowsOp`, which
8
+ // the engine tests run in-process
6
9
  // sqlite-worker.ts runs inside a Worker (sqlite-wasm + OPFS +
7
10
  // postMessage globals); covered by the sqlite
8
11
  // integration tests and the build check
@@ -25,6 +28,7 @@ export default defineConfig({
25
28
  'src/**/*.fixture.ts',
26
29
  'src/testing/**',
27
30
  'src/services/database/sqlite-worker.ts',
31
+ 'src/services/database/rows-worker.ts',
28
32
  'src/client/services.ts',
29
33
  ],
30
34
  thresholds: {