@spooky-sync/core 0.0.1-canary.31 → 0.0.1-canary.310

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 (257) hide show
  1. package/AGENTS.md +81 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2026 -137
  4. package/dist/index.js +14956 -2434
  5. package/dist/live.d.ts +141 -0
  6. package/dist/live.js +709 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/otel/index.js +3 -3
  9. package/dist/pure.d.ts +329 -0
  10. package/dist/pure.js +24 -0
  11. package/dist/sqlite-open.js +358 -0
  12. package/dist/sqlite-worker.d.ts +1 -0
  13. package/dist/sqlite-worker.js +439 -0
  14. package/dist/sw.d.ts +207 -0
  15. package/dist/sw.js +393 -0
  16. package/dist/tabs-broker-worker.d.ts +8 -0
  17. package/dist/tabs-broker-worker.js +472 -0
  18. package/dist/types.d.ts +1765 -38
  19. package/dist/worker-edges.js +423 -0
  20. package/dist/worker-impersonation.js +60 -0
  21. package/dist/worker-ref-tables.d.ts +46 -0
  22. package/dist/worker-types.d.ts +112 -0
  23. package/dist/worker-types.js +73 -0
  24. package/package.json +27 -7
  25. package/scripts/check-broker-bundle.mjs +33 -0
  26. package/scripts/check-worker-entries.mjs +172 -0
  27. package/skills/sp00ky-core/SKILL.md +31 -6
  28. package/skills/sp00ky-core/references/config.md +6 -0
  29. package/src/boot/auth-flip.saga.test.ts +135 -0
  30. package/src/boot/auth-flip.saga.ts +77 -0
  31. package/src/boot/boot.saga.test.ts +158 -0
  32. package/src/boot/boot.saga.ts +131 -0
  33. package/src/boot/bucket-switch.saga.test.ts +187 -0
  34. package/src/boot/bucket-switch.saga.ts +133 -0
  35. package/src/boot/preload.saga.test.ts +51 -0
  36. package/src/boot/preload.saga.ts +31 -0
  37. package/src/bucket-blurhash.test.ts +148 -0
  38. package/src/build-globals.d.ts +12 -0
  39. package/src/client/bucket-handle.test.ts +117 -0
  40. package/src/client/bucket-handle.ts +227 -0
  41. package/src/client/router.test.ts +58 -0
  42. package/src/client/router.ts +100 -0
  43. package/src/client/runtime.test.ts +195 -0
  44. package/src/client/runtime.ts +296 -0
  45. package/src/client/services.ts +370 -0
  46. package/src/client/sp00ky-client.test.ts +303 -0
  47. package/src/client/sp00ky-client.ts +586 -0
  48. package/src/events/events.test.ts +2 -1
  49. package/src/events/index.ts +3 -0
  50. package/src/index.ts +69 -1
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +80 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +161 -0
  55. package/src/kernel/events.ts +57 -0
  56. package/src/kernel/interpreter.test.ts +116 -0
  57. package/src/kernel/interpreter.ts +148 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +478 -0
  61. package/src/live/index.ts +1013 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +141 -0
  65. package/src/modules/auth/events/index.ts +9 -2
  66. package/src/modules/auth/impersonation-banner.ts +443 -0
  67. package/src/modules/auth/impersonation.test.ts +355 -0
  68. package/src/modules/auth/impersonation.ts +179 -0
  69. package/src/modules/auth/index.ts +386 -17
  70. package/src/modules/crdt/crdt-field.ts +294 -0
  71. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  72. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  73. package/src/modules/crdt/index.ts +463 -0
  74. package/src/modules/crdt/loro-loader.ts +25 -0
  75. package/src/modules/devtools/flags.ts +349 -0
  76. package/src/modules/devtools/index.ts +746 -95
  77. package/src/modules/devtools/mutations.test.ts +92 -0
  78. package/src/modules/devtools/mutations.ts +160 -0
  79. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  80. package/src/modules/devtools/state-shape.test.ts +263 -0
  81. package/src/modules/devtools/storage-info.test.ts +79 -0
  82. package/src/modules/devtools/storage-info.ts +168 -0
  83. package/src/modules/devtools/versions.test.ts +74 -0
  84. package/src/modules/devtools/versions.ts +110 -0
  85. package/src/modules/feature-flag/index.test.ts +251 -0
  86. package/src/modules/feature-flag/index.ts +316 -0
  87. package/src/modules/ref-tables.test.ts +91 -0
  88. package/src/modules/ref-tables.ts +88 -0
  89. package/src/modules/web-push/index.test.ts +824 -0
  90. package/src/modules/web-push/index.ts +1027 -0
  91. package/src/mutation/jobs.test.ts +25 -0
  92. package/src/mutation/jobs.ts +41 -0
  93. package/src/mutation/mutation-id.test.ts +37 -0
  94. package/src/mutation/mutation-id.ts +35 -0
  95. package/src/mutation/pending-writes.integration.test.ts +175 -0
  96. package/src/mutation/push.saga.test.ts +285 -0
  97. package/src/mutation/push.saga.ts +217 -0
  98. package/src/mutation/rows.test.ts +231 -0
  99. package/src/mutation/rows.ts +427 -0
  100. package/src/mutation/tray.saga.test.ts +63 -0
  101. package/src/mutation/tray.saga.ts +48 -0
  102. package/src/mutation/write.saga.test.ts +316 -0
  103. package/src/mutation/write.saga.ts +268 -0
  104. package/src/otel/index.ts +10 -7
  105. package/src/pure.ts +65 -0
  106. package/src/push/types.ts +174 -0
  107. package/src/query/env.test.ts +23 -0
  108. package/src/query/env.ts +56 -0
  109. package/src/query/fetch.saga.test.ts +199 -0
  110. package/src/query/fetch.saga.ts +120 -0
  111. package/src/query/hash.test.ts +14 -0
  112. package/src/query/hash.ts +18 -0
  113. package/src/query/id-set-plan.test.ts +132 -0
  114. package/src/query/lifecycle.saga.test.ts +274 -0
  115. package/src/query/lifecycle.saga.ts +159 -0
  116. package/src/query/materialize.saga.test.ts +115 -0
  117. package/src/query/materialize.saga.ts +84 -0
  118. package/src/query/materialize.test.ts +58 -0
  119. package/src/query/materialize.ts +57 -0
  120. package/src/query/membership.saga.test.ts +350 -0
  121. package/src/query/membership.saga.ts +278 -0
  122. package/src/query/membership.test.ts +118 -0
  123. package/src/query/membership.ts +201 -0
  124. package/src/query/register.saga.test.ts +293 -0
  125. package/src/query/register.saga.ts +226 -0
  126. package/src/query/render-set.test.ts +47 -0
  127. package/src/query/render-set.ts +71 -0
  128. package/src/query/sql.test.ts +63 -0
  129. package/src/query/sql.ts +93 -0
  130. package/src/query/window-query.test.ts +70 -0
  131. package/src/query/window-query.ts +195 -0
  132. package/src/services/blobs/blob-cache.test.ts +359 -0
  133. package/src/services/blobs/blob-cache.ts +603 -0
  134. package/src/services/blobs/blob-manifest.ts +227 -0
  135. package/src/services/blobs/blob-store.test.ts +77 -0
  136. package/src/services/blobs/blob-store.ts +359 -0
  137. package/src/services/blobs/blob.fixture.ts +90 -0
  138. package/src/services/blobs/index.ts +70 -0
  139. package/src/services/database/cache-engine.ts +199 -0
  140. package/src/services/database/connection-supervisor.test.ts +318 -0
  141. package/src/services/database/connection-supervisor.ts +422 -0
  142. package/src/services/database/database.query-timeout.test.ts +140 -0
  143. package/src/services/database/database.responses.test.ts +43 -0
  144. package/src/services/database/database.ts +146 -61
  145. package/src/services/database/engine-factory.ts +33 -0
  146. package/src/services/database/errors.ts +34 -0
  147. package/src/services/database/events/index.ts +2 -1
  148. package/src/services/database/index.ts +7 -0
  149. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  150. package/src/services/database/local-migrator.integration.test.ts +110 -0
  151. package/src/services/database/local-migrator.ts +59 -16
  152. package/src/services/database/local.test.ts +64 -0
  153. package/src/services/database/local.ts +487 -63
  154. package/src/services/database/plan-render.test.ts +159 -0
  155. package/src/services/database/plan-render.ts +108 -0
  156. package/src/services/database/relation-resolver.test.ts +467 -0
  157. package/src/services/database/relation-resolver.ts +0 -0
  158. package/src/services/database/remote.ts +213 -6
  159. package/src/services/database/sqlite-cache-engine.test.ts +617 -0
  160. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  161. package/src/services/database/sqlite-cache-engine.ts +1372 -0
  162. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  163. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  164. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  165. package/src/services/database/sqlite-lock-verify.ts +45 -0
  166. package/src/services/database/sqlite-open.test.ts +150 -0
  167. package/src/services/database/sqlite-open.ts +164 -0
  168. package/src/services/database/sqlite-plan-sql.test.ts +139 -0
  169. package/src/services/database/sqlite-plan-sql.ts +179 -0
  170. package/src/services/database/sqlite-projection.test.ts +121 -0
  171. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  172. package/src/services/database/sqlite-select.test.ts +246 -0
  173. package/src/services/database/sqlite-select.ts +131 -0
  174. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  175. package/src/services/database/sqlite-transport.ts +224 -0
  176. package/src/services/database/sqlite-worker.ts +437 -0
  177. package/src/services/database/surql-translate.ts +416 -0
  178. package/src/services/database/surreal-cache-engine.ts +161 -0
  179. package/src/services/logger/index.test.ts +132 -0
  180. package/src/services/logger/index.ts +189 -7
  181. package/src/services/persistence/localstorage.ts +2 -2
  182. package/src/services/persistence/resilient.ts +10 -3
  183. package/src/services/persistence/surrealdb.ts +4 -4
  184. package/src/services/stream-processor/index.ts +779 -67
  185. package/src/services/stream-processor/permissions.test.ts +47 -0
  186. package/src/services/stream-processor/permissions.ts +53 -0
  187. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  188. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  189. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  190. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  191. package/src/services/stream-processor/wasm-types.ts +58 -2
  192. package/src/services/tabs/broker-client.ts +283 -0
  193. package/src/services/tabs/broker.test.ts +327 -0
  194. package/src/services/tabs/coordinator.test.ts +386 -0
  195. package/src/services/tabs/coordinator.ts +638 -0
  196. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  197. package/src/services/tabs/leader-locks.ts +75 -0
  198. package/src/services/tabs/protocol.ts +262 -0
  199. package/src/services/tabs/support.ts +36 -0
  200. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  201. package/src/sp00ky.ts +5 -395
  202. package/src/state/client-state.ts +200 -0
  203. package/src/state/lifecycle.test.ts +118 -0
  204. package/src/state/lifecycle.ts +86 -0
  205. package/src/state/reducers.test.ts +304 -0
  206. package/src/state/reducers.ts +526 -0
  207. package/src/state/selectors.test.ts +167 -0
  208. package/src/state/selectors.ts +216 -0
  209. package/src/sw/index.test.ts +582 -0
  210. package/src/sw/index.ts +607 -0
  211. package/src/sw/store.ts +96 -0
  212. package/src/sync/connection.saga.test.ts +86 -0
  213. package/src/sync/connection.saga.ts +85 -0
  214. package/src/sync/live.saga.test.ts +178 -0
  215. package/src/sync/live.saga.ts +107 -0
  216. package/src/sync/policy.health.test.ts +56 -0
  217. package/src/sync/policy.test.ts +659 -0
  218. package/src/sync/policy.ts +502 -0
  219. package/src/sync/poll.saga.test.ts +51 -0
  220. package/src/sync/poll.saga.ts +36 -0
  221. package/src/sync/tabs.saga.test.ts +78 -0
  222. package/src/sync/tabs.saga.ts +96 -0
  223. package/src/testing/adapters.ts +133 -0
  224. package/src/testing/build.ts +63 -0
  225. package/src/testing/fake-services.ts +48 -0
  226. package/src/testing/run-pure.test.ts +92 -0
  227. package/src/testing/run-pure.ts +128 -0
  228. package/src/testing/services.ts +17 -0
  229. package/src/types.ts +624 -10
  230. package/src/utils/blurhash.ts +90 -0
  231. package/src/utils/edges.ts +39 -0
  232. package/src/utils/error-classification.test.ts +54 -0
  233. package/src/utils/error-classification.ts +25 -0
  234. package/src/utils/index.ts +78 -12
  235. package/src/utils/parser.test.ts +67 -102
  236. package/src/utils/parser.ts +64 -2
  237. package/src/utils/semver.test.ts +32 -0
  238. package/src/utils/semver.ts +30 -0
  239. package/src/utils/sha256.ts +15 -0
  240. package/src/utils/surql.ts +30 -18
  241. package/src/utils/utils.test.ts +3 -2
  242. package/tsdown.config.ts +117 -3
  243. package/vitest.config.ts +48 -0
  244. package/src/modules/cache/index.ts +0 -241
  245. package/src/modules/cache/types.ts +0 -19
  246. package/src/modules/data/data.test.ts +0 -58
  247. package/src/modules/data/index.ts +0 -879
  248. package/src/modules/sync/engine.ts +0 -173
  249. package/src/modules/sync/events/index.ts +0 -77
  250. package/src/modules/sync/index.ts +0 -3
  251. package/src/modules/sync/queue/index.ts +0 -2
  252. package/src/modules/sync/queue/queue-down.ts +0 -89
  253. package/src/modules/sync/queue/queue-up.ts +0 -223
  254. package/src/modules/sync/scheduler.ts +0 -84
  255. package/src/modules/sync/sync.ts +0 -421
  256. package/src/modules/sync/utils.test.ts +0 -311
  257. package/src/modules/sync/utils.ts +0 -167
