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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2514 -58
  3. package/dist/index.js +12561 -2449
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +303 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +439 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +472 -0
  11. package/dist/types.d.ts +751 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +36 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/auth.local-first.test.ts +101 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +127 -24
  27. package/src/modules/cache/cache.relay.test.ts +95 -0
  28. package/src/modules/cache/index.ts +163 -43
  29. package/src/modules/cache/types.ts +2 -2
  30. package/src/modules/crdt/crdt-field.ts +294 -0
  31. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  32. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  33. package/src/modules/crdt/index.ts +463 -0
  34. package/src/modules/crdt/loro-loader.ts +25 -0
  35. package/src/modules/data/data.hydration.test.ts +142 -0
  36. package/src/modules/data/data.membership.test.ts +523 -0
  37. package/src/modules/data/data.notify-table.test.ts +41 -0
  38. package/src/modules/data/data.pending-ids.test.ts +199 -0
  39. package/src/modules/data/data.rebind.test.ts +170 -0
  40. package/src/modules/data/data.rematerialize.test.ts +114 -0
  41. package/src/modules/data/data.run.test.ts +113 -0
  42. package/src/modules/data/data.settled-writes.test.ts +206 -0
  43. package/src/modules/data/data.status.test.ts +249 -0
  44. package/src/modules/data/id-set-plan.test.ts +122 -0
  45. package/src/modules/data/index.ts +1815 -151
  46. package/src/modules/data/mutation-id.test.ts +25 -0
  47. package/src/modules/data/mutation-id.ts +35 -0
  48. package/src/modules/data/window-query.test.ts +52 -0
  49. package/src/modules/data/window-query.ts +194 -0
  50. package/src/modules/devtools/flags.ts +349 -0
  51. package/src/modules/devtools/index.ts +450 -46
  52. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  53. package/src/modules/devtools/state-shape.test.ts +146 -0
  54. package/src/modules/devtools/storage-info.test.ts +79 -0
  55. package/src/modules/devtools/storage-info.ts +168 -0
  56. package/src/modules/devtools/versions.test.ts +74 -0
  57. package/src/modules/devtools/versions.ts +110 -0
  58. package/src/modules/feature-flag/index.test.ts +251 -0
  59. package/src/modules/feature-flag/index.ts +308 -0
  60. package/src/modules/ref-tables.test.ts +91 -0
  61. package/src/modules/ref-tables.ts +88 -0
  62. package/src/modules/sync/engine.ts +164 -82
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +180 -0
  65. package/src/modules/sync/queue/queue-down.ts +80 -13
  66. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  67. package/src/modules/sync/queue/queue-up.ts +241 -57
  68. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  69. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  70. package/src/modules/sync/scheduler.ts +215 -13
  71. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  72. package/src/modules/sync/sync.health.test.ts +149 -0
  73. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  74. package/src/modules/sync/sync.live-removal.test.ts +175 -0
  75. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  76. package/src/modules/sync/sync.subquery.test.ts +82 -0
  77. package/src/modules/sync/sync.tabs.test.ts +249 -0
  78. package/src/modules/sync/sync.ts +1726 -99
  79. package/src/modules/sync/utils.test.ts +269 -2
  80. package/src/modules/sync/utils.ts +201 -17
  81. package/src/otel/index.ts +13 -10
  82. package/src/services/blobs/blob-cache.test.ts +359 -0
  83. package/src/services/blobs/blob-cache.ts +603 -0
  84. package/src/services/blobs/blob-manifest.ts +227 -0
  85. package/src/services/blobs/blob-store.test.ts +77 -0
  86. package/src/services/blobs/blob-store.ts +359 -0
  87. package/src/services/blobs/blob.fixture.ts +90 -0
  88. package/src/services/blobs/index.ts +70 -0
  89. package/src/services/database/cache-engine.ts +193 -0
  90. package/src/services/database/connection-supervisor.test.ts +289 -0
  91. package/src/services/database/connection-supervisor.ts +415 -0
  92. package/src/services/database/database.query-timeout.test.ts +83 -0
  93. package/src/services/database/database.ts +41 -12
  94. package/src/services/database/engine-factory.ts +33 -0
  95. package/src/services/database/errors.ts +34 -0
  96. package/src/services/database/events/index.ts +2 -1
  97. package/src/services/database/index.ts +7 -0
  98. package/src/services/database/local-migrator.ts +30 -27
  99. package/src/services/database/local.test.ts +64 -0
  100. package/src/services/database/local.ts +484 -67
  101. package/src/services/database/plan-render.test.ts +159 -0
  102. package/src/services/database/plan-render.ts +108 -0
  103. package/src/services/database/relation-resolver.test.ts +413 -0
  104. package/src/services/database/relation-resolver.ts +0 -0
  105. package/src/services/database/remote.ts +110 -14
  106. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  107. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  108. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  109. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  110. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  111. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  112. package/src/services/database/sqlite-lock-verify.ts +45 -0
  113. package/src/services/database/sqlite-open.test.ts +150 -0
  114. package/src/services/database/sqlite-open.ts +164 -0
  115. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  116. package/src/services/database/sqlite-plan-sql.ts +138 -0
  117. package/src/services/database/sqlite-projection.test.ts +99 -0
  118. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  119. package/src/services/database/sqlite-select.test.ts +246 -0
  120. package/src/services/database/sqlite-select.ts +131 -0
  121. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  122. package/src/services/database/sqlite-transport.ts +224 -0
  123. package/src/services/database/sqlite-worker.ts +437 -0
  124. package/src/services/database/surql-translate.ts +416 -0
  125. package/src/services/database/surreal-cache-engine.ts +161 -0
  126. package/src/services/logger/index.ts +3 -2
  127. package/src/services/persistence/localstorage.ts +2 -2
  128. package/src/services/persistence/resilient.ts +11 -4
  129. package/src/services/persistence/surrealdb.ts +10 -10
  130. package/src/services/stream-processor/index.ts +796 -84
  131. package/src/services/stream-processor/permissions.test.ts +47 -0
  132. package/src/services/stream-processor/permissions.ts +53 -0
  133. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  134. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  135. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  136. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  137. package/src/services/stream-processor/wasm-types.ts +59 -3
  138. package/src/services/tabs/broker-client.ts +283 -0
  139. package/src/services/tabs/broker.test.ts +327 -0
  140. package/src/services/tabs/coordinator.test.ts +365 -0
  141. package/src/services/tabs/coordinator.ts +633 -0
  142. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  143. package/src/services/tabs/leader-locks.ts +75 -0
  144. package/src/services/tabs/protocol.ts +258 -0
  145. package/src/services/tabs/support.ts +36 -0
  146. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  147. package/src/sp00ky.auth-order.test.ts +92 -0
  148. package/src/sp00ky.init-query.test.ts +183 -0
  149. package/src/sp00ky.local-first.test.ts +60 -0
  150. package/src/sp00ky.ts +1693 -0
  151. package/src/types.ts +528 -13
  152. package/src/utils/blurhash.ts +90 -0
  153. package/src/utils/error-classification.test.ts +44 -0
  154. package/src/utils/error-classification.ts +7 -0
  155. package/src/utils/index.ts +79 -13
  156. package/src/utils/parser.test.ts +49 -120
  157. package/src/utils/parser.ts +32 -2
  158. package/src/utils/semver.test.ts +32 -0
  159. package/src/utils/semver.ts +30 -0
  160. package/src/utils/surql.ts +30 -18
  161. package/src/utils/withRetry.test.ts +1 -1
  162. package/tsdown.config.ts +86 -1
  163. package/src/spooky.ts +0 -395
