@spooky-sync/core 0.0.1-canary.23 → 0.0.1-canary.230

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 (165) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2650 -58
  3. package/dist/index.js +12800 -2419
  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 +141 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +138 -25
  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 +235 -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 +1861 -152
  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 +165 -86
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +228 -0
  65. package/src/modules/sync/queue/queue-down.ts +108 -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.rematerialize-after-fetch.test.ts +93 -0
  77. package/src/modules/sync/sync.settled-poll.test.ts +58 -0
  78. package/src/modules/sync/sync.subquery.test.ts +82 -0
  79. package/src/modules/sync/sync.tabs.test.ts +249 -0
  80. package/src/modules/sync/sync.ts +1868 -98
  81. package/src/modules/sync/utils.test.ts +269 -2
  82. package/src/modules/sync/utils.ts +201 -16
  83. package/src/otel/index.ts +13 -10
  84. package/src/services/blobs/blob-cache.test.ts +359 -0
  85. package/src/services/blobs/blob-cache.ts +603 -0
  86. package/src/services/blobs/blob-manifest.ts +227 -0
  87. package/src/services/blobs/blob-store.test.ts +77 -0
  88. package/src/services/blobs/blob-store.ts +359 -0
  89. package/src/services/blobs/blob.fixture.ts +90 -0
  90. package/src/services/blobs/index.ts +70 -0
  91. package/src/services/database/cache-engine.ts +193 -0
  92. package/src/services/database/connection-supervisor.test.ts +289 -0
  93. package/src/services/database/connection-supervisor.ts +415 -0
  94. package/src/services/database/database.query-timeout.test.ts +83 -0
  95. package/src/services/database/database.ts +41 -12
  96. package/src/services/database/engine-factory.ts +33 -0
  97. package/src/services/database/errors.ts +34 -0
  98. package/src/services/database/events/index.ts +2 -1
  99. package/src/services/database/index.ts +7 -0
  100. package/src/services/database/local-migrator.ts +30 -27
  101. package/src/services/database/local.test.ts +64 -0
  102. package/src/services/database/local.ts +484 -67
  103. package/src/services/database/plan-render.test.ts +159 -0
  104. package/src/services/database/plan-render.ts +108 -0
  105. package/src/services/database/relation-resolver.test.ts +413 -0
  106. package/src/services/database/relation-resolver.ts +0 -0
  107. package/src/services/database/remote.ts +192 -15
  108. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  109. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  110. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  111. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  112. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  113. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  114. package/src/services/database/sqlite-lock-verify.ts +45 -0
  115. package/src/services/database/sqlite-open.test.ts +150 -0
  116. package/src/services/database/sqlite-open.ts +164 -0
  117. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  118. package/src/services/database/sqlite-plan-sql.ts +138 -0
  119. package/src/services/database/sqlite-projection.test.ts +99 -0
  120. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  121. package/src/services/database/sqlite-select.test.ts +246 -0
  122. package/src/services/database/sqlite-select.ts +131 -0
  123. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  124. package/src/services/database/sqlite-transport.ts +224 -0
  125. package/src/services/database/sqlite-worker.ts +437 -0
  126. package/src/services/database/surql-translate.ts +416 -0
  127. package/src/services/database/surreal-cache-engine.ts +161 -0
  128. package/src/services/logger/index.ts +3 -2
  129. package/src/services/persistence/localstorage.ts +2 -2
  130. package/src/services/persistence/resilient.ts +11 -4
  131. package/src/services/persistence/surrealdb.ts +10 -10
  132. package/src/services/stream-processor/index.ts +796 -84
  133. package/src/services/stream-processor/permissions.test.ts +47 -0
  134. package/src/services/stream-processor/permissions.ts +53 -0
  135. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  136. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  137. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  138. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  139. package/src/services/stream-processor/wasm-types.ts +59 -3
  140. package/src/services/tabs/broker-client.ts +283 -0
  141. package/src/services/tabs/broker.test.ts +327 -0
  142. package/src/services/tabs/coordinator.test.ts +365 -0
  143. package/src/services/tabs/coordinator.ts +633 -0
  144. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  145. package/src/services/tabs/leader-locks.ts +75 -0
  146. package/src/services/tabs/protocol.ts +258 -0
  147. package/src/services/tabs/support.ts +36 -0
  148. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  149. package/src/sp00ky.auth-order.test.ts +112 -0
  150. package/src/sp00ky.init-query.test.ts +183 -0
  151. package/src/sp00ky.local-first.test.ts +60 -0
  152. package/src/sp00ky.ts +1772 -0
  153. package/src/types.ts +528 -13
  154. package/src/utils/blurhash.ts +90 -0
  155. package/src/utils/error-classification.test.ts +44 -0
  156. package/src/utils/error-classification.ts +7 -0
  157. package/src/utils/index.ts +79 -13
  158. package/src/utils/parser.test.ts +49 -120
  159. package/src/utils/parser.ts +32 -2
  160. package/src/utils/semver.test.ts +32 -0
  161. package/src/utils/semver.ts +30 -0
  162. package/src/utils/surql.ts +30 -18
  163. package/src/utils/withRetry.test.ts +1 -1
  164. package/tsdown.config.ts +86 -1
  165. package/src/spooky.ts +0 -395
