@spooky-sync/core 0.0.1-canary.8 → 0.0.1-canary.80

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 (65) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +854 -339
  3. package/dist/index.js +2633 -396
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/types.d.ts +494 -0
  7. package/package.json +39 -9
  8. package/skills/sp00ky-core/SKILL.md +258 -0
  9. package/skills/sp00ky-core/references/auth.md +98 -0
  10. package/skills/sp00ky-core/references/config.md +76 -0
  11. package/src/build-globals.d.ts +12 -0
  12. package/src/events/events.test.ts +2 -1
  13. package/src/events/index.ts +3 -0
  14. package/src/index.ts +9 -2
  15. package/src/modules/auth/events/index.ts +2 -1
  16. package/src/modules/auth/index.ts +59 -20
  17. package/src/modules/cache/index.ts +41 -29
  18. package/src/modules/cache/types.ts +2 -2
  19. package/src/modules/crdt/crdt-field.ts +281 -0
  20. package/src/modules/crdt/crdt-hydration.test.ts +206 -0
  21. package/src/modules/crdt/index.ts +352 -0
  22. package/src/modules/data/data.status.test.ts +108 -0
  23. package/src/modules/data/index.ts +726 -108
  24. package/src/modules/data/window-query.test.ts +52 -0
  25. package/src/modules/data/window-query.ts +130 -0
  26. package/src/modules/devtools/index.ts +89 -21
  27. package/src/modules/devtools/versions.test.ts +74 -0
  28. package/src/modules/devtools/versions.ts +81 -0
  29. package/src/modules/feature-flag/index.ts +166 -0
  30. package/src/modules/ref-tables.test.ts +56 -0
  31. package/src/modules/ref-tables.ts +57 -0
  32. package/src/modules/sync/engine.ts +97 -37
  33. package/src/modules/sync/events/index.ts +3 -2
  34. package/src/modules/sync/queue/queue-down.ts +5 -4
  35. package/src/modules/sync/queue/queue-up.ts +14 -13
  36. package/src/modules/sync/scheduler.ts +2 -2
  37. package/src/modules/sync/sync.ts +676 -58
  38. package/src/modules/sync/utils.test.ts +269 -2
  39. package/src/modules/sync/utils.ts +182 -17
  40. package/src/otel/index.ts +127 -0
  41. package/src/services/database/database.ts +11 -11
  42. package/src/services/database/events/index.ts +2 -1
  43. package/src/services/database/local-migrator.ts +21 -21
  44. package/src/services/database/local.test.ts +33 -0
  45. package/src/services/database/local.ts +192 -32
  46. package/src/services/database/remote.ts +13 -13
  47. package/src/services/logger/index.ts +6 -101
  48. package/src/services/persistence/localstorage.ts +2 -2
  49. package/src/services/persistence/resilient.ts +41 -0
  50. package/src/services/persistence/surrealdb.ts +9 -9
  51. package/src/services/stream-processor/index.ts +248 -37
  52. package/src/services/stream-processor/permissions.test.ts +47 -0
  53. package/src/services/stream-processor/permissions.ts +53 -0
  54. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  55. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  56. package/src/services/stream-processor/wasm-types.ts +18 -2
  57. package/src/sp00ky.auth-order.test.ts +65 -0
  58. package/src/sp00ky.ts +625 -0
  59. package/src/types.ts +140 -13
  60. package/src/utils/index.ts +35 -13
  61. package/src/utils/parser.ts +3 -2
  62. package/src/utils/surql.ts +24 -15
  63. package/src/utils/withRetry.test.ts +1 -1
  64. package/tsdown.config.ts +55 -1
  65. package/src/spooky.ts +0 -392