@@ -1,99 +1,516 @@
1
- import { applyDiagnostics, DateTime, Diagnostic, RecordId, Surreal } from 'surrealdb';
2
- import { createWasmWorkerEngines } from '@surrealdb/wasm';
3
- import { SpookyConfig } from '../../types';
4
- import { Logger } from '../logger/index';
1
+ import type { Diagnostic} from 'surrealdb';
2
+ import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
3
+ import { applyDiagnostics, DateTime, RecordId, Surreal } from 'surrealdb';
4
+ import type { Sp00kyConfig } from '../../types';
5
+ import type { Logger } from '../logger/index';
5
6
  import { AbstractDatabaseService } from './database';
6
7
  import { createDatabaseEventSystem, DatabaseEventTypes } from './events/index';
7
- import { encodeRecordId, parseRecordIdString, surql } from '../../utils/index';
8
+ import { encodeRecordId } from '../../utils/index';
9
+ import { ANON_USER_ID } from '../../modules/ref-tables';
10
+ import type { SealedQuery } from '../../utils/surql';
11
+
12
+ /** Thrown when a query carries an `epoch` from before a bucket switch. The
13
+ * caller's chain read from the previous user's store; its write must be
14
+ * dropped, not applied to the new bucket. */
15
+ export class StaleEpochError extends Error {
16
+ constructor() {
17
+ super('Local store epoch changed (bucket switch); stale write dropped');
18
+ this.name = 'StaleEpochError';
19
+ }
20
+ }
21
+
22
+ /** Store URL for a local bucket. One IndexedDB store per user (`anon` for
23
+ * signed-out) so cached rows never leak across accounts on a shared device. */
24
+ export function bucketStoreUrl(bucketId: string): string {
25
+ return `indxdb://${bucketStoreName(bucketId)}`;
26
+ }
27
+
28
+ /** The IndexedDB database name SurrealDB-WASM derives from the store URL. */
29
+ export function bucketStoreName(bucketId: string): string {
30
+ return `sp00ky-${bucketId}`;
31
+ }
32
+
33
+ /** Shared codec: mirrors SurrealDB RecordId/DateTime into our own encodings. */
34
+ const localCodecOptions = {
35
+ valueDecodeVisitor(value: unknown) {
36
+ if (value instanceof RecordId) {
37
+ return encodeRecordId(value);
38
+ }
39
+
40
+ if (value instanceof DateTime) {
41
+ return value.toDate();
42
+ }
43
+
44
+ return value;
45
+ },
46
+ };
47
+
48
+ /**
49
+ * Engine-less Surreal client used as the constructor placeholder. Building this
50
+ * pulls in NO `@surrealdb/wasm` — the ~6 MB wasm engine is deferred to
51
+ * {@link createLocalSurrealClient}, which runs lazily in `connect`/`switchStore`.
52
+ * `connect()` replaces `this.client` with an engine-backed client before any
53
+ * query runs, so this bare client is never actually opened against a store.
54
+ */
55
+ function createBareSurrealClient(): Surreal {
56
+ return new Surreal({ codecOptions: localCodecOptions });
57
+ }
58
+
59
+ /**
60
+ * Engine-backed client. Dynamically imports `@surrealdb/wasm` so the wasm engine
61
+ * only enters the graph as a separate chunk fetched on first connect (module-
62
+ * cached thereafter — `switchStore`'s await is instant).
63
+ */
64
+ async function createLocalSurrealClient(logger: Logger): Promise<Surreal> {
65
+ const { createWasmWorkerEngines } = await import('@surrealdb/wasm');
66
+ return new Surreal({
67
+ codecOptions: localCodecOptions,
68
+ engines: applyDiagnostics(
69
+ createWasmWorkerEngines(),
70
+ ({ key, type, phase, ...other }: Diagnostic) => {
71
+ if (phase === 'progress' || phase === 'after') {
72
+ logger.trace(
73
+ {
74
+ ...other,
75
+ key,
76
+ type,
77
+ phase,
78
+ service: 'surrealdb:local',
79
+ Category: 'sp00ky-client::LocalDatabaseService::diagnostics',
80
+ },
81
+ `Local SurrealDB diagnostics captured ${type}:${phase}`
82
+ );
83
+ }
84
+ }
85
+ ),
86
+ });
87
+ }
8
88
 