package/src/sp00ky.ts ADDED
@@ -0,0 +1,1772 @@
1
+ import { DataModule } from './modules/data/index';
2
+ import type {
3
+ Sp00kyConfig,
4
+ QueryTimeToLive,
5
+ QueryStatusCallback,
6
+ Sp00kyQueryResultPromise,
7
+ PersistenceClient,
8
+ PreloadOptions,
9
+ UpdateOptions,
10
+ RunOptions,
11
+ SyncHealth,
12
+ StorageHealth,
13
+ } from './types';
14
+ import {
15
+ ConnectionSupervisor,
16
+ LocalMigrator,
17
+ RemoteDatabaseService,
18
+ createLocalEngine,
19
+ } from './services/database/index';
20
+ import type { LocalStore } from './services/database/index';
21
+ import { StaleEpochError } from './services/database/index';
22
+ import type { UpEvent } from './modules/sync/index';
23
+ import { Sp00kySync } from './modules/sync/index';
24
+ import type {
25
+ FinalQuery,
26
+ GetTable,
27
+ InnerQuery,
28
+ QueryOptions,
29
+ SchemaStructure,
30
+ TableModel,
31
+ TableNames,
32
+ BucketNames,
33
+ BackendNames,
34
+ BackendRoutes,
35
+ RoutePayload,
36
+ } from '@spooky-sync/query-builder';
37
+ import { QueryBuilder } from '@spooky-sync/query-builder';
38
+
39
+ import { DevToolsService } from './modules/devtools/index';
40
+ import { createLogger } from './services/logger/index';
41
+ import { AuthService } from './modules/auth/index';
42
+ import { StreamProcessorService } from './services/stream-processor/index';
43
+ import { extractSelectPermissions } from './services/stream-processor/permissions';
44
+ import { EventSystem } from './events/index';
45
+ import { CacheModule } from './modules/cache/index';
46
+ import type { RecordWithId } from './modules/cache/index';
47
+ import { CrdtManager, CrdtField } from './modules/crdt/index';
48
+ import { preloadLoro } from './modules/crdt/loro-loader';
49
+ import { FeatureFlagModule, FeatureFlagHandle } from './modules/feature-flag/index';
50
+ import type { FeatureFlagOptions, FeatureFlagOverride } from './modules/feature-flag/index';
51
+ import { AppReleaseModule, AppReleaseHandle } from './modules/app-release/index';
52
+ import type { AppReleaseOptions } from './modules/app-release/index';
53
+ import { LocalStoragePersistenceClient } from './services/persistence/localstorage';
54
+ import { ANON_USER_ID, bucketIdForUser } from './modules/ref-tables';
55
+ import { parseQueryParams, encodeRecordId, parseDuration } from './utils/index';
56
+ import { cleanRecord } from './utils/parser';
57
+ import { RecordId } from 'surrealdb';
58
+ import { SurrealDBPersistenceClient } from './services/persistence/surrealdb';
59
+ import { ResilientPersistenceClient } from './services/persistence/resilient';
60
+ import { detectSharedTabsSupport } from './services/tabs/support';
61
+ import { TabsCoordinator, type CoordinatorHooks } from './services/tabs/coordinator';
62
+ import { computeTabsFingerprint, hash53, type TabRole } from './services/tabs/protocol';
63
+ import type { SqliteCacheEngine } from './services/database/sqlite-cache-engine';
64
+ import type { BlobCache, BlobReadOptions, BlobUrlLease } from './services/blobs/index';
65
+ import { MemoryBlobStore, createBlobCache, resolveBlobBudget } from './services/blobs/index';
66
+
67
+ import {
68
+ blurhashSidecarPath,
69
+ encodeImageToBlurhash,
70
+ isImagePath,
71
+ isBlurhashValid,
72
+ type BlurhashSetting,
73
+ type BlurhashEncodeOptions,
74
+ } from './utils/blurhash';
75
+
76
+ /** Coerce whatever the `.get()` RPC hands back into a Blob. */
77
+ export function bucketContentToBlob(content: unknown): Blob | null {
78
+ if (content == null) return null;
79
+ if (content instanceof Blob) return content;
80
+ if (typeof content === 'string') return new Blob([content]);
81
+ if (content instanceof ArrayBuffer) return new Blob([content]);
82
+ // Uint8Array and friends. The cast sidesteps `ArrayBufferLike` vs
83
+ // `ArrayBuffer` (SharedArrayBuffer) in lib.dom's BlobPart.
84
+ if (ArrayBuffer.isView(content)) return new Blob([content as unknown as BlobPart]);
85
+ return null;
86
+ }
87
+
88
+ export interface BucketPutOptions {
89
+ /** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
90
+ blurhash?: BlurhashSetting;
91
+ }
92
+
93
+ export interface BucketPutResult {
94
+ /** The computed blurhash when the content was a hashable image; else null. */
95
+ blurhash: string | null;
96
+ }
97
+
98
+ interface BucketHandleSettings {
99
+ blurhash?: BlurhashSetting;
100
+ logger?: { warn: (obj: unknown, msg?: string) => void };
101
+ }
102
+
103
+ /**
104
+ * Paths known to have no blurhash sidecar, per tab. The blob cache has no
105
+ * negative caching, so without this every mount of a hashless image would pay
106
+ * one serialized remote read. Cleared when a put writes a sidecar or a delete
107
+ * removes the image. Keyed `${bucket}:${path}` (the image path, not the sidecar).
108
+ */
109
+ const missingBlurhash = new Set<string>();
110
+
111
+ export class BucketHandle {
112
+ constructor(
113
+ private bucketName: string,
114
+ private remote: RemoteDatabaseService,
115
+ /** Absent on the raw handle the cache itself reads through. */
116
+ private blobs?: BlobCache | null,
117
+ private settings?: BucketHandleSettings
118
+ ) {}
119
+
120
+ /** Effective blurhash setting: per-call option > client config > default ON. */
121
+ private resolveBlurhash(option?: BlurhashSetting): BlurhashEncodeOptions | null {
122
+ const setting = option ?? this.settings?.blurhash ?? true;
123
+ if (setting === false) return null;
124
+ return setting === true ? {} : setting;
125
+ }
126
+
127
+ async put(
128
+ path: string,
129
+ content: string | Uint8Array | Blob,
130
+ options?: BucketPutOptions
131
+ ): Promise<BucketPutResult> {
132
+ // Start hashing while the upload is in flight; both browser-side costs
133
+ // overlap and the sidecar put only queues once the main put resolved.
134
+ const encodeOptions = this.resolveBlurhash(options?.blurhash);
135
+ const hashPromise =
136
+ encodeOptions && isImagePath(path)
137
+ ? encodeImageToBlurhash(content, encodeOptions)
138
+ : Promise.resolve(null);
139
+
140
+ await this.remote.query(`RETURN f"${this.bucketName}:/${path}".put($content);`, { content });
141
+ // A path can be overwritten, so anything cached under it is now wrong.
142
+ await this.blobs?.invalidate({ bucket: this.bucketName, path });
143
+
144
+ // The sidecar is best-effort: a hash or sidecar failure must never fail
145
+ // the image put that triggered it.
146
+ let hash: string | null = null;
147
+ try {
148
+ hash = await hashPromise;
149
+ if (hash) {
150
+ const sidecar = blurhashSidecarPath(path);
151
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sidecar}".put($content);`, {
152
+ content: hash,
153
+ });
154
+ await this.blobs?.invalidate({ bucket: this.bucketName, path: sidecar });
155
+ missingBlurhash.delete(`${this.bucketName}:${path}`);
156
+ }
157
+ } catch (error) {
158
+ hash = null;
159
+ this.settings?.logger?.warn({ error, path }, 'blurhash sidecar put failed');
160
+ }
161
+ return { blurhash: hash };
162
+ }
163
+
164
+ /**
165
+ * The blurhash stored alongside an uploaded image (see
166
+ * {@link blurhashSidecarPath}), or null when there is none. Reads through the
167
+ * blob cache, so a warm client answers from OPFS without a network hop, and
168
+ * misses are remembered per tab so a hashless image costs at most one
169
+ * serialized remote read per session.
170
+ */
171
+ async blurhash(path: string): Promise<string | null> {
172
+ const cacheKey = `${this.bucketName}:${path}`;
173
+ if (missingBlurhash.has(cacheKey)) return null;
174
+ try {
175
+ const blob = await this.read(blurhashSidecarPath(path), { persist: true });
176
+ if (!blob) {
177
+ missingBlurhash.add(cacheKey);
178
+ return null;
179
+ }
180
+ const hash = (await blob.text()).trim();
181
+ if (!isBlurhashValid(hash).result) {
182
+ this.settings?.logger?.warn({ path }, 'blurhash sidecar holds an invalid hash');
183
+ missingBlurhash.add(cacheKey);
184
+ return null;
185
+ }
186
+ return hash;
187
+ } catch (error) {
188
+ // Transient failure: do NOT negative-cache, the next mount may succeed.
189
+ this.settings?.logger?.warn({ error, path }, 'blurhash sidecar read failed');
190
+ return null;
191
+ }
192
+ }
193
+
194
+ async get(path: string): Promise<unknown> {
195
+ const [result] = await this.remote.query<[unknown]>(
196
+ `RETURN f"${this.bucketName}:/${path}".get();`
197
+ );
198
+ return result;
199
+ }
200
+
201
+ /**
202
+ * Read through the local blob cache: OPFS first, the bucket second. Unlike
203
+ * {@link get} this survives a reload and works offline. Returns null when the
204
+ * file exists in neither place.
205
+ */
206
+ async read(path: string, options?: BlobReadOptions): Promise<Blob | null> {
207
+ if (!this.blobs) return bucketContentToBlob(await this.get(path));
208
+ return this.blobs.read({ bucket: this.bucketName, path }, options);
209
+ }
210
+
211
+ /**
212
+ * A refcounted object URL for `path`, suitable for `<img src>`. The caller
213
+ * MUST call `release()` when the URL goes off screen. Returns null when the
214
+ * file does not exist, or when object URLs are unavailable (non-browser).
215
+ */
216
+ async url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null> {
217
+ if (!this.blobs) return null;
218
+ return this.blobs.acquireUrl({ bucket: this.bucketName, path }, options);
219
+ }
220
+
221
+ /** Exempt `path` from pressure eviction. Pinned bytes never expire. */
222
+ pin(path: string): void {
223
+ this.blobs?.setPinned({ bucket: this.bucketName, path }, true);
224
+ }
225
+
226
+ unpin(path: string): void {
227
+ this.blobs?.setPinned({ bucket: this.bucketName, path }, false);
228
+ }
229
+
230
+ /** Drop `path` from the local cache without touching the remote file. */
231
+ async evict(path: string): Promise<void> {
232
+ await this.blobs?.invalidate({ bucket: this.bucketName, path });
233
+ }
234
+
235
+ /** Warm the cache for offline use. Already-cached paths are skipped. */
236
+ async prefetch(paths: string[]): Promise<void> {
237
+ await this.blobs?.prefetch(paths.map((path) => ({ bucket: this.bucketName, path })));
238
+ }
239
+
240
+ async delete(path: string): Promise<void> {
241
+ await this.remote.query(`RETURN f"${this.bucketName}:/${path}".delete();`);
242
+ await this.blobs?.invalidate({ bucket: this.bucketName, path });
243
+ // Symmetry with put: an image's blurhash sidecar dies with it. Best-effort,
244
+ // the sidecar may simply not exist.
245
+ if (isImagePath(path)) {
246
+ const sidecar = blurhashSidecarPath(path);
247
+ try {
248
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sidecar}".delete();`);
249
+ await this.blobs?.invalidate({ bucket: this.bucketName, path: sidecar });
250
+ } catch {
251
+ // Nothing to clean up.
252
+ }
253
+ missingBlurhash.delete(`${this.bucketName}:${path}`);
254
+ }
255
+ }
256
+
257
+ async exists(path: string): Promise<boolean> {
258
+ const [result] = await this.remote.query<[boolean]>(
259
+ `RETURN f"${this.bucketName}:/${path}".exists();`
260
+ );
261
+ return result;
262
+ }
263
+
264
+ async head(path: string): Promise<Record<string, unknown>> {
265
+ const [result] = await this.remote.query<[Record<string, unknown>]>(
266
+ `RETURN f"${this.bucketName}:/${path}".head();`
267
+ );
268
+ return result;
269
+ }
270
+
271
+ async copy(sourcePath: string, targetPath: string): Promise<void> {
272
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".copy($target);`, {
273
+ target: targetPath,
274
+ });
275
+ }
276
+
277
+ async rename(sourcePath: string, targetPath: string): Promise<void> {
278
+ await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".rename($target);`, {
279
+ target: targetPath,
280
+ });
281
+ }
282
+
283
+ async list(prefix?: string): Promise<string[]> {
284
+ const p = prefix ?? '';
285
+ const [result] = await this.remote.query<[string[]]>(
286
+ `RETURN f"${this.bucketName}:/${p}".list();`
287
+ );
288
+ return result;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Boot hint for which local bucket to open before auth resolves. Written to
294
+ * PLAIN localStorage (never the configured persistenceClient): the surrealdb
295
+ * persistence client stores its keys INSIDE a bucket, and the whole point of
296
+ * the hint is to pick the bucket before any bucket is open. A warm reload of a
297
+ * signed-in user thus opens their own bucket immediately — zero switches.
298
+ * Losing the hint is fail-closed: boot lands on the anon bucket and the auth
299
+ * callback switches to the user's bucket (cache + outbox intact).
300
+ */
301
+ const LAST_BUCKET_KEY = 'sp00ky:last_bucket';
302
+
303
+ /** Reported for engines that don't track local-store durability. Frozen so a
304
+ * subscriber can't mutate the shared snapshot. */
305
+ const UNKNOWN_STORAGE_HEALTH: StorageHealth = Object.freeze({
306
+ status: 'unknown',
307
+ fallback: false,
308
+ });
309
+
310
+ function readBootBucketHint(): string | null {
311
+ try {
312
+ return typeof localStorage !== 'undefined' ? localStorage.getItem(LAST_BUCKET_KEY) : null;
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+
318
+ function writeBootBucketHint(bucketId: string): void {
319
+ try {
320
+ if (typeof localStorage !== 'undefined') localStorage.setItem(LAST_BUCKET_KEY, bucketId);
321
+ } catch {
322
+ /* private-mode storage errors: boot just falls back to the anon bucket */
323
+ }
324
+ }
325
+
326
+ export class Sp00kyClient<S extends SchemaStructure> {
327
+ private local: LocalStore;
328
+ private remote: RemoteDatabaseService;
329
+ private blobs: BlobCache;
330
+ private connectionSupervisor: ConnectionSupervisor;
331
+ private persistenceClient: PersistenceClient;
332
+
333
+ private migrator: LocalMigrator;
334
+ private cache: CacheModule;
335
+ private dataModule: DataModule<S>;
336
+ private sync: Sp00kySync<S>;
337
+ private devTools: DevToolsService;
338
+ private crdtManager: CrdtManager;
339
+ /**
340
+ * True once the LOCAL half of boot is done and the client can serve reads
341
+ * from the local store. Distinct from being connected: `syncHealth` covers
342
+ * reaching the server and `storageHealth` covers whether the local store is
343
+ * durable, but neither says "usable". Consumers gate their first paint on
344
+ * this, which is what makes a warm boot instant and an offline boot possible.
345
+ */
346
+ private localReady = false;
347
+ // Principal the current query-id salt was minted for (`null` = signed out).
348
+ // Rotated only on a real auth flip: see the call sites in `init`.
349
+ private saltUserId: string | null = null;
350
+ private featureFlags!: FeatureFlagModule<S>;
351
+ private appReleases!: AppReleaseModule<S>;
352
+ // Query hashes already preloaded this session — skip redundant one-shot
353
+ // fetches when the same preload query is requested again (e.g. a list row
354
+ // re-rendering). Cleared on process/session end only.
355
+ private preloadedHashes = new Set<number>();
356
+ // In-flight background init chains (instant-hydrate + register enqueue) keyed
357
+ // by registration hash. Concurrent mounts of the same query reuse the one
358
+ // chain instead of double-hydrating and double-enqueuing `register`.
359
+ // Sequential re-mounts intentionally start a fresh chain — the unconditional
360
+ // `register` re-enqueue is what freshens a warm preload on use.
361
+ private pendingQueryInits = new Map<string, Promise<void>>();
362
+
363
+ private logger: ReturnType<typeof createLogger>;
364
+ public auth: AuthService<S>;
365
+ public streamProcessor: StreamProcessorService;
366
+
367
+ // Shared-tabs: non-null when the capability gate passed at construction.
368
+ // The coordinator owns role state; `sharedActive` flips false if the broker
369
+ // rejects/times out and this tab permanently falls back to solo.
370
+ private tabsCoordinator: TabsCoordinator | null = null;
371
+ private sharedActive = false;
372
+
373
+ /** Current shared-tabs role, or null when the feature is off/fell back. */
374
+ get tabRole(): TabRole | null {
375
+ return this.sharedActive ? this.tabsCoordinator!.role : null;
376
+ }
377
+
378
+ get remoteClient() {
379
+ return this.remote.getClient();
380
+ }
381
+
382
+ get localClient() {
383
+ return this.local.getClient();
384
+ }
385
+
386
+ get pendingMutationCount(): number {
387
+ return this.sync.pendingMutationCount;
388
+ }
389
+
390
+ /** Number of times the initial list_ref LIVE subscription retried on
391
+ * the most recent `setCurrentUserId` call. 0 when the SSP's
392
+ * pre-emptive user-table creation got there first; >0 when LIVE
393
+ * registration hit a "table not found" race. Exposed so the e2e
394
+ * suite can guard the pre-emptive path against regression. */
395
+ get liveRetryCount(): number {
396
+ return this.sync.liveRetryCount;
397
+ }
398
+
399
+ subscribeToPendingMutations(cb: (count: number) => void): () => void {
400
+ return this.sync.subscribeToPendingMutations(cb);
401
+ }
402
+
403
+ /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
404
+ get syncHealth(): SyncHealth {
405
+ return this.sync.syncHealth;
406
+ }
407
+
408
+ /**
409
+ * Observe sync health. Fires immediately with the current status and again
410
+ * on every healthy↔degraded transition. Returns an unsubscribe.
411
+ */
412
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void {
413
+ return this.sync.subscribeToSyncHealth(cb);
414
+ }
415
+
416
+ /** Durability of the local cache. See {@link StorageHealth}. `'unknown'` for
417
+ * engines that don't report it. */
418
+ get storageHealth(): StorageHealth {
419
+ return this.local.storageHealth ?? UNKNOWN_STORAGE_HEALTH;
420
+ }
421
+
422
+ /**
423
+ * Observe local-store durability. Fires immediately with the current snapshot
424
+ * and again on every change (at most once per bucket open in practice).
425
+ * Returns an unsubscribe.
426
+ */
427
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void {
428
+ if (this.local.subscribeToStorageHealth) {
429
+ return this.local.subscribeToStorageHealth(cb);
430
+ }
431
+ cb(UNKNOWN_STORAGE_HEALTH);
432
+ return () => {};
433
+ }
434
+
435
+ constructor(private config: Sp00kyConfig<S>) {
436
+ const logger = createLogger(config.logLevel ?? 'info', config.otelTransmit);
437
+ this.logger = logger.child({ service: 'Sp00kyClient' });
438
+
439
+ this.logger.info(
440
+ {
441
+ config: { ...config, schema: '[SchemaStructure]' },
442
+ Category: 'sp00ky-client::Sp00kyClient::constructor',
443
+ },
444
+ 'Sp00kyClient initialized'
445
+ );
446
+
447
+ // Preload the loro CRDT engine at startup (fetches the chunk on page load)
448
+ // so the first `openCrdtField` doesn't block on a network round-trip. Left
449
+ // off, loro is never loaded unless a CRDT field is explicitly opened.
450
+ if (config.crdt) void preloadLoro();
451
+
452
+ // The default ('surrealdb') engine is a SurrealCacheEngine — a drop-in
453
+ // subclass of LocalDatabaseService that adds the engine-neutral verb surface
454
+ // with zero behavior change. Alternate engines (e.g. 'sqlite') require the
455
+ // raw-SurrealQL call-site migration before they can back `this.local`.
456
+ const tabsSupport = detectSharedTabsSupport(this.config);
457
+ this.local = createLocalEngine(this.config.localEngine, this.config.database, logger, {
458
+ shared: tabsSupport.supported,
459
+ });
460
+ this.remote = new RemoteDatabaseService(this.config.database, logger);
461
+ // Owns socket liveness for the life of the client: re-opens the connection
462
+ // when the SDK's own reconnect gives up, and heartbeats to catch a socket
463
+ // that died without ever firing a `close` event.
464
+ this.connectionSupervisor = new ConnectionSupervisor(this.remote, logger);
465
+
466
+ // Durable cache for bucket file bytes. Reads go through a raw (uncached)
467
+ // handle so the cache's own L2 fetch can't recurse back into itself. The
468
+ // namespace is provisional: `init()` rebinds it to the boot bucket and
469
+ // reconciles against what is actually on disk.
470
+ this.blobs = createBlobCache({
471
+ local: this.local,
472
+ namespace: ANON_USER_ID,
473
+ logger,
474
+ fetchRemote: async (key) =>
475
+ bucketContentToBlob(await this.rawBucket(key.bucket).get(key.path)),
476
+ headRemote: (key) => this.rawBucket(key.bucket).head(key.path),
477
+ maxBytes: this.config.blobCache?.maxBytes,
478
+ // Opting out keeps the in-tab dedupe and object-URL refcounting that
479
+ // existed before this cache, and persists nothing.
480
+ store:
481
+ this.config.blobCache?.enabled === false ? new MemoryBlobStore(ANON_USER_ID) : undefined,
482
+ });
483
+
484
+ if (config.persistenceClient === 'surrealdb') {
485
+ this.persistenceClient = new SurrealDBPersistenceClient(this.local, logger);
486
+ } else if (config.persistenceClient === 'localstorage' || !config.persistenceClient) {
487
+ this.persistenceClient = new LocalStoragePersistenceClient(logger);
488
+ } else {
489
+ this.persistenceClient = config.persistenceClient;
490
+ }
491
+
492
+ this.persistenceClient = new ResilientPersistenceClient(this.persistenceClient, logger);
493
+
494
+ this.streamProcessor = new StreamProcessorService(
495
+ new EventSystem(['stream_update']),
496
+ this.local,
497
+ logger
498
+ );
499
+ // Circuit snapshots are checkpointed, never per-ingest, and on by default
500
+ // where the store can hold them (the OPFS SQLite engine). See
501
+ // `persistCircuit` / `circuitProjection` in types.ts.
502
+ this.streamProcessor.configureCircuitPersistence(
503
+ config.persistCircuit ?? config.localEngine === 'sqlite',
504
+ config.circuitCheckpointMs
505
+ );
506
+ this.streamProcessor.configureProjection(config.circuitProjection ?? true);
507
+ this.migrator = new LocalMigrator(this.local, logger);
508
+
509
+ this.cache = new CacheModule(
510
+ this.local,
511
+ this.streamProcessor,
512
+ (update) => {
513
+ // Direct callback from cache to data module
514
+ this.dataModule.onStreamUpdate(update);
515
+ },
516
+ logger
517
+ );
518
+
519
+ // Initialize CRDT Manager. `local` is used to read the initial
520
+ // `_00_crdt` snapshot when a field opens AND to mirror every local
521
+ // edit (so reload/offline see the freshest state); `remote` is used
522
+ // for the debounced outgoing UPSERTs and the parent-table LIVE feed.
523
+ // The debounce window is configurable via `crdtDebounceMs`.
524
+ this.crdtManager = new CrdtManager(
525
+ this.config.schema,
526
+ this.local,
527
+ this.remote,
528
+ logger,
529
+ config.crdtDebounceMs ?? 500
530
+ );
531
+
532
+ this.dataModule = new DataModule(
533
+ this.cache,
534
+ this.local,
535
+ this.config.schema,
536
+ logger,
537
+ this.config.streamDebounceTime
538
+ );
539
+
540
+ // Initialize Auth
541
+ this.auth = new AuthService(this.config.schema, this.remote, this.persistenceClient, logger);
542
+
543
+ // Initialize Sync
544
+ this.sync = new Sp00kySync(
545
+ this.local,
546
+ this.remote,
547
+ this.cache,
548
+ this.dataModule,
549
+ this.config.schema,
550
+ this.logger,
551
+ {
552
+ refSyncIntervalMs: this.config.refSyncIntervalMs,
553
+ anonymousLiveQueries: this.config.enableAnonymousLiveQueries,
554
+ // `syncHealth: false` (or `{ degradeAfterConsecutiveFailures: 0 }`)
555
+ // disables degraded reporting; otherwise default to 3.
556
+ degradeAfterConsecutiveFailures:
557
+ this.config.syncHealth === false
558
+ ? 0
559
+ : (this.config.syncHealth?.degradeAfterConsecutiveFailures ?? 3),
560
+ pushTimeoutMs: this.config.pushTimeoutMs,
561
+ downTimeoutMs: this.config.downTimeoutMs,
562
+ // Read-only: sync mirrors the transport state into `SyncHealth`.
563
+ connectionSupervisor: this.connectionSupervisor,
564
+ }
565
+ );
566
+ this.sync.setPrimeGate(() => this.streamProcessor.whenPrimed());
567
+
568
+ // Initialize feature flags. Reuses the down-queue to register SSP plans
569
+ // on `_00_user_feature` and the auth subscription to re-register handles
570
+ // when the signed-in user changes.
571
+ this.featureFlags = new FeatureFlagModule({
572
+ dataModule: this.dataModule,
573
+ sync: this.sync,
574
+ auth: this.auth,
575
+ logger,
576
+ });
577
+
578
+ // App release announcements (world-readable `_00_app_release`, written by
579
+ // spky deploy/release). Same shared-live-query design as feature flags.
580
+ this.appReleases = new AppReleaseModule({
581
+ dataModule: this.dataModule,
582
+ sync: this.sync,
583
+ auth: this.auth,
584
+ logger,
585
+ });
586
+
587
+ // Initialize DevTools
588
+ this.devTools = new DevToolsService(
589
+ this.local,
590
+ this.remote,
591
+ logger,
592
+ this.config.schema,
593
+ this.auth,
594
+ this.dataModule
595
+ );
596
+
597
+ // Let the DevTools Access tab read and write local flag overrides. Done
598
+ // here rather than via the constructor because FeatureFlagModule is built
599
+ // above and DevToolsService takes its deps positionally.
600
+ this.devTools.setFeatureFlagOverrides(this.featureFlags);
601
+
602
+ // Register DevTools as a receiver for stream updates
603
+ this.streamProcessor.addReceiver(this.devTools);
604
+
605
+ // Wire up callbacks instead of events
606
+ this.setupCallbacks();
607
+
608
+ // Shared-tabs: construct the coordinator last so its hooks can close over
609
+ // every module. Nothing starts until init() calls coordinator.start().
610
+ if (tabsSupport.supported) {
611
+ this.tabsCoordinator = this.buildTabsCoordinator();
612
+ } else if (this.config.sharedTabs) {
613
+ this.logger.info(
614
+ {
615
+ reason: (tabsSupport as { reason: string }).reason,
616
+ Category: 'sp00ky-client::Sp00kyClient::tabs',
617
+ },
618
+ 'sharedTabs requested but unsupported here; running solo'
619
+ );
620
+ }
621
+ // Report shared-tabs state whenever the feature was REQUESTED, active or
622
+ // not: "asked to share one store, running alone because X" is exactly the
623
+ // thing you need to see in the panel. Apps that never set the flag report
624
+ // null and the panel shows no section at all.
625
+ if (this.config.sharedTabs) {
626
+ const unsupportedReason = tabsSupport.supported
627
+ ? undefined
628
+ : (tabsSupport as { reason: string }).reason;
629
+ this.devTools.setTabsInfoProvider(() => {
630
+ const c = this.tabsCoordinator;
631
+ if (!this.sharedActive || !c) {
632
+ return { active: false, reason: unsupportedReason ?? 'fell-back' };
633
+ }
634
+ const hub = c.syncHub;
635
+ return {
636
+ active: true,
637
+ role: c.role,
638
+ tabId: c.tabId,
639
+ leadershipId: c.leadershipId,
640
+ leaderTabId: c.role === 'leader' ? c.tabId : c.leaderTabId,
641
+ ...(hub ? { followers: hub.followerCount, relayedBatches: hub.relayedBatches } : {}),
642
+ };
643
+ });
644
+ }
645
+ this.devTools.setBlobInfoProvider(() => this.blobs.stats());
646
+ }
647
+
648
+ /** The shared-tabs role machinery, wired to this client's modules. */
649
+ private buildTabsCoordinator(): TabsCoordinator {
650
+ const engine = this.local as SqliteCacheEngine;
651
+ const tabId =
652
+ typeof crypto !== 'undefined' && crypto.randomUUID
653
+ ? crypto.randomUUID()
654
+ : `tab_${Math.random().toString(36).slice(2)}`;
655
+ const hooks: CoordinatorHooks = {
656
+ adoptOwner: (bucketId, opts) =>
657
+ engine.adoptOwner(bucketId, {
658
+ workerLockName: opts.workerLockName,
659
+ allowMemoryFallback: opts.allowMemoryFallback,
660
+ resumeHeld: opts.resumeHeld,
661
+ }),
662
+ adoptAttached: (dbPort, snapshot) =>
663
+ engine.adoptAttached(dbPort, snapshot, (reason) => engine.onLeaderLost(reason)),
664
+ releaseOwnership: () => engine.releaseOwnership(),
665
+ onLeaderLost: (reason) => engine.onLeaderLost(reason),
666
+ exposeClientPort: (clientId, port) => engine.exposeClientPort(clientId, port),
667
+ removeClientPort: (clientId) => engine.removeClientPort(clientId),
668
+ becomeSyncLeader: (hub) => {
669
+ this.streamProcessor.setPersistenceEnabled(true);
670
+ this.cache.setIngestRelay((tuples) => hub.relayIngest(tuples));
671
+ this.sync.setTabContext('leader', tabId);
672
+ this.dataModule.setTabId(tabId);
673
+ this.sync.promoteToLeader(hub);
674
+ },
675
+ resumeSyncLeaderDuties: () => this.sync.resumeLeaderDuties(),
676
+ becomeSyncFollower: (forwarder) => {
677
+ this.streamProcessor.setPersistenceEnabled(false);
678
+ // A follower's own mutations go to the leader, which ingests them and
679
+ // fans them out to the other followers: one hop, no server round-trip.
680
+ // Only the mutation path relays; this tab's sync fetches are the
681
+ // leader's data coming back and must not be re-broadcast.
682
+ this.cache.setIngestRelay((tuples) => forwarder.ingest(tuples), {
683
+ localWritesOnly: true,
684
+ });
685
+ this.sync.setTabContext('follower', tabId);
686
+ this.dataModule.setTabId(tabId);
687
+ // Installs the whole syncPort handler: ingest-relay, list_ref relay,
688
+ // settled writes, rollbacks.
689
+ this.sync.demoteToFollower(forwarder);
690
+ },
691
+ becomeSyncSolo: () => {
692
+ this.streamProcessor.setPersistenceEnabled(true);
693
+ this.cache.setIngestRelay(null);
694
+ this.sync.setTabContext('solo', tabId);
695
+ },
696
+ currentStorageHealth: () =>
697
+ this.local.storageHealth ?? { status: 'unknown', fallback: false },
698
+ };
699
+ return new TabsCoordinator({
700
+ tabId,
701
+ fingerprint: computeTabsFingerprint({
702
+ coreVersion:
703
+ typeof __SP00KY_CORE_VERSION__ !== 'undefined' ? __SP00KY_CORE_VERSION__ : 'unknown',
704
+ schemaHash: hash53(this.config.schemaSurql),
705
+ endpoint: this.config.database.endpoint ?? '',
706
+ namespace: this.config.database.namespace,
707
+ database: this.config.database.database,
708
+ }),
709
+ hooks,
710
+ logger: this.logger,
711
+ onLeaderPageHide: () => {
712
+ void engine.shutdownOwnedWorker();
713
+ },
714
+ });
715
+ }
716
+
717
+ /**
718
+ * Setup direct callbacks instead of event subscriptions
719
+ */
720
+ private setupCallbacks() {
721
+ // Surface query fetch-status changes (idle/fetching) in DevTools. Logs a
722
+ // discrete event and triggers a state push so the active-queries panel
723
+ // reflects the flip immediately.
724
+ this.dataModule.onQueryStatusChange = (queryHash, status) => {
725
+ this.devTools.logEvent('QUERY_STATUS_CHANGED', { queryHash, status });
726
+ };
727
+
728
+ // Keep an actively-watched query's remote `_00_query.lastActiveAt` fresh so
729
+ // the server TTL sweep doesn't expire it out from under live subscribers.
730
+ // DataModule fires this only while the query still has ≥1 subscriber.
731
+ this.dataModule.onHeartbeat = (queryHash) => {
732
+ void this.sync.heartbeatQuery(queryHash).catch((err) => {
733
+ this.logger.warn(
734
+ { err, queryHash, Category: 'sp00ky-client::Sp00kyClient::onHeartbeat' },
735
+ 'TTL heartbeat failed'
736
+ );
737
+ });
738
+ };
739
+
740
+ // Eager teardown of an opt-in deregistered query: enqueue a `cleanup`
741
+ // down-event so it's serialized after any in-flight register/sync for the
742
+ // same query (avoids out-of-order delete-before-create).
743
+ this.dataModule.onDeregister = (queryHash) => {
744
+ this.sync.enqueueDownEvent({ type: 'cleanup', payload: { hash: queryHash } });
745
+ };
746
+
747
+ // Mutation callback for sync
748
+ this.dataModule.onMutation((mutations: UpEvent[]) => {
749
+ // Notify DevTools
750
+ this.devTools.onMutation(mutations);
751
+
752
+ // Enqueue in Sync
753
+ if (mutations.length > 0) {
754
+ this.sync.enqueueMutation(mutations);
755
+ }
756
+ });
757
+
758
+ // Sync events for incoming updates
759
+ this.sync.events.subscribe('SYNC_QUERY_UPDATED', (event: any) => {
760
+ this.devTools.logEvent('SYNC_QUERY_UPDATED', event.payload);
761
+ });
762
+
763
+ // Hand list_ref-driven row ingests to the CrdtManager so CRDT body
764
+ // / cursor updates reach the receiver even when the cross-session
765
+ // LIVE on the parent table is filtered out by the SurrealDB
766
+ // permission-LIVE gap. Same-user clients receive these rows via
767
+ // CrdtManager's own `LIVE SELECT * FROM <table>`; this hook is the
768
+ // redundant path that fires when only the list_ref bumped.
769
+ this.sync.engineEvents.subscribe('SYNC_REMOTE_DATA_INGESTED', (event: any) => {
770
+ try {
771
+ const records: Array<Record<string, any>> = event.payload?.records ?? [];
772
+ for (const row of records) {
773
+ const id = row?.id;
774
+ const table =
775
+ id && typeof id === 'object' && id.table !== undefined ? String(id.table) : undefined;
776
+ if (!table) continue;
777
+ this.crdtManager.applyRow(table, row);
778
+ }
779
+ } catch (err) {
780
+ this.logger.debug(
781
+ { err, Category: 'sp00ky-client::engineEvents::ingested' },
782
+ 'applyRow forwarding from sync ingest failed'
783
+ );
784
+ }
785
+ });
786
+
787
+ // Database events for DevTools
788
+ this.local.getEvents().subscribe('DATABASE_LOCAL_QUERY', (event: any) => {
789
+ this.devTools.logEvent('LOCAL_QUERY', event.payload);
790
+ });
791
+
792
+ this.remote.getEvents().subscribe('DATABASE_REMOTE_QUERY', (event: any) => {
793
+ this.devTools.logEvent('REMOTE_QUERY', event.payload);
794
+ });
795
+ }
796
+
797
+ async init() {
798
+ this.logger.info(
799
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
800
+ 'Sp00kyClient initialization started'
801
+ );
802
+ try {
803
+ // Open the bucket the last session used (per-user local stores). If auth
804
+ // resolves to a different user below, the auth callback switches buckets.
805
+ const bootBucket = readBootBucketHint() ?? ANON_USER_ID;
806
+ if (this.tabsCoordinator) {
807
+ // Shared-tabs: the broker assigns this tab's role; the coordinator's
808
+ // hooks open the store (leader) or attach to the leader's (follower).
809
+ // Any failure here (no SharedWorker start, election timeout, rejected
810
+ // fingerprint) falls back to plain solo boot: exactly the flag-off
811
+ // path, including the second-tab memory fallback + its warning.
812
+ // A role can still land AFTER start() gave up (the election that timed
813
+ // out here keeps running), and when it does this tab really is sharing
814
+ // the leader's store. Track every transition so the reported state is
815
+ // the current one instead of frozen at whatever boot saw.
816
+ this.tabsCoordinator.onRoleChange((role) => {
817
+ this.sharedActive = role !== 'solo';
818
+ // Surface the transition in DevTools. Reconstructing a failover from
819
+ // the `database.tabs` snapshot alone is guesswork after the fact; a
820
+ // discrete event gives `get_events` the leader handover directly.
821
+ this.devTools.logEvent('TABS_ROLE_CHANGED', {
822
+ role,
823
+ tabId: this.tabsCoordinator?.tabId,
824
+ leadershipId: this.tabsCoordinator?.leadershipId,
825
+ leaderTabId: this.tabsCoordinator?.leaderTabId,
826
+ promotionMs: this.tabsCoordinator?.lastPromotionMs,
827
+ });
828
+ });
829
+ try {
830
+ const role = await this.tabsCoordinator.start(bootBucket);
831
+ this.sharedActive = true;
832
+ this.logger.info(
833
+ { role, bootBucket, Category: 'sp00ky-client::Sp00kyClient::init' },
834
+ 'Shared-tabs role assigned'
835
+ );
836
+ } catch (e) {
837
+ this.logger.warn(
838
+ { err: e, Category: 'sp00ky-client::Sp00kyClient::init' },
839
+ 'Shared-tabs unavailable; booting solo'
840
+ );
841
+ this.sharedActive = false;
842
+ await this.local.connect(bootBucket);
843
+ }
844
+ } else {
845
+ await this.local.connect(bootBucket);
846
+ }
847
+ this.logger.debug(
848
+ { bootBucket, Category: 'sp00ky-client::Sp00kyClient::init' },
849
+ 'Local database connected'
850
+ );
851
+
852
+ // Schemaless local engines (SQLite) create tables lazily and need no
853
+ // SurrealQL DDL provisioning.
854
+ if (this.local.usesSurqlSchema) {
855
+ await this.migrator.provision(this.config.schemaSurql);
856
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Schema provisioned');
857
+ }
858
+
859
+ // Warm the blob cache in the background. Deliberately NOT awaited, and
860
+ // deliberately after `remote.connect()`: this walks the OPFS directory to
861
+ // rebuild the manifest, and awaiting it ahead of the socket delayed the
862
+ // connect (and the connection supervisor with it) for no benefit. Reads
863
+ // await `BlobCache.ready` internally, so a bucket read that lands mid-walk
864
+ // still sees a reconciled manifest. Best-effort: a cold blob cache is a
865
+ // slow first image, not a broken client.
866
+ void (async () => {
867
+ try {
868
+ this.blobs.setMaxBytes(await resolveBlobBudget(this.config.blobCache?.maxBytes));
869
+ await this.blobs.start(bootBucket);
870
+ } catch (e) {
871
+ this.logger.warn(
872
+ { err: e, Category: 'sp00ky-client::Sp00kyClient::init' },
873
+ 'Blob cache failed to start; bucket files will not be cached locally'
874
+ );
875
+ }
876
+ })();
877
+
878
+ await this.streamProcessor.init();
879
+ // Seed table `select` permissions from the schema before any query is
880
+ // registered — otherwise the SSP default-denies every non-`_00_` table.
881
+ this.streamProcessor.setPermissions(extractSelectPermissions(this.config.schemaSurql));
882
+ // Fill the circuit from the local store in the background (snapshot +
883
+ // reconcile, or every cached row). Not awaited: first paint reads the
884
+ // store directly; sync waits on `whenPrimed` before its first diff.
885
+ void this.primeCircuit();
886
+ this.logger.debug(
887
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
888
+ 'StreamProcessor initialized'
889
+ );
890
+
891
+
892
+ // Restore the session from the cached JWT, with no network. This is what
893
+ // lets the rest of the boot - and the app on top of it - proceed as a
894
+ // signed-in user before a socket exists. `initRemote()` verifies the
895
+ // token afterwards and signs out for real if the server rejects it.
896
+ const restoredUserId = await this.auth.restoreSessionFromToken();
897
+
898
+ // Salt for query-id hashing, minted locally (see `mintSessionSalt`). It
899
+ // is stable for the life of this client: the salt keys `_00_query` rows
900
+ // and local cache entries, so rotating it would invalidate every query
901
+ // hash and force a full re-register. Auth flips are the one case that
902
+ // must rotate it - a sign-in is a different principal.
903
+ const sessionId = this.mintSessionSalt();
904
+ this.saltUserId = restoredUserId;
905
+ await this.dataModule.init(sessionId);
906
+ this.crdtManager.setSessionId(sessionId);
907
+
908
+ // Route queries and satisfy `$auth`-gated permission predicates from the
909
+ // restored identity, BEFORE anything can register. Without this a query
910
+ // registering pre-verification would target the wrong
911
+ // `_00_query_user_<id>` table and register a permission-dead SSP view.
912
+ if (restoredUserId) {
913
+ this.dataModule.setCurrentUserId(restoredUserId);
914
+ this.streamProcessor.setSessionAuth(this.sessionAuthId(), this.auth.access);
915
+ }
916
+ this.logger.debug(
917
+ { sessionId, Category: 'sp00ky-client::Sp00kyClient::init' },
918
+ 'DataModule initialized'
919
+ );
920
+
921
+ // Refresh the salt whenever auth state flips (sign-in, sign-out).
922
+ // session::id() changes per WebSocket session, and a sign-in spawns
923
+ // a new authenticated session, so the salt must follow. Also
924
+ // forward the user id into `DataModule` and `Sp00kySync` so they
925
+ // can route to per-user `_00_query_user_<id>` /
926
+ // `_00_list_ref_user_<id>` tables in `RefMode.Dedicated` — the
927
+ // LIVE subscription on `_00_list_ref_user_<id>` is restarted
928
+ // under the new auth context inside `Sp00kySync.setCurrentUserId`
929
+ // since SurrealDB binds the LIVE permission at registration time.
930
+ //
931
+ // Sync prefix BEFORE the first `await`: setting `currentUserId`
932
+ // synchronously here is critical because the AuthProvider's own
933
+ // subscribe callback runs right after ours and immediately enables
934
+ // queries that depend on the user id. Any `await` before
935
+ // `setCurrentUserId` would let those queries register against the
936
+ // stale (null) user id and hit the wrong `_00_query[_user_*]`
937
+ // table.
938
+ this.auth.subscribe(async (userId) => {
939
+ this.dataModule.setCurrentUserId(userId);
940
+ // Mirror the server's `fn::query::register` auth injection for the
941
+ // in-browser SSP: feed the current user's full record id + access
942
+ // method so `$auth`-gated table permissions (e.g. `thread`) resolve
943
+ // locally instead of being rejected. Set synchronously BEFORE the
944
+ // first `await` (like `setCurrentUserId` above) so queries that
945
+ // re-register on this auth flip see the fresh context, not a stale one.
946
+ this.streamProcessor.setSessionAuth(this.sessionAuthId(), this.auth.access);
947
+ // Record the target bucket synchronously (still before the first
948
+ // `await`) so a reload mid-switch boots straight into the right store.
949
+ writeBootBucketHint(bucketIdForUser(userId));
950
+ // FIRST await: swap the local store to this user's bucket. Serialized
951
+ // + latest-target-wins internally; no-op when the bucket already
952
+ // matches (the boot-hint warm path).
953
+ await this.ensureLocalBucket(userId);
954
+ // Only rotate the salt when the PRINCIPAL actually changed: a sign-in or
955
+ // sign-out is a different principal and must not keep the old
956
+ // principal's query ids, but the first fire of this callback after boot
957
+ // carries the same user the salt was already minted for, and rotating
958
+ // there would invalidate every query hash for no change in value.
959
+ // Canonicalize with the SAME encoding the restore path used, NOT
960
+ // String(): after background verification this callback carries a
961
+ // RecordId, while a session restored from the token carries the plain
962
+ // "table:id" string. Comparing their raw stringifications made every
963
+ // warm boot look like a principal change, which rotated the salt and
964
+ // re-registered every mounted query - the list painted from cache and
965
+ // then emptied a second later.
966
+ const saltFor = this.sessionAuthId();
967
+ if (saltFor !== this.saltUserId) {
968
+ this.saltUserId = saltFor;
969
+ const next = this.mintSessionSalt();
970
+ this.dataModule.setSessionId(next);
971
+ this.crdtManager.setSessionId(next);
972
+ }
973
+ try {
974
+ await this.sync.setCurrentUserId(userId);
975
+ } catch (e) {
976
+ this.logger.error(
977
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::authChange' },
978
+ 'sync.setCurrentUserId failed'
979
+ );
980
+ }
981
+ // After the bucket switch, so the row lands in THIS user's store.
982
+ await this.persistVerifiedUser();
983
+ });
984
+
985
+ await this.sync.init();
986
+ this.logger.debug({ Category: 'sp00ky-client::Sp00kyClient::init' }, 'Sync initialized');
987
+
988
+ // Hand this tab's views back when the page goes away. Without it they
989
+ // stay materialized on the SSP for a whole TTL after the tab is gone —
990
+ // see `Sp00kySync.releaseViewsOnUnload`.
991
+ //
992
+ // `pagehide` rather than `beforeunload`: it is the one teardown event
993
+ // that also fires on mobile, where tabs are discarded rather than
994
+ // closed. `persisted` means the page went into the bfcache and can come
995
+ // BACK, so releasing there would tear down views a live page still
996
+ // needs.
997
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
998
+ const onPageHide = (event: PageTransitionEvent) => {
999
+ if (event.persisted) return;
1000
+ this.sync.releaseViewsOnUnload();
1001
+ };
1002
+ window.addEventListener('pagehide', onPageHide);
1003
+ this.detachUnloadRelease = () => window.removeEventListener('pagehide', onPageHide);
1004
+ }
1005
+
1006
+ this.featureFlags.init();
1007
+ this.logger.debug(
1008
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
1009
+ 'FeatureFlagModule initialized'
1010
+ );
1011
+
1012
+ this.appReleases.init();
1013
+ this.logger.debug(
1014
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
1015
+ 'AppReleaseModule initialized'
1016
+ );
1017
+
1018
+ // LOCAL BOOT IS DONE — the client can serve reads. Consumers gate their
1019
+ // UI on this resolving, so everything above must stay network-free.
1020
+ this.localReady = true;
1021
+ this.logger.info(
1022
+ { Category: 'sp00ky-client::Sp00kyClient::init' },
1023
+ 'Sp00kyClient local initialization completed; connecting in the background'
1024
+ );
1025
+
1026
+ // The network half, deliberately NOT awaited. Nothing above needed it:
1027
+ // queries paint from the local store, `sync.init()` tolerates a closed
1028
+ // socket, and the session was restored from the cached token. Awaiting
1029
+ // this was the entire reason a warm reload sat on a loading screen for
1030
+ // seconds over data the browser already had on disk - and the reason an
1031
+ // offline boot never completed at all.
1032
+ void this.initRemote();
1033
+ } catch (e) {
1034
+ this.logger.error(
1035
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::init' },
1036
+ 'Sp00kyClient initialization failed'
1037
+ );
1038
+ throw e;
1039
+ }
1040
+ }
1041
+
1042
+ /**
1043
+ * The network half of boot: connect, verify the restored session, and let the
1044
+ * sync engine catch up. Runs in the background after `init()` has already
1045
+ * resolved, so nothing here is on the paint path.
1046
+ *
1047
+ * Every step is best-effort. A failure leaves the client in exactly the state
1048
+ * a warm offline boot is in - local reads working, writes queued in the
1049
+ * outbox - and the connection supervisor keeps retrying underneath.
1050
+ */
1051
+ private async initRemote(): Promise<void> {
1052
+ try {
1053
+ await this.remote.connect();
1054
+ this.logger.debug(
1055
+ { Category: 'sp00ky-client::Sp00kyClient::initRemote' },
1056
+ 'Remote database connected'
1057
+ );
1058
+ } catch (e) {
1059
+ // NOT fatal. This used to throw out of init() and leave the consuming app
1060
+ // on its loading screen forever with no network. The supervisor (started
1061
+ // unconditionally below) owns the retry from here.
1062
+ this.logger.warn(
1063
+ { err: e, Category: 'sp00ky-client::Sp00kyClient::initRemote' },
1064
+ 'Remote connect failed; running from the local store and retrying in the background'
1065
+ );
1066
+ }
1067
+
1068
+ // Started whether or not the first connect succeeded - it is the thing that
1069
+ // revives the socket, so gating it on a successful connect would mean a
1070
+ // boot-time failure never recovered.
1071
+ this.connectionSupervisor.start();
1072
+
1073
+ try {
1074
+ // Verifies the optimistically restored token against the server. On a
1075
+ // rejected token this signs out for real; on an unreachable server it
1076
+ // keeps the cached session (see AuthService.check).
1077
+ await this.auth.init();
1078
+ this.logger.debug(
1079
+ { Category: 'sp00ky-client::Sp00kyClient::initRemote' },
1080
+ 'Auth verified'
1081
+ );
1082
+ } catch (e) {
1083
+ this.logger.warn(
1084
+ { err: e, Category: 'sp00ky-client::Sp00kyClient::initRemote' },
1085
+ 'Auth verification failed; keeping the restored session'
1086
+ );
1087
+ }
1088
+ }
1089
+
1090
+ /**
1091
+ * Write the signed-in user's own row, as the SERVER just returned it, into
1092
+ * the local store.
1093
+ *
1094
+ * `AuthService.check()` (boot verification, sign-in, an app-driven refresh)
1095
+ * runs `SELECT * FROM ONLY $auth.id` and keeps the answer on
1096
+ * `auth.currentUser`; nothing consumed it beyond the id. Meanwhile the app's
1097
+ * own `user` query paints local-first from whatever body the store holds,
1098
+ * and that body is only refreshed when the server's row version reaches
1099
+ * this client through membership (`_00_list_ref`). While the SSP is down or
1100
+ * bootstrapping that never happens, so a device that registered before the
1101
+ * account was verified kept rendering a row without `email_verified` and
1102
+ * the app parked the user on "Verify your email" over a server that said
1103
+ * "already verified". The authoritative row was already in hand.
1104
+ *
1105
+ * MERGE semantics (`CacheModule.saveBatch`) keep local-only fields, and
1106
+ * re-using the memoized version keeps the sync dedup honest: this is a
1107
+ * field refresh, not a version claim. `notifyTableQueries` re-materializes
1108
+ * the `user` queries so the gate flips without waiting for a stream update.
1109
+ * Best-effort: a failure here leaves things exactly as they were.
1110
+ */
1111
+ private async persistVerifiedUser(): Promise<void> {
1112
+ const row = this.auth.currentUser as Record<string, unknown> | null;
1113
+ if (!row || !(row.id instanceof RecordId) || Object.keys(row).length <= 1) return;
1114
+ const rid = row.id as RecordId;
1115
+ const table = rid.table.toString();
1116
+ const tableSchema = this.config.schema.tables.find((t) => t.name === table);
1117
+ if (!tableSchema) return;
1118
+ try {
1119
+ const encoded = encodeRecordId(rid);
1120
+ const version = this.cache.lookup(encoded) || 1;
1121
+ await this.cache.saveBatch([
1122
+ {
1123
+ table,
1124
+ op: 'UPDATE',
1125
+ record: cleanRecord(tableSchema.columns, row) as RecordWithId,
1126
+ version,
1127
+ },
1128
+ ]);
1129
+ await this.dataModule.notifyTableQueries(table);
1130
+ } catch (e) {
1131
+ this.logger.warn(
1132
+ { err: e, Category: 'sp00ky-client::Sp00kyClient::persistVerifiedUser' },
1133
+ 'Could not persist the verified user row locally'
1134
+ );
1135
+ }
1136
+ }
1137
+
1138
+ // Serializes bucket switches from rapid auth flips; `pendingBucketTarget`
1139
+ // makes intermediate targets collapse (A→anon→B never opens the anon bucket).
1140
+ private bucketSwitchChain: Promise<void> = Promise.resolve();
1141
+ private pendingBucketTarget: string | null = null;
1142
+
1143
+ /**
1144
+ * Ensure the local store is this user's bucket, switching if needed. Called
1145
+ * from the auth listener on every auth flip; concurrent calls are chained
1146
+ * and superseded intermediates are skipped (latest target wins).
1147
+ */
1148
+ private ensureLocalBucket(userId: string | null): Promise<void> {
1149
+ const target = bucketIdForUser(userId);
1150
+ this.pendingBucketTarget = target;
1151
+ // Close the query gate SYNCHRONOUSLY the instant a switch is pending — the
1152
+ // AuthProvider's own auth subscriber fires right after this (same tick) and
1153
+ // enables queries, and `doSwitchBucket` only runs a microtask later on the
1154
+ // chain. Without closing the gate here, that query is issued through the
1155
+ // still-open gate and is in-flight on the local wasm engine when
1156
+ // `switchStore` closes the client — which wedges the engine (every
1157
+ // subsequent query, including provisioning, hangs → no view ever registers).
1158
+ // No-op when already on the target bucket.
1159
+ const needsSwitch = this.local.currentBucketId !== target;
1160
+ const release = needsSwitch ? this.local.beginSwitch() : null;
1161
+ this.bucketSwitchChain = this.bucketSwitchChain.then(async () => {
1162
+ // Superseded by a newer flip, or already on target: reopen the gate we
1163
+ // closed above and skip the switch.
1164
+ if (this.pendingBucketTarget !== target || this.local.currentBucketId === target) {
1165
+ release?.();
1166
+ return;
1167
+ }
1168
+ await this.doSwitchBucket(target, release);
1169
+ });
1170
+ // Isolate chain failures per-caller: a failed switch must not poison every
1171
+ // future switch. The caller (auth listener) logs it. Reopen the gate on
1172
+ // failure so the client never gets stuck closed.
1173
+ const result = this.bucketSwitchChain;
1174
+ this.bucketSwitchChain = this.bucketSwitchChain.catch(() => {
1175
+ release?.();
1176
+ });
1177
+ return result;
1178
+ }
1179
+
1180
+ /**
1181
+ * The bucket-switch choreography: drain → swap → rebind.
1182
+ *
1183
+ * Drain: sync quiesced (poll/LIVE stopped, in-flight round awaited so its
1184
+ * outbox delete lands in the OLD bucket, debounce timers cancelled),
1185
+ * DataModule timers cleared, CRDT fields closed WITHOUT their final flush
1186
+ * (the remote session already belongs to the next user).
1187
+ *
1188
+ * Swap: gate closes so any local query issued mid-switch (sibling auth
1189
+ * subscribers, FeatureFlagModule) waits and then runs against the NEW
1190
+ * bucket; store swaps open-new-before-close-old; schema provisions
1191
+ * (no-op for a returning bucket); stale `_00_query` rows are wiped (dead
1192
+ * sessionId-salted hashes with stale arrays — record bodies stay warm);
1193
+ * SSP resets to a fresh circuit with re-seeded permissions.
1194
+ *
1195
+ * Rebind: auth token re-persisted (the surrealdb persistence client wrote it
1196
+ * into the OLD bucket's `_00_kv` before this listener ran), active queries
1197
+ * re-homed keeping their hashes, sync resumed on the new bucket's own
1198
+ * outbox, and every query re-registered remotely to refill from the server.
1199
+ */
1200
+ private async doSwitchBucket(target: string, gateRelease?: (() => void) | null): Promise<void> {
1201
+ this.logger.info(
1202
+ {
1203
+ target,
1204
+ from: this.local.currentBucketId,
1205
+ Category: 'sp00ky-client::Sp00kyClient::doSwitchBucket',
1206
+ },
1207
+ 'Switching local bucket'
1208
+ );
1209
+
1210
+ const leavingBucket = this.local.currentBucketId;
1211
+
1212
+ await this.sync.prepareBucketSwitch();
1213
+ this.dataModule.quiesce();
1214
+ this.crdtManager.closeAll({ flush: false });
1215
+
1216
+ // Reuse the gate the caller (`ensureLocalBucket`) closed synchronously; only
1217
+ // open our own if called without one (keeps the gate continuously closed
1218
+ // from the auth flip through the swap — no window for a racing query).
1219
+ const reopen = gateRelease ?? this.local.beginSwitch();
1220
+ try {
1221
+ if (this.sharedActive && this.tabsCoordinator) {
1222
+ // Shared-tabs: a bucket switch is a namespace move. Leaving the old
1223
+ // namespace re-elects it (if this tab led it); joining the new one
1224
+ // assigns a fresh role, whose hooks open or attach the store. The
1225
+ // leader wipe-on-pool-open replaces the DELETE _00_query below, and a
1226
+ // joining follower must NOT wipe: other tabs' rows there are live.
1227
+ try {
1228
+ await this.tabsCoordinator.moveToBucket(target);
1229
+ } catch (e) {
1230
+ this.logger.warn(
1231
+ { err: e, target, Category: 'sp00ky-client::Sp00kyClient::doSwitchBucket' },
1232
+ 'Shared-tabs bucket move failed; switching solo'
1233
+ );
1234
+ this.sharedActive = false;
1235
+ this.sync.setTabContext('solo', null);
1236
+ this.cache.setIngestRelay(null);
1237
+ this.streamProcessor.setPersistenceEnabled(true);
1238
+ await this.local.switchStore(target);
1239
+ await this.local.queryUngated('DELETE _00_query;');
1240
+ }
1241
+ } else {
1242
+ await this.local.switchStore(target);
1243
+ if (this.local.usesSurqlSchema) {
1244
+ await this.migrator.provision(this.config.schemaSurql);
1245
+ }
1246
+ await this.local.queryUngated('DELETE _00_query;');
1247
+ }
1248
+ // Cached bytes are namespaced per local bucket, so the switch is a
1249
+ // repoint, not a wipe: signing back in finds the cache warm. Apps that
1250
+ // want the signed-out user's files gone opt in with `clearOnSignOut`.
1251
+ try {
1252
+ if (
1253
+ this.config.blobCache?.clearOnSignOut &&
1254
+ target === ANON_USER_ID &&
1255
+ leavingBucket !== ANON_USER_ID
1256
+ ) {
1257
+ await this.blobs.clear();
1258
+ }
1259
+ await this.blobs.setNamespace(target);
1260
+ } catch (e) {
1261
+ this.logger.warn(
1262
+ { err: e, target, Category: 'sp00ky-client::Sp00kyClient::doSwitchBucket' },
1263
+ 'Blob cache bucket switch failed'
1264
+ );
1265
+ }
1266
+ await this.streamProcessor.reset();
1267
+ this.streamProcessor.setPermissions(extractSelectPermissions(this.config.schemaSurql));
1268
+ this.cache.clearVersionLookups();
1269
+ void this.primeCircuit();
1270
+ // Preload dedup is per-bucket: the `_00_preload` markers + cached rows it
1271
+ // guards live in the local store we just swapped away from. Keeping the
1272
+ // hashes would make `preload()` skip warming the NEW bucket (its store is
1273
+ // empty), so every thread/comment prewarm silently no-ops after login.
1274
+ this.preloadedHashes.clear();
1275
+ } finally {
1276
+ reopen();
1277
+ }
1278
+
1279
+ if (this.auth.token) {
1280
+ try {
1281
+ await this.persistenceClient.set('sp00ky_auth_token', this.auth.token);
1282
+ } catch (e) {
1283
+ this.logger.warn(
1284
+ { error: e, Category: 'sp00ky-client::Sp00kyClient::doSwitchBucket' },
1285
+ 'Failed to re-persist auth token into the new bucket'
1286
+ );
1287
+ }
1288
+ }
1289
+
1290
+ const hashes = await this.dataModule.rebindAfterBucketSwitch();
1291
+ await this.sync.completeBucketSwitch();
1292
+ for (const hash of hashes) {
1293
+ this.sync.enqueueDownEvent({ type: 'register', payload: { hash } });
1294
+ }
1295
+
1296
+ this.logger.info(
1297
+ { target, queries: hashes.length, Category: 'sp00ky-client::Sp00kyClient::doSwitchBucket' },
1298
+ 'Local bucket switch complete'
1299
+ );
1300
+ }
1301
+
1302
+ /** Removes the `pagehide` listener installed in `init`; see `close`. */
1303
+ private detachUnloadRelease: (() => void) | null = null;
1304
+
1305
+ async close() {
1306
+ // Before anything else: a live supervisor would read the intentional
1307
+ // `remote.close()` below as a failure and immediately reconnect.
1308
+ this.connectionSupervisor.dispose();
1309
+ await this.featureFlags.closeAll();
1310
+ await this.appReleases.closeAll();
1311
+ this.crdtManager.closeAll();
1312
+ this.crdtManager.dispose();
1313
+ // Flush the blob manifest while the local store is still open — the flush
1314
+ // writes `_00_blob` rows through it — and revoke every object URL.
1315
+ await this.blobs.close().catch(() => {});
1316
+ // Last chance to persist the circuit while the store is still ours.
1317
+ await this.streamProcessor.checkpoint('close').catch(() => {});
1318
+ // Leaving the broker first hands leadership to another tab (and releases
1319
+ // the OPFS handles via the worker shutdown) before the store closes.
1320
+ if (this.tabsCoordinator) await this.tabsCoordinator.stop();
1321
+ this.detachUnloadRelease?.();
1322
+ this.detachUnloadRelease = null;
1323
+ await this.local.close();
1324
+ await this.remote.close();
1325
+ // Free the wasm circuit explicitly. V8 cannot see wasm-internal bytes, so
1326
+ // relying on the wasm-bindgen FinalizationRegistry leaves the whole store
1327
+ // resident until a GC that may never come, and a client that is recreated
1328
+ // (provider remount, HMR) would stack circuits.
1329
+ this.streamProcessor.dispose();
1330
+ }
1331
+
1332
+ /**
1333
+ * Subscribe to a feature flag for the current user. Returns a
1334
+ * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
1335
+ * accessors reflect the latest assignment from `_00_user_feature`,
1336
+ * and whose `subscribe(cb)` fires whenever that assignment changes.
1337
+ *
1338
+ * Permissions are enforced by SurrealDB: a client can only ever see
1339
+ * its own row, and cannot create or modify assignments.
1340
+ */
1341
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle {
1342
+ return this.featureFlags.feature(key, options);
1343
+ }
1344
+
1345
+ /**
1346
+ * Force a feature flag to `variant` in THIS browser only; `null` clears it.
1347
+ *
1348
+ * Nothing is sent to the server — the `_00_user_feature` assignment is
1349
+ * untouched, so clearing restores whatever the server says. Persisted to
1350
+ * localStorage, survives reloads, and applies while signed out. Backs the
1351
+ * DevTools Access tab, and is a convenient hook for tests.
1352
+ *
1353
+ * To change a flag for OTHER users you need admin rights (`spky admin add`)
1354
+ * and the DevTools Access tab, or `spky flag`.
1355
+ */
1356
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void {
1357
+ this.featureFlags.setLocalOverride(key, variant, payload);
1358
+ }
1359
+
1360
+ /** Drop every local feature flag override set via `setFeatureOverride`. */
1361
+ clearFeatureOverrides(): void {
1362
+ this.featureFlags.clearLocalOverrides();
1363
+ }
1364
+
1365
+ /** The local feature flag overrides currently in effect, keyed by flag. */
1366
+ getFeatureOverrides(): Record<string, FeatureFlagOverride> {
1367
+ return this.featureFlags.getLocalOverrides();
1368
+ }
1369
+
1370
+ /**
1371
+ * Observe the announced release of an app (`_00_app_release:<app>`, written
1372
+ * by `spky deploy` / `spky release`). The handle's `snapshot()` carries the
1373
+ * announced version plus the cache-bust/mandatory flags, and
1374
+ * `updateAvailable(currentVersion)` compares it semver-wise against the
1375
+ * running build. World-readable; writes are root-only.
1376
+ */
1377
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle {
1378
+ return this.appReleases.release(app, options);
1379
+ }
1380
+
1381
+ authenticate(token: string) {
1382
+ // Record it before authenticating, so a socket the supervisor rebuilds
1383
+ // later comes back as this identity rather than anonymous. See
1384
+ // `RemoteDatabaseService.setAuthToken`.
1385
+ this.remote.setAuthToken(token);
1386
+ return this.remote.getClient().authenticate(token);
1387
+ }
1388
+
1389
+ /**
1390
+ * Open a CRDT field for collaborative editing.
1391
+ * Returns a CrdtField with a LoroDoc that can be bound to any editor.
1392
+ * Also starts a LIVE SELECT on the parent table for real-time sync;
1393
+ * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
1394
+ */
1395
+ async openCrdtField(
1396
+ table: string,
1397
+ recordId: string,
1398
+ field: string,
1399
+ fallbackText?: string
1400
+ ): Promise<CrdtField> {
1401
+ return this.crdtManager.open(table, recordId, field, fallbackText);
1402
+ }
1403
+
1404
+ /**
1405
+ * Close a CRDT field when editing is done.
1406
+ */
1407
+ closeCrdtField(table: string, recordId: string, field: string): void {
1408
+ this.crdtManager.close(table, recordId, field);
1409
+ }
1410
+
1411
+ deauthenticate() {
1412
+ return this.remote.getClient().invalidate();
1413
+ }
1414
+
1415
+ query<Table extends TableNames<S>>(
1416
+ table: Table,
1417
+ options: QueryOptions<TableModel<GetTable<S, Table>>, false>,
1418
+ ttl: QueryTimeToLive = '10m'
1419
+ ): QueryBuilder<S, Table, Sp00kyQueryResultPromise> {
1420
+ return new QueryBuilder<S, Table, Sp00kyQueryResultPromise>(
1421
+ this.config.schema,
1422
+ table,
1423
+ async (q) => ({
1424
+ hash: await this.initQuery(table, q, ttl),
1425
+ }),
1426
+ options
1427
+ );
1428
+ }
1429
+
1430
+ private async initQuery<Table extends TableNames<S>>(
1431
+ table: Table,
1432
+ q: InnerQuery<any, any, any>,
1433
+ ttl: QueryTimeToLive
1434
+ ) {
1435
+ const tableSchema = this.config.schema.tables.find((t) => t.name === table);
1436
+ if (!tableSchema) {
1437
+ throw new Error(`Table ${table} not found`);
1438
+ }
1439
+
1440
+ const params = parseQueryParams(tableSchema.columns, q.selectQuery.vars ?? {});
1441
+ const hash = await this.dataModule.query(
1442
+ table,
1443
+ q.selectQuery.query,
1444
+ params,
1445
+ ttl,
1446
+ q.selectQuery.plan
1447
+ );
1448
+
1449
+ // Local-first paint: the hash is returned as soon as the LOCAL registration
1450
+ // above completes — `queryState.records` is already seeded from the local
1451
+ // cache/SSP snapshot, so `useQuery` subscribes and paints from memory with
1452
+ // zero network on the paint path. Instant-hydrate and the `register`
1453
+ // down-event continue in a background chain (hydrate strictly before
1454
+ // enqueue, so a stale one-shot snapshot can never land after the sync's
1455
+ // authoritative `_00_list_ref` overwrite). Concurrent mounts of the same
1456
+ // query share one chain; a sequential re-mount starts a fresh one so its
1457
+ // `register` re-enqueue keeps freshening warm data on use.
1458
+ if (!this.pendingQueryInits.has(hash)) {
1459
+ const chain = this.finishQueryInit(hash, q, params).finally(() => {
1460
+ this.pendingQueryInits.delete(hash);
1461
+ });
1462
+ this.pendingQueryInits.set(hash, chain);
1463
+ }
1464
+
1465
+ return hash;
1466
+ }
1467
+
1468
+ /**
1469
+ * Background tail of {@link initQuery}: instant-hydrate (opt-in via
1470
+ * `config.instantHydrate`, and only when the query is cold) followed by
1471
+ * enqueuing the `register` down-event. Never rejects — both halves catch and
1472
+ * log, so `void`-ing the returned promise can't produce an unhandled
1473
+ * rejection. By default (hydrate off) the register lifecycle is the single
1474
+ * freshness path; the one-shot fetch is an optimization apps enable
1475
+ * explicitly, and it runs regardless of preload state — cache-first delivery
1476
+ * never depends on WHY rows are cached.
1477
+ */
1478
+ private async finishQueryInit(
1479
+ hash: string,
1480
+ q: InnerQuery<any, any, any>,
1481
+ params: Record<string, any>
1482
+ ): Promise<void> {
1483
+ if (this.config.instantHydrate === true && this.dataModule.isCold(hash)) {
1484
+ try {
1485
+ // Fence against bucket switches: rows fetched under the previous
1486
+ // auth context must not hydrate the new bucket's query state — the
1487
+ // rebind's re-registration refills it from the right context.
1488
+ const epoch = this.local.epoch;
1489
+ const [rows] = await this.remote.query<[RecordWithId[]]>(q.selectQuery.query, params);
1490
+ if (epoch === this.local.epoch) {
1491
+ await this.dataModule.applyHydration(hash, rows ?? []);
1492
+ }
1493
+ } catch (err) {
1494
+ if (err instanceof StaleEpochError) {
1495
+ this.logger.debug(
1496
+ { hash, Category: 'sp00ky-client::Sp00kyClient::instantHydrate' },
1497
+ 'Dropped instant hydrate from before a bucket switch'
1498
+ );
1499
+ } else {
1500
+ this.logger.warn(
1501
+ { err, hash, Category: 'sp00ky-client::Sp00kyClient::instantHydrate' },
1502
+ 'Instant hydrate failed; proceeding with registration'
1503
+ );
1504
+ }
1505
+ }
1506
+ }
1507
+
1508
+ try {
1509
+ await this.sync.enqueueDownEvent({
1510
+ type: 'register',
1511
+ payload: {
1512
+ hash,
1513
+ },
1514
+ });
1515
+ } catch (err) {
1516
+ this.logger.error(
1517
+ { err, hash, Category: 'sp00ky-client::Sp00kyClient::initQuery' },
1518
+ 'Failed to enqueue register down-event'
1519
+ );
1520
+ }
1521
+ }
1522
+
1523
+ /**
1524
+ * Smart, awaitable preload/prewarm into the LOCAL cache — without registering a
1525
+ * live view (NO `_00_query`, NO subscription, NO TTL heartbeat).
1526
+ *
1527
+ * Cache-aware via a durable per-bucket freshness marker (`_00_preload`):
1528
+ * - COLD (never preloaded in this bucket): fetch the query one-shot from the
1529
+ * remote, persist the rows (+ embedded `.related()` children), stamp the
1530
+ * marker — and AWAIT it. This is the "smart waiting" first load: callers can
1531
+ * `await db.preload(...)` to hold the UI until the data is ready.
1532
+ * - WARM (marker present): return instantly — NEVER blocks. `refresh` decides
1533
+ * whether to also kick a one-time silent refetch (see {@link PreloadOptions}).
1534
+ * Default `onUse` does nothing; the data freshens when the real `useQuery`
1535
+ * mounts and registers its live view.
1536
+ *
1537
+ * Best-effort: any fetch failure (offline, etc.) is a no-op warn (no marker
1538
+ * written, so it's retried next load). Deduped per session by query hash.
1539
+ */
1540
+ async preload(
1541
+ finalQuery: FinalQuery<S, any, any, any, any, any>,
1542
+ options?: PreloadOptions
1543
+ ): Promise<void> {
1544
+ const q = finalQuery.innerQuery;
1545
+ if (this.preloadedHashes.has(q.hash)) return;
1546
+
1547
+ const tableName = q.tableName;
1548
+ const tableSchema = this.config.schema.tables.find((t) => t.name === tableName);
1549
+ if (!tableSchema) {
1550
+ throw new Error(`Table ${tableName} not found`);
1551
+ }
1552
+ const params = parseQueryParams(tableSchema.columns, q.selectQuery.vars ?? {});
1553
+ const hashKey = String(q.hash);
1554
+
1555
+ const marker = await this.dataModule.getPreloadMarker(hashKey);
1556
+
1557
+ // COLD → fetch + persist + stamp, awaited so the caller can block on it.
1558
+ if (!marker) {
1559
+ const rowCount = await this.fetchAndPersist(q, tableName, params);
1560
+ if (rowCount >= 0) {
1561
+ await this.dataModule.writePreloadMarker(hashKey, rowCount);
1562
+ this.preloadedHashes.add(q.hash);
1563
+ }
1564
+ return;
1565
+ }
1566
+
1567
+ // WARM → never block. Mark handled for this session, then optionally refresh.
1568
+ this.preloadedHashes.add(q.hash);
1569
+ const refresh = options?.refresh ?? 'onUse';
1570
+ if (refresh === 'onUse') return;
1571
+
1572
+ if (refresh === 'stale') {
1573
+ const maxAgeMs = parseDuration(options?.staleTime ?? '1h');
1574
+ if (Date.now() - marker.fetchedAt <= maxAgeMs) return; // still fresh
1575
+ }
1576
+
1577
+ // `background`, or `stale` past its staleTime → one-time silent refetch.
1578
+ void this.fetchAndPersist(q, tableName, params).then((rowCount) => {
1579
+ if (rowCount >= 0) return this.dataModule.writePreloadMarker(hashKey, rowCount);
1580
+ });
1581
+ }
1582
+
1583
+ /**
1584
+ * One-shot remote fetch + local persist for a preload query. Returns the row
1585
+ * count on success, or -1 on failure (best-effort: logged, never thrown) so
1586
+ * the caller skips stamping the freshness marker and retries next load.
1587
+ */
1588
+ private async fetchAndPersist(
1589
+ q: InnerQuery<any, any, any>,
1590
+ tableName: string,
1591
+ params: Record<string, any>
1592
+ ): Promise<number> {
1593
+ try {
1594
+ const [rows] = await this.remote.query<[RecordWithId[]]>(q.selectQuery.query, params);
1595
+ const list = rows ?? [];
1596
+ await this.dataModule.persistSnapshot(tableName, list);
1597
+ return list.length;
1598
+ } catch (err) {
1599
+ this.logger.warn(
1600
+ { err, hash: q.hash, Category: 'sp00ky-client::Sp00kyClient::preload' },
1601
+ 'Preload fetch failed; data will be fetched on demand'
1602
+ );
1603
+ return -1;
1604
+ }
1605
+ }
1606
+
1607
+ async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive) {
1608
+ const tableName = sql.split('FROM ')[1].split(' ')[0];
1609
+ return this.dataModule.query(tableName, sql, params, ttl);
1610
+ }
1611
+
1612
+ async subscribe(
1613
+ queryHash: string,
1614
+ callback: (records: Record<string, any>[]) => void,
1615
+ options?: { immediate?: boolean }
1616
+ ): Promise<() => void> {
1617
+ return this.dataModule.subscribe(queryHash, callback, options);
1618
+ }
1619
+
1620
+ /**
1621
+ * Opt-in eager teardown for a query whose last subscriber has gone away
1622
+ * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
1623
+ * while any subscriber remains. Tears down the remote `_00_query` view +
1624
+ * local WASM view instead of waiting for the TTL sweep. Default behavior
1625
+ * (no call here) keeps the view resident for cheap re-subscription.
1626
+ */
1627
+ deregisterQuery(queryHash: string): void {
1628
+ this.dataModule.deregisterQuery(queryHash);
1629
+ }
1630
+
1631
+ /**
1632
+ * Subscribe to a query's fetch-status changes (idle/fetching). With
1633
+ * `{ immediate: true }` the callback fires synchronously with the current
1634
+ * status. Powers the `useQuery` hook's `isFetching()` accessor.
1635
+ */
1636
+ subscribeQueryStatus(
1637
+ queryHash: string,
1638
+ callback: QueryStatusCallback,
1639
+ options?: { immediate?: boolean }
1640
+ ): () => void {
1641
+ return this.dataModule.subscribeStatus(queryHash, callback, options);
1642
+ }
1643
+
1644
+ /**
1645
+ * Report the frontend processing time (ms) a client framework spent applying
1646
+ * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
1647
+ * surface the "frontend" phase of the per-query timing breakdown.
1648
+ */
1649
+ reportFrontendTiming(queryHash: string, ms: number): void {
1650
+ this.dataModule.recordFrontendTiming(queryHash, ms);
1651
+ }
1652
+
1653
+ run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(
1654
+ backend: B,
1655
+ path: R,
1656
+ payload: RoutePayload<S, B, R>,
1657
+ options?: RunOptions
1658
+ ) {
1659
+ return this.dataModule.run(backend, path, payload, options);
1660
+ }
1661
+
1662
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle {
1663
+ return new BucketHandle(name, this.remote, this.blobs, {
1664
+ blurhash: this.config.blurhash,
1665
+ logger: this.logger,
1666
+ });
1667
+ }
1668
+
1669
+ /** Cache-free handle. The blob cache reads the remote through this, so a
1670
+ * cache miss can't loop back into the cache. */
1671
+ private rawBucket(name: string): BucketHandle {
1672
+ return new BucketHandle(name, this.remote, null, {
1673
+ blurhash: this.config.blurhash,
1674
+ logger: this.logger,
1675
+ });
1676
+ }
1677
+
1678
+ /** Blob cache counters for DevTools. */
1679
+ getBlobCacheStats() {
1680
+ return this.blobs.stats();
1681
+ }
1682
+
1683
+ create(id: string, data: Record<string, unknown>) {
1684
+ return this.dataModule.create(id, data);
1685
+ }
1686
+
1687
+ update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions) {
1688
+ return this.dataModule.update(table, id, data, options);
1689
+ }
1690
+
1691
+ delete(table: string, id: string) {
1692
+ return this.dataModule.delete(table, id);
1693
+ }
1694
+
1695
+ /**
1696
+ * Whether the local store is initialized and reads can be served. See the
1697
+ * `localReady` field: this is deliberately independent of connectivity.
1698
+ */
1699
+ isLocalReady(): boolean {
1700
+ return this.localReady;
1701
+ }
1702
+
1703
+ async useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T> {
1704
+ return fn(this.remote.getClient());
1705
+ }
1706
+
1707
+ /**
1708
+ * Mint the salt used for query-id hashing, so two sessions registering the
1709
+ * same logical query get distinct `_00_query` rows.
1710
+ *
1711
+ * Generated LOCALLY, deliberately. This used to be `RETURN <string>session::id()`,
1712
+ * which cost a serial round trip on the critical boot path and resolved to
1713
+ * `''` offline. The value never needed to come from the server: the server
1714
+ * derives its own `clientId` inside `fn::query::register` and *ignores*
1715
+ * whatever the caller passed, and the permission rules that matter gate on
1716
+ * `auth_id = $auth.id` rather than the session (`_00_list_ref`). Session
1717
+ * scoping via `clientId = session::id()` was in fact removed upstream because
1718
+ * it broke a user with two tabs open. All this value has to be is unique per
1719
+ * browser session, which `randomUUID` gives us for free and offline.
1720
+ */
1721
+ /**
1722
+ * The current principal as the `"table:id"` string the in-browser SSP wants
1723
+ * for `$auth.id`, or null when signed out.
1724
+ *
1725
+ * Tolerates BOTH shapes `currentUser.id` can take, which is the point:
1726
+ * a session restored from the cached token carries a plain string (the JWT's
1727
+ * `ID` claim), while one verified by the server carries a RecordId. Passing
1728
+ * the former to `encodeRecordId` reads `.table` off a string and throws
1729
+ * during boot.
1730
+ */
1731
+ /**
1732
+ * Prime the in-browser circuit from the local store. Builds the context the
1733
+ * stream processor needs: every synced table (the app schema plus the
1734
+ * server-written meta tables that sync down), a schema hash so a snapshot
1735
+ * projected under another schema is not trusted, and the ids whose local
1736
+ * `_00_rv` was bumped by an unsettled mutation.
1737
+ */
1738
+ private async primeCircuit(): Promise<void> {
1739
+ const tables = [
1740
+ ...this.config.schema.tables.map((t) => t.name),
1741
+ '_00_user_feature',
1742
+ '_00_app_release',
1743
+ ];
1744
+ let pendingIds = new Set<string>();
1745
+ try {
1746
+ const pending = await this.dataModule.getPendingRecordIds();
1747
+ pendingIds = new Set([...pending.writes, ...pending.deletes]);
1748
+ } catch {
1749
+ /* no outbox yet: nothing is pending */
1750
+ }
1751
+ await this.streamProcessor.primeFromLocal({
1752
+ tables,
1753
+ schemaHash: String(hash53(this.config.schemaSurql)),
1754
+ pendingIds,
1755
+ onVersions: (_table, entries) => this.cache.primeVersions(entries),
1756
+ });
1757
+ }
1758
+
1759
+ private sessionAuthId(): string | null {
1760
+ const id = this.auth.currentUser?.id;
1761
+ if (!id) return null;
1762
+ return typeof id === 'string' ? id : encodeRecordId(id);
1763
+ }
1764
+
1765
+ private mintSessionSalt(): string {
1766
+ const c: Crypto | undefined =
1767
+ typeof globalThis !== 'undefined' ? (globalThis as { crypto?: Crypto }).crypto : undefined;
1768
+ if (c?.randomUUID) return c.randomUUID();
1769
+ // Older browsers / non-secure contexts: uniqueness is all that is required.
1770
+ return `s${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
1771
+ }
1772
+ }