package/src/sp00ky.ts ADDED
@@ -0,0 +1,625 @@
1
+ import { DataModule } from './modules/data/index';
2
+ import type {
3
+ Sp00kyConfig,
4
+ QueryTimeToLive,
5
+ QueryStatusCallback,
6
+ Sp00kyQueryResultPromise,
7
+ PersistenceClient,
8
+ UpdateOptions,
9
+ RunOptions} from './types';
10
+ import {
11
+ LocalDatabaseService,
12
+ LocalMigrator,
13
+ RemoteDatabaseService,
14
+ } from './services/database/index';
15
+ import type { UpEvent } from './modules/sync/index';
16
+ import { Sp00kySync } from './modules/sync/index';
17
+ import type {
18
+ GetTable,
19
+ InnerQuery,
20
+ QueryOptions,
21
+ SchemaStructure,
22
+ TableModel,
23
+ TableNames,
24
+ BucketNames,
25
+ BackendNames,
26
+ BackendRoutes,
27
+ RoutePayload} from '@spooky-sync/query-builder';
28
+ import {
29
+ QueryBuilder
30
+ } from '@spooky-sync/query-builder';
31
+
32
+ import { DevToolsService } from './modules/devtools/index';
33
+ import { createLogger } from './services/logger/index';
34
+ import { AuthService } from './modules/auth/index';
35
+ import { StreamProcessorService } from './services/stream-processor/index';
36
+ import { extractSelectPermissions } from './services/stream-processor/permissions';
37
+ import { EventSystem } from './events/index';
38
+ import { CacheModule } from './modules/cache/index';
39
+ import type { RecordWithId } from './modules/cache/index';
40
+ import { CrdtManager, CrdtField } from './modules/crdt/index';
41
+ import { FeatureFlagModule, FeatureFlagHandle } from './modules/feature-flag/index';
42
+ import type { FeatureFlagOptions } from './modules/feature-flag/index';
43
+ import { LocalStoragePersistenceClient } from './services/persistence/localstorage';
44
+ import { parseParams, encodeRecordId } from './utils/index';
45
+ import { SurrealDBPersistenceClient } from './services/persistence/surrealdb';
46
+ import { ResilientPersistenceClient } from './services/persistence/resilient';
47
+
48
+ export class BucketHandle {
49
+ constructor(private bucketName: string, private remote: RemoteDatabaseService) {}
50
+
51
+ async put(path: string, content: string | Uint8Array | Blob): Promise<void> {
52
+ await this.remote.query(`RETURN f"${this.bucketName}:/${path}".put($content);`, { content });
53
+ }
54
+
55
+ async get(path: string): Promise<unknown> {
56
+ const [result] = await this.remote.query<[unknown]>(`RETURN f"${this.bucketName}:/${path}".get();`);
57
+ return result;
58
+ }
59
+
60
+ async delete(path: string): Promise<void> {
61
+ await this.remote.query(`RETURN f"${this.bucketName}:/${path}".delete();`);
62
+ }
63
+
64
+ async exists(path: string): Promise<boolean> {
65
+ const [result] = await this.remote.query<[boolean]>(`RETURN f"${this.bucketName}:/${path}".exists();`);
66
+ return result;
67
+ }
68
+
69
+ async head(path: string): Promise<Record<string, unknown>> {
70
+ const [result] = await this.remote.query<[Record<string, unknown>]>(`RETURN f"${this.bucketName}:/${path}".head();`);
71
+ return result;
72
+ }
73
+
74
+ async copy(sourcePath: string, targetPath: string): Promise<void> {
75
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".copy($target);`, { target: targetPath });
76
+ }
77
+
78
+ async rename(sourcePath: string, targetPath: string): Promise<void> {
79
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".rename($target);`, { target: targetPath });
80
+ }
81
+
82
+ async list(prefix?: string): Promise<string[]> {
83
+ const p = prefix ?? '';
84
+ const [result] = await this.remote.query<[string[]]>(`RETURN f"${this.bucketName}:/${p}".list();`);
85
+ return result;
86
+ }
87
+ }
88
+
89
+ export class Sp00kyClient<S extends SchemaStructure> {
90
+ private local: LocalDatabaseService;
91
+ private remote: RemoteDatabaseService;
92
+ private persistenceClient: PersistenceClient;
93
+
94
+ private migrator: LocalMigrator;
95
+ private cache: CacheModule;
96
+ private dataModule: DataModule<S>;
97
+ private sync: Sp00kySync<S>;
98
+ private devTools: DevToolsService;
99
+ private crdtManager: CrdtManager;
100
+ private featureFlags!: FeatureFlagModule<S>;
101
+
102
+ private logger: ReturnType<typeof createLogger>;
103
+ public auth: AuthService<S>;
104
+ public streamProcessor: StreamProcessorService;
105
+
106
+ get remoteClient() {
107
+ return this.remote.getClient();
108
+ }
109
+
110
+ get localClient() {
111
+ return this.local.getClient();
112
+ }
113
+
114
+ get pendingMutationCount(): number {
115
+ return this.sync.pendingMutationCount;
116
+ }
117
+
118
+ /** Number of times the initial list_ref LIVE subscription retried on
119
+ * the most recent `setCurrentUserId` call. 0 when the SSP's
120
+ * pre-emptive user-table creation got there first; >0 when LIVE
121
+ * registration hit a "table not found" race. Exposed so the e2e
122
+ * suite can guard the pre-emptive path against regression. */
123
+ get liveRetryCount(): number {
124
+ return this.sync.liveRetryCount;
125
+ }
126
+
127
+ subscribeToPendingMutations(cb: (count: number) => void): () => void {
128
+ return this.sync.subscribeToPendingMutations(cb);
129
+ }
130
+
131
+ constructor(private config: Sp00kyConfig<S>) {
132
+ const logger = createLogger(config.logLevel ?? 'info', config.otelTransmit);
133
+ this.logger = logger.child({ service: 'Sp00kyClient' });
134
+
135
+ this.logger.info(
136
+ {
137
+ config: { ...config, schema: '[SchemaStructure]' },
138
+ Category: 'sp00ky-client::Sp00kyClient::constructor',
139
+ },
140
+ 'Sp00kyClient initialized'
141
+ );
142
+
143
+ this.local = new LocalDatabaseService(this.config.database, logger);
144
+ this.remote = new RemoteDatabaseService(this.config.database, logger);
145
+
146
+ if (config.persistenceClient === 'surrealdb') {
147
+ this.persistenceClient = new SurrealDBPersistenceClient(this.local, logger);
148
+ } else if (config.persistenceClient === 'localstorage' || !config.persistenceClient) {
149
+ this.persistenceClient = new LocalStoragePersistenceClient(logger);
150
+ } else {
151
+ this.persistenceClient = config.persistenceClient;
152
+ }
153
+
154
+ this.persistenceClient = new ResilientPersistenceClient(this.persistenceClient, logger);
155
+
156
+ this.streamProcessor = new StreamProcessorService(
157
+ new EventSystem(['stream_update']),
158
+ this.local,
159
+ this.persistenceClient,
160
+ logger
161
+ );
162
+ this.migrator = new LocalMigrator(this.local, logger);
163
+
164
+ this.cache = new CacheModule(
165
+ this.local,
166
+ this.streamProcessor,
167
+ (update) => {
168
+ // Direct callback from cache to data module
169
+ this.dataModule.onStreamUpdate(update);
170
+ },
171
+ logger
172
+ );
173
+
174
+ // Initialize CRDT Manager. `local` is used to read the initial
175
+ // `_00_crdt` snapshot when a field opens AND to mirror every local
176
+ // edit (so reload/offline see the freshest state); `remote` is used
177
+ // for the debounced outgoing UPSERTs and the parent-table LIVE feed.
178
+ // The debounce window is configurable via `crdtDebounceMs`.
179
+ this.crdtManager = new CrdtManager(
180
+ this.config.schema,
181
+ this.local,
182
+ this.remote,
183
+ logger,
184
+ config.crdtDebounceMs ?? 500,
185
+ );
186
+
187
+ this.dataModule = new DataModule(
188
+ this.cache,
189
+ this.local,
190
+ this.config.schema,
191
+ logger,
192
+ this.config.streamDebounceTime
193
+ );
194
+
195
+ // Initialize Auth
196
+ this.auth = new AuthService(this.config.schema, this.remote, this.persistenceClient, logger);
197
+
198
+ // Initialize Sync
199
+ this.sync = new Sp00kySync(
200
+ this.local,
201
+ this.remote,
202
+ this.cache,
203
+ this.dataModule,
204
+ this.config.schema,
205
+ this.logger,
206
+ { refSyncIntervalMs: this.config.refSyncIntervalMs }
207
+ );
208
+
209
+ // Initialize feature flags. Reuses the down-queue to register SSP plans
210
+ // on `_00_user_feature` and the auth subscription to re-register handles
211
+ // when the signed-in user changes.
212
+ this.featureFlags = new FeatureFlagModule({
213
+ dataModule: this.dataModule,
214
+ sync: this.sync,
215
+ auth: this.auth,
216
+ logger,
217
+ });
218
+
219
+ // Initialize DevTools
220
+ this.devTools = new DevToolsService(
221
+ this.local,
222
+ this.remote,
223
+ logger,
224
+ this.config.schema,
225
+ this.auth,
226
+ this.dataModule
227
+ );
228
+
229
+ // Register DevTools as a receiver for stream updates
230
+ this.streamProcessor.addReceiver(this.devTools);
231
+
232
+ // Wire up callbacks instead of events
233
+ this.setupCallbacks();
234
+ }
235
+
236
+ /**
237
+ * Setup direct callbacks instead of event subscriptions
238
+ */
239
+ private setupCallbacks() {
240
+ // Surface query fetch-status changes (idle/fetching) in DevTools. Logs a
241
+ // discrete event and triggers a state push so the active-queries panel
242
+ // reflects the flip immediately.
243
+ this.dataModule.onQueryStatusChange = (queryHash, status) => {
244
+ this.devTools.logEvent('QUERY_STATUS_CHANGED', { queryHash, status });
245
+ };
246
+
247
+ // Keep an actively-watched query's remote `_00_query.lastActiveAt` fresh so
248
+ // the server TTL sweep doesn't expire it out from under live subscribers.
249
+ // DataModule fires this only while the query still has ≥1 subscriber.
250
+ this.dataModule.onHeartbeat = (queryHash) => {
251
+ void this.sync.heartbeatQuery(queryHash).catch((err) => {
252
+ this.logger.warn(
253
+ { err, queryHash, Category: 'sp00ky-client::Sp00kyClient::onHeartbeat' },
254
+ 'TTL heartbeat failed'
255
+ );
256
+ });
257
+ };
258
+
259
+ // Eager teardown of an opt-in deregistered query: enqueue a `cleanup`
260
+ // down-event so it's serialized after any in-flight register/sync for the
261
+ // same query (avoids out-of-order delete-before-create).
262
+ this.dataModule.onDeregister = (queryHash) => {
263
+ this.sync.enqueueDownEvent({ type: 'cleanup', payload: { hash: queryHash } });
264
+ };
265
+
266
+ // Mutation callback for sync
267
+ this.dataModule.onMutation((mutations: UpEvent[]) => {
268
+ // Notify DevTools
269
+ this.devTools.onMutation(mutations);
270
+
271
+ // Enqueue in Sync
272
+ if (mutations.length > 0) {
273
+ this.sync.enqueueMutation(mutations);
274
+ }
275
+ });
276
+
277
+ // Sync events for incoming updates
278
+ this.sync.events.subscribe('SYNC_QUERY_UPDATED', (event: any) => {
279
+ this.devTools.logEvent('SYNC_QUERY_UPDATED', event.payload);
280
+ });
281
+
282
+ // Hand list_ref-driven row ingests to the CrdtManager so CRDT body
283
+ // / cursor updates reach the receiver even when the cross-session
284
+ // LIVE on the parent table is filtered out by the SurrealDB
285
+ // permission-LIVE gap. Same-user clients receive these rows via
286
+ // CrdtManager's own `LIVE SELECT * FROM <table>`; this hook is the
287
+ // redundant path that fires when only the list_ref bumped.
288
+ this.sync.engineEvents.subscribe('SYNC_REMOTE_DATA_INGESTED', (event: any) => {
289
+ try {
290
+ const records: Array<Record<string, any>> = event.payload?.records ?? [];
291
+ for (const row of records) {
292
+ const id = row?.id;
293
+ const table =
294
+ id && typeof id === 'object' && id.table !== undefined
295
+ ? String(id.table)
296
+ : undefined;
297
+ if (!table) continue;
298
+ this.crdtManager.applyRow(table, row);
299
+ }
300
+ } catch (err) {
301
+ this.logger.debug(
302
+ { err, Category: 'sp00ky-client::engineEvents::ingested' },
303
+ 'applyRow forwarding from sync ingest failed'
304
+ );
305
+ }
306
+ });
307
+
308
+ // Database events for DevTools
309
+ this.local.getEvents().subscribe('DATABASE_LOCAL_QUERY', (event: any) => {
310
+ this.devTools.logEvent('LOCAL_QUERY', event.payload);
311
+ });
312
+
313
+ this.remote.getEvents().subscribe('DATABASE_REMOTE_QUERY', (event: any) => {
314
+ this.devTools.logEvent('REMOTE_QUERY', event.payload);
315
+ });
316
+ }
317
+
318
+ async init() {
319
+ this.logger.info(
320
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
321
+ 'Sp00kyClient initialization started'
322
+ );
323
+ try {
324
+ await this.local.connect();
325
+ this.logger.debug(
326
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
327
+ 'Local database connected'
328
+ );
329
+
330
+ await this.migrator.provision(this.config.schemaSurql);
331
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Schema provisioned');
332
+
333
+ await this.remote.connect();
334
+ this.logger.debug(
335
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
336
+ 'Remote database connected'
337
+ );
338
+
339
+ await this.streamProcessor.init();
340
+ // Seed table `select` permissions from the schema before any query is
341
+ // registered — otherwise the SSP default-denies every non-`_00_` table.
342
+ this.streamProcessor.setPermissions(
343
+ extractSelectPermissions(this.config.schemaSurql)
344
+ );
345
+ this.logger.debug(
346
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
347
+ 'StreamProcessor initialized'
348
+ );
349
+
350
+ await this.auth.init();
351
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Auth initialized');
352
+
353
+ // Salt query-id hashing with the SurrealDB session id so two browsers
354
+ // for the same user don't collide on shared `_00_query` rows. The same
355
+ // session id is the `session_id` key in `_00_cursor` rows, so the
356
+ // CrdtManager needs it too.
357
+ const sessionId = await this.fetchSessionId();
358
+ await this.dataModule.init(sessionId);
359
+ this.crdtManager.setSessionId(sessionId);
360
+ this.logger.debug(
361
+ { sessionId, Category: 'sp00ky-client::Sp00kyClient::init' },
362
+ 'DataModule initialized'
363
+ );
364
+
365
+ // Refresh the salt whenever auth state flips (sign-in, sign-out).
366
+ // session::id() changes per WebSocket session, and a sign-in spawns
367
+ // a new authenticated session, so the salt must follow. Also
368
+ // forward the user id into `DataModule` and `Sp00kySync` so they
369
+ // can route to per-user `_00_query_user_<id>` /
370
+ // `_00_list_ref_user_<id>` tables in `RefMode.Dedicated` — the
371
+ // LIVE subscription on `_00_list_ref_user_<id>` is restarted
372
+ // under the new auth context inside `Sp00kySync.setCurrentUserId`
373
+ // since SurrealDB binds the LIVE permission at registration time.
374
+ //
375
+ // Sync prefix BEFORE the first `await`: setting `currentUserId`
376
+ // synchronously here is critical because the AuthProvider's own
377
+ // subscribe callback runs right after ours and immediately enables
378
+ // queries that depend on the user id. Any `await` before
379
+ // `setCurrentUserId` would let those queries register against the
380
+ // stale (null) user id and hit the wrong `_00_query[_user_*]`
381
+ // table.
382
+ this.auth.subscribe(async (userId) => {
383
+ this.dataModule.setCurrentUserId(userId);
384
+ // Mirror the server's `fn::query::register` auth injection for the
385
+ // in-browser SSP: feed the current user's full record id + access
386
+ // method so `$auth`-gated table permissions (e.g. `thread`) resolve
387
+ // locally instead of being rejected. Set synchronously BEFORE the
388
+ // first `await` (like `setCurrentUserId` above) so queries that
389
+ // re-register on this auth flip see the fresh context, not a stale one.
390
+ this.streamProcessor.setSessionAuth(
391
+ this.auth.currentUser?.id ? encodeRecordId(this.auth.currentUser.id) : null,
392
+ this.auth.access
393
+ );
394
+ const next = await this.fetchSessionId();
395
+ this.dataModule.setSessionId(next);
396
+ this.crdtManager.setSessionId(next);
397
+ try {
398
+ await this.sync.setCurrentUserId(userId);
399
+ } catch (e) {
400
+ this.logger.error(
401
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::authChange' },
402
+ 'sync.setCurrentUserId failed'
403
+ );
404
+ }
405
+ });
406
+
407
+ await this.sync.init();
408
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Sync initialized');
409
+
410
+ this.featureFlags.init();
411
+ this.logger.debug(
412
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
413
+ 'FeatureFlagModule initialized'
414
+ );
415
+
416
+ this.logger.info(
417
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
418
+ 'Sp00kyClient initialization completed successfully'
419
+ );
420
+ } catch (e) {
421
+ this.logger.error(
422
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::init' },
423
+ 'Sp00kyClient initialization failed'
424
+ );
425
+ throw e;
426
+ }
427
+ }
428
+
429
+ async close() {
430
+ await this.featureFlags.closeAll();
431
+ this.crdtManager.closeAll();
432
+ await this.local.close();
433
+ await this.remote.close();
434
+ }
435
+
436
+ /**
437
+ * Subscribe to a feature flag for the current user. Returns a
438
+ * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
439
+ * accessors reflect the latest assignment from `_00_user_feature`,
440
+ * and whose `subscribe(cb)` fires whenever that assignment changes.
441
+ *
442
+ * Permissions are enforced by SurrealDB: a client can only ever see
443
+ * its own row, and cannot create or modify assignments.
444
+ */
445
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle {
446
+ return this.featureFlags.feature(key, options);
447
+ }
448
+
449
+ authenticate(token: string) {
450
+ return this.remote.getClient().authenticate(token);
451
+ }
452
+
453
+ /**
454
+ * Open a CRDT field for collaborative editing.
455
+ * Returns a CrdtField with a LoroDoc that can be bound to any editor.
456
+ * Also starts a LIVE SELECT on the parent table for real-time sync;
457
+ * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
458
+ */
459
+ async openCrdtField(
460
+ table: string,
461
+ recordId: string,
462
+ field: string,
463
+ fallbackText?: string,
464
+ ): Promise<CrdtField> {
465
+ return this.crdtManager.open(table, recordId, field, fallbackText);
466
+ }
467
+
468
+ /**
469
+ * Close a CRDT field when editing is done.
470
+ */
471
+ closeCrdtField(table: string, recordId: string, field: string): void {
472
+ this.crdtManager.close(table, recordId, field);
473
+ }
474
+
475
+ deauthenticate() {
476
+ return this.remote.getClient().invalidate();
477
+ }
478
+
479
+ query<Table extends TableNames<S>>(
480
+ table: Table,
481
+ options: QueryOptions<TableModel<GetTable<S, Table>>, false>,
482
+ ttl: QueryTimeToLive = '10m'
483
+ ): QueryBuilder<S, Table, Sp00kyQueryResultPromise> {
484
+ return new QueryBuilder<S, Table, Sp00kyQueryResultPromise>(
485
+ this.config.schema,
486
+ table,
487
+ async (q) => ({
488
+ hash: await this.initQuery(table, q, ttl),
489
+ }),
490
+ options
491
+ );
492
+ }
493
+
494
+ private async initQuery<Table extends TableNames<S>>(
495
+ table: Table,
496
+ q: InnerQuery<any, any, any>,
497
+ ttl: QueryTimeToLive
498
+ ) {
499
+ const tableSchema = this.config.schema.tables.find((t) => t.name === table);
500
+ if (!tableSchema) {
501
+ throw new Error(`Table ${table} not found`);
502
+ }
503
+
504
+ const params = parseParams(tableSchema.columns, q.selectQuery.vars ?? {});
505
+ const hash = await this.dataModule.query(table, q.selectQuery.query, params, ttl);
506
+
507
+ // Instant-hydrate: for a cold query, fetch its rows one-shot from the remote
508
+ // (its own surql, run directly like useRemote) and display them NOW; the full
509
+ // realtime registration proceeds below. Hydrated rows carry their `_00_rv`
510
+ // versions so the registration's syncRecords skips re-pulling unchanged bodies.
511
+ // Best-effort: any failure (e.g. offline) just falls through to registration.
512
+ if (this.config.instantHydrate !== false && this.dataModule.isCold(hash)) {
513
+ try {
514
+ const [rows] = await this.remote.query<[RecordWithId[]]>(q.selectQuery.query, params);
515
+ await this.dataModule.applyHydration(hash, rows ?? []);
516
+ } catch (err) {
517
+ this.logger.warn(
518
+ { err, hash, Category: 'sp00ky-client::Sp00kyClient::instantHydrate' },
519
+ 'Instant hydrate failed; proceeding with registration'
520
+ );
521
+ }
522
+ }
523
+
524
+ await this.sync.enqueueDownEvent({
525
+ type: 'register',
526
+ payload: {
527
+ hash,
528
+ },
529
+ });
530
+
531
+ return hash;
532
+ }
533
+
534
+ async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive) {
535
+ const tableName = sql.split('FROM ')[1].split(' ')[0];
536
+ return this.dataModule.query(tableName, sql, params, ttl);
537
+ }
538
+
539
+ async subscribe(
540
+ queryHash: string,
541
+ callback: (records: Record<string, any>[]) => void,
542
+ options?: { immediate?: boolean }
543
+ ): Promise<() => void> {
544
+ return this.dataModule.subscribe(queryHash, callback, options);
545
+ }
546
+
547
+ /**
548
+ * Opt-in eager teardown for a query whose last subscriber has gone away
549
+ * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
550
+ * while any subscriber remains. Tears down the remote `_00_query` view +
551
+ * local WASM view instead of waiting for the TTL sweep. Default behavior
552
+ * (no call here) keeps the view resident for cheap re-subscription.
553
+ */
554
+ deregisterQuery(queryHash: string): void {
555
+ this.dataModule.deregisterQuery(queryHash);
556
+ }
557
+
558
+ /**
559
+ * Subscribe to a query's fetch-status changes (idle/fetching). With
560
+ * `{ immediate: true }` the callback fires synchronously with the current
561
+ * status. Powers the `useQuery` hook's `isFetching()` accessor.
562
+ */
563
+ subscribeQueryStatus(
564
+ queryHash: string,
565
+ callback: QueryStatusCallback,
566
+ options?: { immediate?: boolean }
567
+ ): () => void {
568
+ return this.dataModule.subscribeStatus(queryHash, callback, options);
569
+ }
570
+
571
+ /**
572
+ * Report the frontend processing time (ms) a client framework spent applying
573
+ * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
574
+ * surface the "frontend" phase of the per-query timing breakdown.
575
+ */
576
+ reportFrontendTiming(queryHash: string, ms: number): void {
577
+ this.dataModule.recordFrontendTiming(queryHash, ms);
578
+ }
579
+
580
+ run<
581
+ B extends BackendNames<S>,
582
+ R extends BackendRoutes<S, B>,
583
+ >(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions) {
584
+ return this.dataModule.run(backend, path, payload, options);
585
+ }
586
+
587
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle {
588
+ return new BucketHandle(name, this.remote);
589
+ }
590
+
591
+ create(id: string, data: Record<string, unknown>) {
592
+ return this.dataModule.create(id, data);
593
+ }
594
+
595
+ update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions) {
596
+ return this.dataModule.update(table, id, data, options);
597
+ }
598
+
599
+ delete(table: string, id: string) {
600
+ return this.dataModule.delete(table, id);
601
+ }
602
+
603
+ async useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T> {
604
+ return fn(this.remote.getClient());
605
+ }
606
+
607
+ /**
608
+ * Fetch SurrealDB's `session::id()` as a string. Used as a salt for
609
+ * query-id hashing so two sessions for the same user get distinct
610
+ * `_00_query` rows. Returns empty string if the query fails (we still
611
+ * boot, just without session scoping for IDs).
612
+ */
613
+ private async fetchSessionId(): Promise<string> {
614
+ try {
615
+ const [sid] = await this.remote.query<[string]>('RETURN <string>session::id()');
616
+ return typeof sid === 'string' ? sid : '';
617
+ } catch (e) {
618
+ this.logger.warn(
619
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::fetchSessionId' },
620
+ 'Failed to fetch session::id() — proceeding with empty salt'
621
+ );
622
+ return '';
623
+ }
624
+ }
625
+ }