9
89
  export class LocalDatabaseService extends AbstractDatabaseService {
10
- private config: SpookyConfig<any>['database'];
90
+ private config: Sp00kyConfig<any>['database'];
11
91
  protected eventType = DatabaseEventTypes.LocalQuery;
12
92
 
13
- constructor(config: SpookyConfig<any>['database'], logger: Logger) {
93
+ /** Bucket currently open. Set by `connect`/`switchStore`. */
94
+ private bucketId: string = ANON_USER_ID;
95
+ /**
96
+ * Monotonic store generation. Bumped on every `switchStore`. Async chains
97
+ * that read from the store, await something remote, and then write back
98
+ * (sync poll, SSP stream updates) capture this at chain start and drop
99
+ * their write when it no longer matches — a stale-epoch write would land
100
+ * another user's data in the new bucket.
101
+ */
102
+ private storeEpoch = 0;
103
+ /** Gate that `query()`/`execute()` await; closed for the switch window. */
104
+ private gate: Promise<void> = Promise.resolve();
105
+ /** The incoming client while a switch is in flight (for unload cleanup). */
106
+ private pendingSwitchClient: Surreal | null = null;
107
+
108
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger) {
14
109
  const events = createDatabaseEventSystem();
15
- super(
16
- new Surreal({
17
- codecOptions: {
18
- valueDecodeVisitor(value) {
19
- if (value instanceof RecordId) {
20
- return encodeRecordId(value);
21
- }
22
-
23
- if (value instanceof DateTime) {
24
- return value.toDate();
25
- }
26
-
27
- return value;
28
- },
29
- },
30
- engines: applyDiagnostics(
31
- createWasmWorkerEngines(),
32
- ({ key, type, phase, ...other }: Diagnostic) => {
33
- if (phase === 'progress' || phase === 'after') {
34
- logger.trace(
35
- {
36
- ...other,
37
- key,
38
- type,
39
- phase,
40
- service: 'surrealdb:local',
41
- Category: 'spooky-client::LocalDatabaseService::diagnostics',
42
- },
43
- `Local SurrealDB diagnostics captured ${type}:${phase}`
44
- );
45
- }
46
- }
47
- ),
48
- }),
49
- logger,
50
- events
51
- );
110
+ // Placeholder client with no wasm engine; `connect()` swaps in the real
111
+ // engine-backed client (built lazily) before any query is issued.
112
+ super(createBareSurrealClient(), logger, events);
52
113
  this.config = config;
114
+ this.queryTimeoutMs = Math.max(0, config.localOpTimeoutMs ?? DEFAULT_LOCAL_OP_TIMEOUT_MS);
53
115
  }
54
116
 
55
- getConfig(): SpookyConfig<any>['database'] {
117
+ protected override timeoutError(query: string): Error {
118
+ return new LocalOpTimeoutError(query.slice(0, 80), this.queryTimeoutMs);
119
+ }
120
+
121
+ getConfig(): Sp00kyConfig<any>['database'] {
56
122
  return this.config;
57
123
  }
58
124
 
59
- async connect(): Promise<void> {
125
+ get currentBucketId(): string {
126
+ return this.bucketId;
127
+ }
128
+
129
+ get epoch(): number {
130
+ return this.storeEpoch;
131
+ }
132
+
133
+ /**
134
+ * Close the query gate for a bucket switch. Every `query()`/`execute()`
135
+ * issued after this waits until the returned release fn runs — so work
136
+ * triggered mid-switch (sibling auth subscribers registering queries)
137
+ * lands on the NEW bucket instead of racing the swap. The migrator uses
138
+ * `queryUngated()` to provision the new bucket while the gate is closed.
139
+ */
140
+ beginSwitch(): () => void {
141
+ let release!: () => void;
142
+ this.gate = new Promise<void>((resolve) => {
143
+ release = resolve;
144
+ });
145
+ return release;
146
+ }
147
+
148
+ override async query<T extends unknown[]>(
149
+ query: string,
150
+ vars?: Record<string, unknown>,
151
+ opts?: { epoch?: number }
152
+ ): Promise<T> {
153
+ await this.gate;
154
+ // A write whose async chain started before a bucket switch must not land
155
+ // in the new bucket — that would be another user's data. Callers on such
156
+ // chains pass the epoch they captured at chain start; mismatches throw.
157
+ if (opts?.epoch !== undefined && opts.epoch !== this.storeEpoch) {
158
+ throw new StaleEpochError();
159
+ }
160
+ return super.query(query, vars);
161
+ }
162
+
163
+ override async execute<T>(
164
+ query: SealedQuery<T>,
165
+ vars?: Record<string, unknown>,
166
+ opts?: { epoch?: number }
167
+ ): Promise<T> {
168
+ const raw = await this.query<unknown[]>(query.sql, vars, opts);
169
+ return query.extract(raw);
170
+ }
171
+
172
+ /** Gate-bypassing query — ONLY for the switch path itself (schema
173
+ * provisioning must run while the gate is closed, or it deadlocks). */
174
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T> {
175
+ return super.query(query, vars);
176
+ }
177
+
178
+ async connect(bucketId: string = ANON_USER_ID): Promise<void> {
60
179
  const { namespace, database } = this.getConfig();
180
+ const store = this.getConfig().store ?? 'memory';
181
+ this.bucketId = bucketId;
182
+ const storeUrl = store === 'memory' ? 'mem://' : bucketStoreUrl(bucketId);
61
183
  this.logger.info(
62
- { namespace, database, Category: 'spooky-client::LocalDatabaseService::connect' },
184
+ { namespace, database, storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
63
185
  'Connecting to local database'
64
186
  );
65
- try {
66
- const store = this.getConfig().store ?? 'memory';
67
- const storeUrl = store === 'memory' ? 'mem://' : 'indxdb://spooky';
68
- this.logger.debug(
69
- { storeUrl, Category: 'spooky-client::LocalDatabaseService::connect' },
70
- '[LocalDatabaseService] Calling client.connect'
71
- );
72
- await this.client.connect(storeUrl, {});
73
- this.logger.debug(
74
- { namespace, database, Category: 'spooky-client::LocalDatabaseService::connect' },
75
- '[LocalDatabaseService] client.connect returned. Calling client.use'
187
+
188
+ this.registerUnloadClose();
189
+ // Build the real engine-backed client lazily here (first `@surrealdb/wasm`
190
+ // load), replacing the constructor's engine-less placeholder before any
191
+ // query runs.
192
+ this.client = await createLocalSurrealClient(this.logger);
193
+ await this.openWithRecovery(this.client, storeUrl, namespace, database, bucketId, store);
194
+ }
195
+
196
+ /**
197
+ * Switch the local store to another user's bucket. Opens the NEW bucket on a
198
+ * second client first (with the same 3-tier recovery), then atomically swaps
199
+ * `this.client` and closes the old one — a failed open never leaves the
200
+ * service on a dead client. Bumps the store epoch so in-flight old-bucket
201
+ * async chains can detect they're stale.
202
+ *
203
+ * Callers own the drain/rebind choreography (close the gate, quiesce sync +
204
+ * timers BEFORE calling this; re-provision + rebind AFTER).
205
+ */
206
+ async switchStore(bucketId: string): Promise<void> {
207
+ if (bucketId === this.bucketId) return;
208
+ const { namespace, database } = this.getConfig();
209
+ const store = this.getConfig().store ?? 'memory';
210
+ this.storeEpoch++;
211
+
212
+ if (store === 'memory') {
213
+ // mem:// has no per-user persistence; close + reopen the same client
214
+ // yields a fresh empty store, which is exactly the reset we want.
215
+ try {
216
+ await this.client.close();
217
+ } catch {
218
+ /* ignore */
219
+ }
220
+ await this.openStore(this.client, 'mem://', namespace, database);
221
+ this.bucketId = bucketId;
222
+ this.logger.info(
223
+ { bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
224
+ 'Reset in-memory local store for bucket switch'
76
225
  );
226
+ return;
227
+ }
77
228
 
78
- await this.client.use({
229
+ const next = await createLocalSurrealClient(this.logger);
230
+ this.pendingSwitchClient = next;
231
+ try {
232
+ await this.openWithRecovery(
233
+ next,
234
+ bucketStoreUrl(bucketId),
79
235
  namespace,
80
236
  database,
81
- });
82
- this.logger.debug(
83
- { Category: 'spooky-client::LocalDatabaseService::connect' },
84
- '[LocalDatabaseService] client.use returned'
237
+ bucketId,
238
+ store
85
239
  );
240
+ } finally {
241
+ this.pendingSwitchClient = null;
242
+ }
86
243
 
244
+ const old = this.client;
245
+ this.client = next;
246
+ this.bucketId = bucketId;
247
+ try {
248
+ await old.close();
249
+ } catch {
250
+ /* best-effort — the old store's handle is released on unload regardless */
251
+ }
252
+ this.logger.info(
253
+ { bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
254
+ 'Switched local store bucket'
255
+ );
256
+ }
257
+
258
+ /**
259
+ * Open `storeUrl` on `client` with tiered recovery:
260
+ * tier 1 retries the same store (transient idb-handle races — preserves the
261
+ * cache), tier 2 drops THIS bucket's IndexedDB store and reconnects fresh,
262
+ * tier 3 falls back to `mem://` for the session. Only ever drops the bucket
263
+ * being opened — other users' buckets hold their own caches AND un-pushed
264
+ * mutation outboxes, which must survive another bucket's corruption.
265
+ */
266
+ private async openWithRecovery(
267
+ client: Surreal,
268
+ storeUrl: string,
269
+ namespace: string,
270
+ database: string,
271
+ bucketId: string,
272
+ store: string
273
+ ): Promise<void> {
274
+ try {
275
+ await this.openStore(client, storeUrl, namespace, database);
87
276
  this.logger.info(
88
- { Category: 'spooky-client::LocalDatabaseService::connect' },
277
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
89
278
  'Connected to local database'
90
279
  );
280
+ return;
91
281
  } catch (err) {
282
+ // A persistent (IndexedDB) local store can fail to open if it was left
283
+ // corrupt or version-incompatible by a prior session/crash/engine bump.
284
+ // The local store is only a cache (everything re-syncs from the server),
285
+ // so recover by dropping it and reconnecting rather than bricking startup.
286
+ if (store === 'memory' || !isLocalStoreOpenError(err)) {
287
+ this.logger.error(
288
+ { err, Category: 'sp00ky-client::LocalDatabaseService::connect' },
289
+ 'Failed to connect to local database'
290
+ );
291
+ throw err;
292
+ }
293
+ this.logger.warn(
294
+ { err, Category: 'sp00ky-client::LocalDatabaseService::connect' },
295
+ 'Local IndexedDB store failed to open; retrying before clearing'
296
+ );
297
+ }
298
+
299
+ // Tier 1 — RETRY the SAME store WITHOUT dropping. The idb open/`use` failure
300
+ // is often transient (a not-yet-released handle from the previous page, or a
301
+ // first-open WAL-recovery race), not real corruption. Closing and reopening
302
+ // frequently succeeds — and crucially PRESERVES the cache, so a warm load
303
+ // stays warm. Dropping the store every time (the old behavior) silently wiped
304
+ // the cache on every reload, making warm loads as slow as cold ones.
305
+ for (let attempt = 1; attempt <= 2; attempt++) {
306
+ try {
307
+ await client.close();
308
+ } catch {
309
+ /* ignore */
310
+ }
311
+ await delay(150 * attempt);
312
+ try {
313
+ await this.openStore(client, storeUrl, namespace, database);
314
+ this.logger.info(
315
+ { attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
316
+ 'Connected to local database on retry (cache preserved)'
317
+ );
318
+ return;
319
+ } catch (retryErr) {
320
+ this.logger.warn(
321
+ { err: retryErr, attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
322
+ 'Local store retry failed'
323
+ );
324
+ }
325
+ }
326
+
327
+ // Tier 2 — the store is genuinely unopenable; drop THIS bucket and reconnect
328
+ // fresh. This loses the bucket's cache (re-syncs from the server), so it's
329
+ // the last resort before in-memory.
330
+ try {
331
+ await client.close();
332
+ } catch {
333
+ /* ignore — closing a half-open connection is best-effort */
334
+ }
335
+ await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
336
+
337
+ try {
338
+ await this.openStore(client, storeUrl, namespace, database);
339
+ this.logger.info(
340
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
341
+ 'Reconnected to local database after clearing the corrupt store'
342
+ );
343
+ } catch (retryErr) {
344
+ // Last resort: run in-memory so the app still loads. No local persistence
345
+ // this session; the freshly-dropped IndexedDB is recreated cleanly next
346
+ // load, and all data re-syncs from the server regardless.
92
347
  this.logger.error(
93
- { err, Category: 'spooky-client::LocalDatabaseService::connect' },
94
- 'Failed to connect to local database'
348
+ { err: retryErr, Category: 'sp00ky-client::LocalDatabaseService::connect' },
349
+ 'Local store still failing after clear; falling back to in-memory'
95
350
  );
96
- throw err;
351
+ try {
352
+ await client.close();
353
+ } catch {
354
+ /* ignore */
355
+ }
356
+ await this.openStore(client, 'mem://', namespace, database);
357
+ this.logger.warn(
358
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
359
+ 'Connected to local database (in-memory fallback)'
360
+ );
361
+ }
362
+ }
363
+
364
+ private unloadCloseRegistered = false;
365
+
366
+ /**
367
+ * Close the local DB on page unload so the SurrealDB-WASM worker releases its
368
+ * IndexedDB connection cleanly. Without this, the previous page's connection
369
+ * lingers; the next load's `client.connect` opens the store but the first
370
+ * write transaction in `client.use` hits an "IndexedDB error" — which then
371
+ * (mis)triggered the corrupt-store recovery and WIPED the cache on every
372
+ * reload, making warm loads as slow as cold ones. `pagehide` is the reliable
373
+ * unload signal (fires on bfcache + normal navigation); `close()` is async but
374
+ * the WASM worker initiates the IndexedDB connection teardown synchronously.
375
+ * Also closes a mid-switch incoming client so its fresh handle doesn't linger.
376
+ */
377
+ private registerUnloadClose(): void {
378
+ if (this.unloadCloseRegistered || typeof window === 'undefined') return;
379
+ this.unloadCloseRegistered = true;
380
+ const close = () => {
381
+ try {
382
+ void this.client.close();
383
+ } catch {
384
+ /* best-effort */
385
+ }
386
+ try {
387
+ void this.pendingSwitchClient?.close();
388
+ } catch {
389
+ /* best-effort */
390
+ }
391
+ };
392
+ window.addEventListener('pagehide', close);
393
+ window.addEventListener('beforeunload', close);
394
+ }
395
+
396
+ private async openStore(
397
+ client: Surreal,
398
+ storeUrl: string,
399
+ namespace: string,
400
+ database: string
401
+ ): Promise<void> {
402
+ this.logger.debug(
403
+ { storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
404
+ '[LocalDatabaseService] Calling client.connect'
405
+ );
406
+ await client.connect(storeUrl, {});
407
+ this.logger.debug(
408
+ { namespace, database, Category: 'sp00ky-client::LocalDatabaseService::connect' },
409
+ '[LocalDatabaseService] client.connect returned. Calling client.use'
410
+ );
411
+ await client.use({ namespace, database });
412
+ this.logger.debug(
413
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
414
+ '[LocalDatabaseService] client.use returned'
415
+ );
416
+ }
417
+ }
418
+
419
+ function delay(ms: number): Promise<void> {
420
+ return new Promise((resolve) => setTimeout(resolve, ms));
421
+ }
422
+
423
+ /** True for the SurrealDB-WASM error raised when its IndexedDB-backed key-value
424
+ * store can't be opened (corrupt / version-incompatible / blocked). Exported
425
+ * for unit testing the error-message match. */
426
+ export function isLocalStoreOpenError(err: unknown): boolean {
427
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
428
+ return (
429
+ msg.includes('indexeddb') ||
430
+ msg.includes('idb error') ||
431
+ msg.includes('key-value store')
432
+ );
433
+ }
434
+
435
+ /** Best-effort delete of ONE bucket's IndexedDB store(s). SurrealDB-WASM backs
436
+ * `indxdb://<name>` with one or more IndexedDB databases whose names include
437
+ * `<name>`. Scoped to the given store name — never wipe by the bare `sp00ky`
438
+ * substring, that would take every user's bucket (and their un-pushed mutation
439
+ * outboxes) down with one corrupt store. Resolves even on error/blocked so
440
+ * startup can proceed. No-op outside a browser. Exported for unit tests. */
441
+ export async function dropLocalIndexedDbStores(logger: Logger, storeName: string): Promise<void> {
442
+ if (typeof indexedDB === 'undefined') return;
443
+ try {
444
+ let names: string[] = [];
445
+ if (typeof indexedDB.databases === 'function') {
446
+ const dbs = await indexedDB.databases();
447
+ names = dbs
448
+ .map((d) => d.name)
449
+ .filter((n): n is string => !!n && matchesBucketStore(n, storeName));
97
450
  }
451
+ // Fall back to the known store name if enumeration is unavailable/empty.
452
+ if (names.length === 0) names = [storeName];
453
+ await Promise.all(names.map(deleteIndexedDb));
454
+ logger.info(
455
+ { names, Category: 'sp00ky-client::LocalDatabaseService::connect' },
456
+ 'Cleared local IndexedDB store(s)'
457
+ );
458
+ } catch (e) {
459
+ logger.warn(
460
+ { err: e, Category: 'sp00ky-client::LocalDatabaseService::connect' },
461
+ 'Failed to enumerate/clear IndexedDB; proceeding anyway'
462
+ );
98
463
  }
99
464
  }
465
+
466
+ /** True when idb database `name` belongs to the bucket store `storeName` —
467
+ * exact match or a derived name (`<storeName>`, `<storeName>-*`, `*<storeName>*`
468
+ * with a non-alphanumeric boundary so `sp00ky-abc` never matches
469
+ * `sp00ky-abcdef`'s store). Exported for unit tests. */
470
+ export function matchesBucketStore(name: string, storeName: string): boolean {
471
+ const lower = name.toLowerCase();
472
+ const target = storeName.toLowerCase();
473
+ const idx = lower.indexOf(target);
474
+ if (idx === -1) return false;
475
+ const after = lower[idx + target.length];
476
+ return after === undefined || !/[a-z0-9_]/.test(after);
477
+ }
478
+
479
+ /** Nuke EVERY sp00ky local bucket on this device (manual full reset only —
480
+ * the automated corruption recovery is scoped to one bucket). */
481
+ export async function dropAllSp00kyIndexedDbStores(logger: Logger): Promise<void> {
482
+ if (typeof indexedDB === 'undefined') return;
483
+ try {
484
+ let names: string[] = [];
485
+ if (typeof indexedDB.databases === 'function') {
486
+ const dbs = await indexedDB.databases();
487
+ names = dbs
488
+ .map((d) => d.name)
489
+ .filter((n): n is string => !!n && n.toLowerCase().includes('sp00ky'));
490
+ }
491
+ if (names.length === 0) names = ['sp00ky'];
492
+ await Promise.all(names.map(deleteIndexedDb));
493
+ logger.info(
494
+ { names, Category: 'sp00ky-client::LocalDatabaseService::reset' },
495
+ 'Cleared ALL sp00ky IndexedDB stores'
496
+ );
497
+ } catch (e) {
498
+ logger.warn(
499
+ { err: e, Category: 'sp00ky-client::LocalDatabaseService::reset' },
500
+ 'Failed to enumerate/clear IndexedDB; proceeding anyway'
501
+ );
502
+ }
503
+ }
504
+
505
+ function deleteIndexedDb(name: string): Promise<void> {
506
+ return new Promise((resolve) => {
507
+ try {
508
+ const req = indexedDB.deleteDatabase(name);
509
+ req.onsuccess = () => resolve();
510
+ req.onerror = () => resolve();
511
+ req.onblocked = () => resolve();
512
+ } catch {
513
+ resolve();
514
+ }
515
+ });
516
+ }