@@ -1,99 +1,523 @@
1
- import { applyDiagnostics, DateTime, Diagnostic, RecordId, Surreal } from 'surrealdb';
2
- import { createWasmWorkerEngines } from '@surrealdb/wasm';
3
- import { Sp00kyConfig } 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
90
  private config: Sp00kyConfig<any>['database'];
11
91
  protected eventType = DatabaseEventTypes.LocalQuery;
12
92
 
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
+
13
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: 'sp00ky-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);
115
+ }
116
+
117
+ protected override timeoutError(query: string): Error {
118
+ return new LocalOpTimeoutError(query.slice(0, 80), this.queryTimeoutMs);
53
119
  }
54
120
 
55
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: 'sp00ky-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://sp00ky';
68
- this.logger.debug(
69
- { storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
70
- '[LocalDatabaseService] Calling client.connect'
71
- );
72
- await this.client.connect(storeUrl, {});
73
- this.logger.debug(
74
- { namespace, database, Category: 'sp00ky-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: 'sp00ky-client::LocalDatabaseService::connect' },
84
- '[LocalDatabaseService] client.use returned'
237
+ bucketId,
238
+ store
85
239
  );
240
+ } finally {
241
+ this.pendingSwitchClient = null;
242
+ }
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
+ /** See `LocalStore.dropBucket`. A memory store keeps nothing to delete. */
259
+ async dropBucket(bucketId: string): Promise<void> {
260
+ if (bucketId === this.bucketId) throw new Error('Cannot drop the open bucket.');
261
+ if ((this.getConfig().store ?? 'memory') === 'memory') return;
262
+ await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
263
+ }
86
264
 
265
+ /**
266
+ * Open `storeUrl` on `client` with tiered recovery:
267
+ * tier 1 retries the same store (transient idb-handle races — preserves the
268
+ * cache), tier 2 drops THIS bucket's IndexedDB store and reconnects fresh,
269
+ * tier 3 falls back to `mem://` for the session. Only ever drops the bucket
270
+ * being opened — other users' buckets hold their own caches AND un-pushed
271
+ * mutation outboxes, which must survive another bucket's corruption.
272
+ */
273
+ private async openWithRecovery(
274
+ client: Surreal,
275
+ storeUrl: string,
276
+ namespace: string,
277
+ database: string,
278
+ bucketId: string,
279
+ store: string
280
+ ): Promise<void> {
281
+ try {
282
+ await this.openStore(client, storeUrl, namespace, database);
87
283
  this.logger.info(
88
284
  { Category: 'sp00ky-client::LocalDatabaseService::connect' },
89
285
  'Connected to local database'
90
286
  );
287
+ return;
91
288
  } catch (err) {
92
- this.logger.error(
289
+ // A persistent (IndexedDB) local store can fail to open if it was left
290
+ // corrupt or version-incompatible by a prior session/crash/engine bump.
291
+ // The local store is only a cache (everything re-syncs from the server),
292
+ // so recover by dropping it and reconnecting rather than bricking startup.
293
+ if (store === 'memory' || !isLocalStoreOpenError(err)) {
294
+ this.logger.error(
295
+ { err, Category: 'sp00ky-client::LocalDatabaseService::connect' },
296
+ 'Failed to connect to local database'
297
+ );
298
+ throw err;
299
+ }
300
+ this.logger.warn(
93
301
  { err, Category: 'sp00ky-client::LocalDatabaseService::connect' },
94
- 'Failed to connect to local database'
302
+ 'Local IndexedDB store failed to open; retrying before clearing'
303
+ );
304
+ }
305
+
306
+ // Tier 1 — RETRY the SAME store WITHOUT dropping. The idb open/`use` failure
307
+ // is often transient (a not-yet-released handle from the previous page, or a
308
+ // first-open WAL-recovery race), not real corruption. Closing and reopening
309
+ // frequently succeeds — and crucially PRESERVES the cache, so a warm load
310
+ // stays warm. Dropping the store every time (the old behavior) silently wiped
311
+ // the cache on every reload, making warm loads as slow as cold ones.
312
+ for (let attempt = 1; attempt <= 2; attempt++) {
313
+ try {
314
+ await client.close();
315
+ } catch {
316
+ /* ignore */
317
+ }
318
+ await delay(150 * attempt);
319
+ try {
320
+ await this.openStore(client, storeUrl, namespace, database);
321
+ this.logger.info(
322
+ { attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
323
+ 'Connected to local database on retry (cache preserved)'
324
+ );
325
+ return;
326
+ } catch (retryErr) {
327
+ this.logger.warn(
328
+ { err: retryErr, attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
329
+ 'Local store retry failed'
330
+ );
331
+ }
332
+ }
333
+
334
+ // Tier 2 — the store is genuinely unopenable; drop THIS bucket and reconnect
335
+ // fresh. This loses the bucket's cache (re-syncs from the server), so it's
336
+ // the last resort before in-memory.
337
+ try {
338
+ await client.close();
339
+ } catch {
340
+ /* ignore — closing a half-open connection is best-effort */
341
+ }
342
+ await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
343
+
344
+ try {
345
+ await this.openStore(client, storeUrl, namespace, database);
346
+ this.logger.info(
347
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
348
+ 'Reconnected to local database after clearing the corrupt store'
349
+ );
350
+ } catch (retryErr) {
351
+ // Last resort: run in-memory so the app still loads. No local persistence
352
+ // this session; the freshly-dropped IndexedDB is recreated cleanly next
353
+ // load, and all data re-syncs from the server regardless.
354
+ this.logger.error(
355
+ { err: retryErr, Category: 'sp00ky-client::LocalDatabaseService::connect' },
356
+ 'Local store still failing after clear; falling back to in-memory'
357
+ );
358
+ try {
359
+ await client.close();
360
+ } catch {
361
+ /* ignore */
362
+ }
363
+ await this.openStore(client, 'mem://', namespace, database);
364
+ this.logger.warn(
365
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
366
+ 'Connected to local database (in-memory fallback)'
95
367
  );
96
- throw err;
97
368
  }
98
369
  }
370
+
371
+ private unloadCloseRegistered = false;
372
+
373
+ /**
374
+ * Close the local DB on page unload so the SurrealDB-WASM worker releases its
375
+ * IndexedDB connection cleanly. Without this, the previous page's connection
376
+ * lingers; the next load's `client.connect` opens the store but the first
377
+ * write transaction in `client.use` hits an "IndexedDB error" — which then
378
+ * (mis)triggered the corrupt-store recovery and WIPED the cache on every
379
+ * reload, making warm loads as slow as cold ones. `pagehide` is the reliable
380
+ * unload signal (fires on bfcache + normal navigation); `close()` is async but
381
+ * the WASM worker initiates the IndexedDB connection teardown synchronously.
382
+ * Also closes a mid-switch incoming client so its fresh handle doesn't linger.
383
+ */
384
+ private registerUnloadClose(): void {
385
+ if (this.unloadCloseRegistered || typeof window === 'undefined') return;
386
+ this.unloadCloseRegistered = true;
387
+ const close = () => {
388
+ try {
389
+ void this.client.close();
390
+ } catch {
391
+ /* best-effort */
392
+ }
393
+ try {
394
+ void this.pendingSwitchClient?.close();
395
+ } catch {
396
+ /* best-effort */
397
+ }
398
+ };
399
+ window.addEventListener('pagehide', close);
400
+ window.addEventListener('beforeunload', close);
401
+ }
402
+
403
+ private async openStore(
404
+ client: Surreal,
405
+ storeUrl: string,
406
+ namespace: string,
407
+ database: string
408
+ ): Promise<void> {
409
+ this.logger.debug(
410
+ { storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
411
+ '[LocalDatabaseService] Calling client.connect'
412
+ );
413
+ await client.connect(storeUrl, {});
414
+ this.logger.debug(
415
+ { namespace, database, Category: 'sp00ky-client::LocalDatabaseService::connect' },
416
+ '[LocalDatabaseService] client.connect returned. Calling client.use'
417
+ );
418
+ await client.use({ namespace, database });
419
+ this.logger.debug(
420
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
421
+ '[LocalDatabaseService] client.use returned'
422
+ );
423
+ }
424
+ }
425
+
426
+ function delay(ms: number): Promise<void> {
427
+ return new Promise((resolve) => setTimeout(resolve, ms));
428
+ }
429
+
430
+ /** True for the SurrealDB-WASM error raised when its IndexedDB-backed key-value
431
+ * store can't be opened (corrupt / version-incompatible / blocked). Exported
432
+ * for unit testing the error-message match. */
433
+ export function isLocalStoreOpenError(err: unknown): boolean {
434
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
435
+ return (
436
+ msg.includes('indexeddb') ||
437
+ msg.includes('idb error') ||
438
+ msg.includes('key-value store')
439
+ );
440
+ }
441
+
442
+ /** Best-effort delete of ONE bucket's IndexedDB store(s). SurrealDB-WASM backs
443
+ * `indxdb://<name>` with one or more IndexedDB databases whose names include
444
+ * `<name>`. Scoped to the given store name — never wipe by the bare `sp00ky`
445
+ * substring, that would take every user's bucket (and their un-pushed mutation
446
+ * outboxes) down with one corrupt store. Resolves even on error/blocked so
447
+ * startup can proceed. No-op outside a browser. Exported for unit tests. */
448
+ export async function dropLocalIndexedDbStores(logger: Logger, storeName: string): Promise<void> {
449
+ if (typeof indexedDB === 'undefined') return;
450
+ try {
451
+ let names: string[] = [];
452
+ if (typeof indexedDB.databases === 'function') {
453
+ const dbs = await indexedDB.databases();
454
+ names = dbs
455
+ .map((d) => d.name)
456
+ .filter((n): n is string => !!n && matchesBucketStore(n, storeName));
457
+ }
458
+ // Fall back to the known store name if enumeration is unavailable/empty.
459
+ if (names.length === 0) names = [storeName];
460
+ await Promise.all(names.map(deleteIndexedDb));
461
+ logger.info(
462
+ { names, Category: 'sp00ky-client::LocalDatabaseService::connect' },
463
+ 'Cleared local IndexedDB store(s)'
464
+ );
465
+ } catch (e) {
466
+ logger.warn(
467
+ { err: e, Category: 'sp00ky-client::LocalDatabaseService::connect' },
468
+ 'Failed to enumerate/clear IndexedDB; proceeding anyway'
469
+ );
470
+ }
471
+ }
472
+
473
+ /** True when idb database `name` belongs to the bucket store `storeName` —
474
+ * exact match or a derived name (`<storeName>`, `<storeName>-*`, `*<storeName>*`
475
+ * with a non-alphanumeric boundary so `sp00ky-abc` never matches
476
+ * `sp00ky-abcdef`'s store). Exported for unit tests. */
477
+ export function matchesBucketStore(name: string, storeName: string): boolean {
478
+ const lower = name.toLowerCase();
479
+ const target = storeName.toLowerCase();
480
+ const idx = lower.indexOf(target);
481
+ if (idx === -1) return false;
482
+ const after = lower[idx + target.length];
483
+ return after === undefined || !/[a-z0-9_]/.test(after);
484
+ }
485
+
486
+ /** Nuke EVERY sp00ky local bucket on this device (manual full reset only —
487
+ * the automated corruption recovery is scoped to one bucket). */
488
+ export async function dropAllSp00kyIndexedDbStores(logger: Logger): Promise<void> {
489
+ if (typeof indexedDB === 'undefined') return;
490
+ try {
491
+ let names: string[] = [];
492
+ if (typeof indexedDB.databases === 'function') {
493
+ const dbs = await indexedDB.databases();
494
+ names = dbs
495
+ .map((d) => d.name)
496
+ .filter((n): n is string => !!n && n.toLowerCase().includes('sp00ky'));
497
+ }
498
+ if (names.length === 0) names = ['sp00ky'];
499
+ await Promise.all(names.map(deleteIndexedDb));
500
+ logger.info(
501
+ { names, Category: 'sp00ky-client::LocalDatabaseService::reset' },
502
+ 'Cleared ALL sp00ky IndexedDB stores'
503
+ );
504
+ } catch (e) {
505
+ logger.warn(
506
+ { err: e, Category: 'sp00ky-client::LocalDatabaseService::reset' },
507
+ 'Failed to enumerate/clear IndexedDB; proceeding anyway'
508
+ );
509
+ }
510
+ }
511
+
512
+ function deleteIndexedDb(name: string): Promise<void> {
513
+ return new Promise((resolve) => {
514
+ try {
515
+ const req = indexedDB.deleteDatabase(name);
516
+ req.onsuccess = () => resolve();
517
+ req.onerror = () => resolve();
518
+ req.onblocked = () => resolve();
519
+ } catch {
520
+ resolve();
521
+ }
522
+ });
99
523
  }