@spooky-sync/core 0.0.1-canary.97 → 1.0.0-beta.1

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 (261) hide show
  1. package/AGENTS.md +57 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2096 -929
  4. package/dist/index.js +18217 -5019
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/sqlite-open.js +392 -0
  11. package/dist/sqlite-worker.d.ts +1 -0
  12. package/dist/sqlite-worker.js +439 -0
  13. package/dist/sw.d.ts +207 -0
  14. package/dist/sw.js +393 -0
  15. package/dist/tabs-broker-worker.d.ts +8 -0
  16. package/dist/tabs-broker-worker.js +477 -0
  17. package/dist/types.d.ts +1968 -82
  18. package/dist/worker-edges.js +498 -0
  19. package/dist/worker-impersonation.js +60 -0
  20. package/dist/worker-ref-tables.d.ts +48 -0
  21. package/dist/worker-types.d.ts +112 -0
  22. package/dist/worker-types.js +73 -0
  23. package/package.json +34 -8
  24. package/scripts/check-broker-bundle.mjs +33 -0
  25. package/scripts/check-worker-entries.mjs +173 -0
  26. package/skills/sp00ky-core/SKILL.md +42 -8
  27. package/skills/sp00ky-core/references/config.md +8 -2
  28. package/src/boot/auth-flip.saga.test.ts +174 -0
  29. package/src/boot/auth-flip.saga.ts +77 -0
  30. package/src/boot/boot.saga.test.ts +203 -0
  31. package/src/boot/boot.saga.ts +146 -0
  32. package/src/boot/bucket-switch.saga.test.ts +191 -0
  33. package/src/boot/bucket-switch.saga.ts +151 -0
  34. package/src/boot/preload.saga.test.ts +96 -0
  35. package/src/boot/preload.saga.ts +45 -0
  36. package/src/bucket-blurhash.test.ts +148 -0
  37. package/src/client/bucket-handle.test.ts +195 -0
  38. package/src/client/bucket-handle.ts +352 -0
  39. package/src/client/router.test.ts +59 -0
  40. package/src/client/router.ts +104 -0
  41. package/src/client/runtime.test.ts +319 -0
  42. package/src/client/runtime.ts +307 -0
  43. package/src/client/services.test.ts +74 -0
  44. package/src/client/services.ts +437 -0
  45. package/src/client/sp00ky-client.test.ts +428 -0
  46. package/src/client/sp00ky-client.ts +737 -0
  47. package/src/index.ts +78 -0
  48. package/src/kernel/constants.test.ts +19 -0
  49. package/src/kernel/constants.ts +94 -0
  50. package/src/kernel/effects.test.ts +40 -0
  51. package/src/kernel/effects.ts +171 -0
  52. package/src/kernel/events.ts +60 -0
  53. package/src/kernel/interpreter.test.ts +116 -0
  54. package/src/kernel/interpreter.ts +148 -0
  55. package/src/kernel/saga.test.ts +89 -0
  56. package/src/kernel/saga.ts +73 -0
  57. package/src/live/index.test.ts +512 -0
  58. package/src/live/index.ts +1059 -0
  59. package/src/modules/app-release/index.test.ts +125 -0
  60. package/src/modules/app-release/index.ts +209 -0
  61. package/src/modules/auth/auth.local-first.test.ts +228 -0
  62. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  63. package/src/modules/auth/events/index.ts +7 -1
  64. package/src/modules/auth/impersonation-banner.ts +443 -0
  65. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  66. package/src/modules/auth/impersonation.test.ts +377 -0
  67. package/src/modules/auth/impersonation.ts +179 -0
  68. package/src/modules/auth/index.ts +516 -34
  69. package/src/modules/channel/channel.test.ts +752 -0
  70. package/src/modules/channel/index.ts +1153 -0
  71. package/src/modules/channel/webrtc.ts +472 -0
  72. package/src/modules/crdt/acceptance.ts +75 -0
  73. package/src/modules/crdt/bytes.ts +50 -0
  74. package/src/modules/crdt/crdt-field.ts +82 -238
  75. package/src/modules/crdt/crdt.test.ts +546 -0
  76. package/src/modules/crdt/hash.ts +103 -0
  77. package/src/modules/crdt/index.ts +740 -271
  78. package/src/modules/crdt/loro-loader.ts +25 -0
  79. package/src/modules/crdt/mirror.ts +37 -0
  80. package/src/modules/devtools/flags.ts +349 -0
  81. package/src/modules/devtools/index.ts +661 -99
  82. package/src/modules/devtools/mutations.test.ts +92 -0
  83. package/src/modules/devtools/mutations.ts +160 -0
  84. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  85. package/src/modules/devtools/state-shape.test.ts +263 -0
  86. package/src/modules/devtools/storage-info.test.ts +79 -0
  87. package/src/modules/devtools/storage-info.ts +168 -0
  88. package/src/modules/devtools/versions.ts +29 -0
  89. package/src/modules/feature-flag/index.test.ts +179 -1
  90. package/src/modules/feature-flag/index.ts +117 -10
  91. package/src/modules/ref-tables.test.ts +28 -1
  92. package/src/modules/ref-tables.ts +23 -1
  93. package/src/modules/web-push/index.test.ts +824 -0
  94. package/src/modules/web-push/index.ts +1027 -0
  95. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  96. package/src/mutation/jobs.test.ts +25 -0
  97. package/src/mutation/jobs.ts +41 -0
  98. package/src/mutation/mutation-id.test.ts +37 -0
  99. package/src/mutation/mutation-id.ts +35 -0
  100. package/src/mutation/pending-writes.integration.test.ts +175 -0
  101. package/src/mutation/push.saga.test.ts +361 -0
  102. package/src/mutation/push.saga.ts +245 -0
  103. package/src/mutation/rows.test.ts +278 -0
  104. package/src/mutation/rows.ts +515 -0
  105. package/src/mutation/tray.saga.test.ts +63 -0
  106. package/src/mutation/tray.saga.ts +48 -0
  107. package/src/mutation/write.saga.test.ts +436 -0
  108. package/src/mutation/write.saga.ts +384 -0
  109. package/src/pure.ts +66 -0
  110. package/src/push/types.ts +174 -0
  111. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  112. package/src/query/env.test.ts +23 -0
  113. package/src/query/env.ts +65 -0
  114. package/src/query/fetch.saga.test.ts +199 -0
  115. package/src/query/fetch.saga.ts +120 -0
  116. package/src/query/hash.test.ts +14 -0
  117. package/src/query/hash.ts +18 -0
  118. package/src/query/id-set-plan.test.ts +132 -0
  119. package/src/query/lifecycle.saga.test.ts +274 -0
  120. package/src/query/lifecycle.saga.ts +186 -0
  121. package/src/query/list-ref-live.integration.test.ts +203 -0
  122. package/src/query/materialize.saga.test.ts +200 -0
  123. package/src/query/materialize.saga.ts +102 -0
  124. package/src/query/materialize.test.ts +58 -0
  125. package/src/query/materialize.ts +57 -0
  126. package/src/query/membership.saga.test.ts +514 -0
  127. package/src/query/membership.saga.ts +339 -0
  128. package/src/query/membership.test.ts +151 -0
  129. package/src/query/membership.ts +234 -0
  130. package/src/query/register.saga.test.ts +369 -0
  131. package/src/query/register.saga.ts +293 -0
  132. package/src/query/render-set.test.ts +47 -0
  133. package/src/query/render-set.ts +71 -0
  134. package/src/query/session-guard.integration.test.ts +304 -0
  135. package/src/query/sql.test.ts +118 -0
  136. package/src/query/sql.ts +174 -0
  137. package/src/{modules/data → query}/window-query.test.ts +22 -4
  138. package/src/{modules/data → query}/window-query.ts +86 -8
  139. package/src/services/blobs/blob-cache.test.ts +359 -0
  140. package/src/services/blobs/blob-cache.ts +603 -0
  141. package/src/services/blobs/blob-manifest.ts +227 -0
  142. package/src/services/blobs/blob-store.test.ts +77 -0
  143. package/src/services/blobs/blob-store.ts +359 -0
  144. package/src/services/blobs/blob.fixture.ts +90 -0
  145. package/src/services/blobs/index.ts +70 -0
  146. package/src/services/database/cache-engine.ts +209 -0
  147. package/src/services/database/connection-supervisor.test.ts +318 -0
  148. package/src/services/database/connection-supervisor.ts +422 -0
  149. package/src/services/database/database.query-timeout.test.ts +140 -0
  150. package/src/services/database/database.responses.test.ts +43 -0
  151. package/src/services/database/database.ts +151 -56
  152. package/src/services/database/engine-factory.ts +33 -0
  153. package/src/services/database/errors.ts +34 -0
  154. package/src/services/database/index.ts +7 -0
  155. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  156. package/src/services/database/local-migrator.integration.test.ts +110 -0
  157. package/src/services/database/local-migrator.ts +54 -9
  158. package/src/services/database/local.test.ts +117 -0
  159. package/src/services/database/local.ts +364 -74
  160. package/src/services/database/plan-render.test.ts +159 -0
  161. package/src/services/database/plan-render.ts +108 -0
  162. package/src/services/database/relation-resolver.test.ts +484 -0
  163. package/src/services/database/relation-resolver.ts +0 -0
  164. package/src/services/database/remote.ts +283 -4
  165. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  166. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  167. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  168. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  169. package/src/services/database/sqlite-column-reset.ts +91 -0
  170. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  171. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  172. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  173. package/src/services/database/sqlite-lock-verify.ts +45 -0
  174. package/src/services/database/sqlite-open.test.ts +150 -0
  175. package/src/services/database/sqlite-open.ts +164 -0
  176. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  177. package/src/services/database/sqlite-plan-sql.ts +196 -0
  178. package/src/services/database/sqlite-projection.test.ts +121 -0
  179. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  180. package/src/services/database/sqlite-select.test.ts +261 -0
  181. package/src/services/database/sqlite-select.ts +131 -0
  182. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  183. package/src/services/database/sqlite-transport.ts +229 -0
  184. package/src/services/database/sqlite-worker.ts +437 -0
  185. package/src/services/database/surql-translate.ts +417 -0
  186. package/src/services/database/surreal-cache-engine.ts +163 -0
  187. package/src/services/logger/index.test.ts +132 -0
  188. package/src/services/logger/index.ts +187 -6
  189. package/src/services/persistence/surrealdb.ts +2 -2
  190. package/src/services/stream-processor/index.ts +621 -93
  191. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  192. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  193. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  194. package/src/services/stream-processor/wasm-types.ts +41 -1
  195. package/src/services/tabs/broker-client.ts +284 -0
  196. package/src/services/tabs/broker.test.ts +381 -0
  197. package/src/services/tabs/coordinator.test.ts +386 -0
  198. package/src/services/tabs/coordinator.ts +646 -0
  199. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  200. package/src/services/tabs/leader-locks.ts +75 -0
  201. package/src/services/tabs/protocol.ts +262 -0
  202. package/src/services/tabs/support.ts +36 -0
  203. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  204. package/src/sp00ky.ts +5 -648
  205. package/src/state/client-state.ts +231 -0
  206. package/src/state/lifecycle.test.ts +184 -0
  207. package/src/state/lifecycle.ts +127 -0
  208. package/src/state/reducers.test.ts +337 -0
  209. package/src/state/reducers.ts +571 -0
  210. package/src/state/selectors.test.ts +203 -0
  211. package/src/state/selectors.ts +264 -0
  212. package/src/sw/index.test.ts +582 -0
  213. package/src/sw/index.ts +607 -0
  214. package/src/sw/store.ts +96 -0
  215. package/src/sync/connection.saga.test.ts +97 -0
  216. package/src/sync/connection.saga.ts +89 -0
  217. package/src/sync/live.saga.test.ts +229 -0
  218. package/src/sync/live.saga.ts +116 -0
  219. package/src/sync/policy.health.test.ts +56 -0
  220. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  221. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  222. package/src/sync/poll.saga.test.ts +51 -0
  223. package/src/sync/poll.saga.ts +36 -0
  224. package/src/sync/tabs.saga.test.ts +78 -0
  225. package/src/sync/tabs.saga.ts +96 -0
  226. package/src/testing/adapters.ts +137 -0
  227. package/src/testing/build.ts +63 -0
  228. package/src/testing/fake-services.ts +63 -0
  229. package/src/testing/run-pure.test.ts +92 -0
  230. package/src/testing/run-pure.ts +128 -0
  231. package/src/testing/services.ts +17 -0
  232. package/src/types.ts +568 -25
  233. package/src/utils/blurhash.ts +90 -0
  234. package/src/utils/edges.ts +57 -0
  235. package/src/utils/error-classification.test.ts +116 -0
  236. package/src/utils/error-classification.ts +74 -0
  237. package/src/utils/index.ts +58 -3
  238. package/src/utils/parser.test.ts +67 -102
  239. package/src/utils/parser.ts +62 -1
  240. package/src/utils/semver.test.ts +32 -0
  241. package/src/utils/semver.ts +30 -0
  242. package/src/utils/sha256.ts +15 -0
  243. package/src/utils/surql.ts +17 -15
  244. package/src/utils/utils.test.ts +3 -2
  245. package/tsdown.config.ts +64 -4
  246. package/vitest.config.ts +48 -0
  247. package/src/modules/cache/index.ts +0 -253
  248. package/src/modules/cache/types.ts +0 -19
  249. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  250. package/src/modules/data/data.status.test.ts +0 -108
  251. package/src/modules/data/data.test.ts +0 -58
  252. package/src/modules/data/index.ts +0 -1491
  253. package/src/modules/sync/engine.ts +0 -227
  254. package/src/modules/sync/events/index.ts +0 -84
  255. package/src/modules/sync/index.ts +0 -3
  256. package/src/modules/sync/queue/index.ts +0 -2
  257. package/src/modules/sync/queue/queue-down.ts +0 -90
  258. package/src/modules/sync/queue/queue-up.ts +0 -224
  259. package/src/modules/sync/scheduler.ts +0 -121
  260. package/src/modules/sync/sync.ts +0 -1244
  261. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -1,75 +1,311 @@
1
1
  import type { Diagnostic} from 'surrealdb';
2
+ import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
2
3
  import { applyDiagnostics, DateTime, RecordId, Surreal } from 'surrealdb';
3
- import { createWasmWorkerEngines } from '@surrealdb/wasm';
4
- import type { Sp00kyConfig } from '../../types';
4
+ import type { LocalWorkers, Sp00kyConfig } from '../../types';
5
5
  import type { Logger } from '../logger/index';
6
6
  import { AbstractDatabaseService } from './database';
7
7
  import { createDatabaseEventSystem, DatabaseEventTypes } from './events/index';
8
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(
65
+ logger: Logger,
66
+ createWorker: LocalWorkers['surreal']
67
+ ): Promise<Surreal> {
68
+ const { createWasmWorkerEngines } = await import('@surrealdb/wasm');
69
+ return new Surreal({
70
+ codecOptions: localCodecOptions,
71
+ engines: applyDiagnostics(
72
+ // An app-supplied worker (`database.workers.surreal`) for bundlers that
73
+ // do not bundle the engine's own `new Worker(new URL(...))`.
74
+ createWasmWorkerEngines(createWorker ? { createWorker } : undefined),
75
+ ({ key, type, phase, ...other }: Diagnostic) => {
76
+ if (phase === 'progress' || phase === 'after') {
77
+ logger.trace(
78
+ {
79
+ ...other,
80
+ key,
81
+ type,
82
+ phase,
83
+ service: 'surrealdb:local',
84
+ Category: 'sp00ky-client::LocalDatabaseService::diagnostics',
85
+ },
86
+ `Local SurrealDB diagnostics captured ${type}:${phase}`
87
+ );
88
+ }
89
+ }
90
+ ),
91
+ });
92
+ }
9
93
 
10
94
  export class LocalDatabaseService extends AbstractDatabaseService {
11
95
  private config: Sp00kyConfig<any>['database'];
12
96
  protected eventType = DatabaseEventTypes.LocalQuery;
13
97
 
98
+ /** Bucket currently open. Set by `connect`/`switchStore`. */
99
+ private bucketId: string = ANON_USER_ID;
100
+ /**
101
+ * Monotonic store generation. Bumped on every `switchStore`. Async chains
102
+ * that read from the store, await something remote, and then write back
103
+ * (sync poll, SSP stream updates) capture this at chain start and drop
104
+ * their write when it no longer matches — a stale-epoch write would land
105
+ * another user's data in the new bucket.
106
+ */
107
+ private storeEpoch = 0;
108
+ /** Gate that `query()`/`execute()` await; closed for the switch window. */
109
+ private gate: Promise<void> = Promise.resolve();
110
+ /** The incoming client while a switch is in flight (for unload cleanup). */
111
+ private pendingSwitchClient: Surreal | null = null;
112
+ /** The open `connect()` started, until it settles. */
113
+ private opening: Promise<void> | null = null;
114
+
14
115
  constructor(config: Sp00kyConfig<any>['database'], logger: Logger) {
15
116
  const events = createDatabaseEventSystem();
16
- super(
17
- new Surreal({
18
- codecOptions: {
19
- valueDecodeVisitor(value) {
20
- if (value instanceof RecordId) {
21
- return encodeRecordId(value);
22
- }
23
-
24
- if (value instanceof DateTime) {
25
- return value.toDate();
26
- }
27
-
28
- return value;
29
- },
30
- },
31
- engines: applyDiagnostics(
32
- createWasmWorkerEngines(),
33
- ({ key, type, phase, ...other }: Diagnostic) => {
34
- if (phase === 'progress' || phase === 'after') {
35
- logger.trace(
36
- {
37
- ...other,
38
- key,
39
- type,
40
- phase,
41
- service: 'surrealdb:local',
42
- Category: 'sp00ky-client::LocalDatabaseService::diagnostics',
43
- },
44
- `Local SurrealDB diagnostics captured ${type}:${phase}`
45
- );
46
- }
47
- }
48
- ),
49
- }),
50
- logger,
51
- events
52
- );
117
+ // Placeholder client with no wasm engine; `connect()` swaps in the real
118
+ // engine-backed client (built lazily) before any query is issued.
119
+ super(createBareSurrealClient(), logger, events);
53
120
  this.config = config;
121
+ this.queryTimeoutMs = Math.max(0, config.localOpTimeoutMs ?? DEFAULT_LOCAL_OP_TIMEOUT_MS);
122
+ }
123
+
124
+ protected override timeoutError(query: string): Error {
125
+ return new LocalOpTimeoutError(query.slice(0, 80), this.queryTimeoutMs);
54
126
  }
55
127
 
56
128
  getConfig(): Sp00kyConfig<any>['database'] {
57
129
  return this.config;
58
130
  }
59
131
 
60
- async connect(): Promise<void> {
132
+ get currentBucketId(): string {
133
+ return this.bucketId;
134
+ }
135
+
136
+ get epoch(): number {
137
+ return this.storeEpoch;
138
+ }
139
+
140
+ /**
141
+ * Close the query gate for a bucket switch. Every `query()`/`execute()`
142
+ * issued after this waits until the returned release fn runs — so work
143
+ * triggered mid-switch (sibling auth subscribers registering queries)
144
+ * lands on the NEW bucket instead of racing the swap. The migrator uses
145
+ * `queryUngated()` to provision the new bucket while the gate is closed.
146
+ */
147
+ beginSwitch(): () => void {
148
+ let release!: () => void;
149
+ this.gate = new Promise<void>((resolve) => {
150
+ release = resolve;
151
+ });
152
+ return release;
153
+ }
154
+
155
+ override async query<T extends unknown[]>(
156
+ query: string,
157
+ vars?: Record<string, unknown>,
158
+ opts?: { epoch?: number }
159
+ ): Promise<T> {
160
+ await this.gate;
161
+ // A write whose async chain started before a bucket switch must not land
162
+ // in the new bucket — that would be another user's data. Callers on such
163
+ // chains pass the epoch they captured at chain start; mismatches throw.
164
+ if (opts?.epoch !== undefined && opts.epoch !== this.storeEpoch) {
165
+ throw new StaleEpochError();
166
+ }
167
+ return super.query(query, vars);
168
+ }
169
+
170
+ override async execute<T>(
171
+ query: SealedQuery<T>,
172
+ vars?: Record<string, unknown>,
173
+ opts?: { epoch?: number }
174
+ ): Promise<T> {
175
+ const raw = await this.query<unknown[]>(query.sql, vars, opts);
176
+ return query.extract(raw);
177
+ }
178
+
179
+ /** Gate-bypassing query — ONLY for the switch path itself (schema
180
+ * provisioning must run while the gate is closed, or it deadlocks). */
181
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T> {
182
+ return super.query(query, vars);
183
+ }
184
+
185
+ async connect(bucketId: string = ANON_USER_ID): Promise<void> {
186
+ const opening = this.openBucket(bucketId);
187
+ this.opening = opening;
188
+ try {
189
+ await opening;
190
+ } finally {
191
+ if (this.opening === opening) this.opening = null;
192
+ }
193
+ }
194
+
195
+ private async openBucket(bucketId: string): Promise<void> {
61
196
  const { namespace, database } = this.getConfig();
62
197
  const store = this.getConfig().store ?? 'memory';
63
- const storeUrl = store === 'memory' ? 'mem://' : 'indxdb://sp00ky';
198
+ this.bucketId = bucketId;
199
+ const storeUrl = store === 'memory' ? 'mem://' : bucketStoreUrl(bucketId);
64
200
  this.logger.info(
65
201
  { namespace, database, storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
66
202
  'Connecting to local database'
67
203
  );
68
204
 
69
205
  this.registerUnloadClose();
206
+ // Build the real engine-backed client lazily here (first `@surrealdb/wasm`
207
+ // load), replacing the constructor's engine-less placeholder before any
208
+ // query runs.
209
+ this.client = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
210
+ await this.openWithRecovery(this.client, storeUrl, namespace, database, bucketId, store);
211
+ }
212
+
213
+ /**
214
+ * Switch the local store to another user's bucket. Opens the NEW bucket on a
215
+ * second client first (with the same 3-tier recovery), then atomically swaps
216
+ * `this.client` and closes the old one — a failed open never leaves the
217
+ * service on a dead client. Bumps the store epoch so in-flight old-bucket
218
+ * async chains can detect they're stale.
219
+ *
220
+ * Callers own the drain/rebind choreography (close the gate, quiesce sync +
221
+ * timers BEFORE calling this; re-provision + rebind AFTER). Statements that
222
+ * passed the gate before it closed are let finish before the old client
223
+ * closes: the engine streams results from its worker, and a client closed
224
+ * under a statement leaves that statement pending until its deadline, with
225
+ * every later local statement queued behind it.
226
+ */
227
+ async switchStore(bucketId: string): Promise<void> {
228
+ // Never overlap the boot open: the switch would close the client `connect`
229
+ // is still opening, and both would provision a store at once.
230
+ if (this.opening) await this.opening.catch(() => {});
231
+ if (bucketId === this.bucketId) return;
232
+ const { namespace, database } = this.getConfig();
233
+ const store = this.getConfig().store ?? 'memory';
234
+ this.storeEpoch++;
235
+
236
+ if (store === 'memory') {
237
+ // mem:// has no per-user persistence; close + reopen the same client
238
+ // yields a fresh empty store, which is exactly the reset we want.
239
+ await this.drainStatements();
240
+ try {
241
+ await this.client.close();
242
+ } catch {
243
+ /* ignore */
244
+ }
245
+ await this.openStore(this.client, 'mem://', namespace, database);
246
+ this.bucketId = bucketId;
247
+ this.logger.info(
248
+ { bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
249
+ 'Reset in-memory local store for bucket switch'
250
+ );
251
+ return;
252
+ }
253
+
254
+ const next = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
255
+ this.pendingSwitchClient = next;
256
+ try {
257
+ await this.openWithRecovery(
258
+ next,
259
+ bucketStoreUrl(bucketId),
260
+ namespace,
261
+ database,
262
+ bucketId,
263
+ store
264
+ );
265
+ } finally {
266
+ this.pendingSwitchClient = null;
267
+ }
268
+
269
+ await this.drainStatements();
270
+ const old = this.client;
271
+ this.client = next;
272
+ this.bucketId = bucketId;
273
+ try {
274
+ await old.close();
275
+ } catch {
276
+ /* best-effort — the old store's handle is released on unload regardless */
277
+ }
278
+ this.logger.info(
279
+ { bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
280
+ 'Switched local store bucket'
281
+ );
282
+ }
70
283
 
284
+ /** See `LocalStore.dropBucket`. A memory store keeps nothing to delete. */
285
+ async dropBucket(bucketId: string): Promise<void> {
286
+ if (bucketId === this.bucketId) throw new Error('Cannot drop the open bucket.');
287
+ if ((this.getConfig().store ?? 'memory') === 'memory') return;
288
+ await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
289
+ }
290
+
291
+ /**
292
+ * Open `storeUrl` on `client` with tiered recovery:
293
+ * tier 1 retries the same store (transient idb-handle races — preserves the
294
+ * cache), tier 2 drops THIS bucket's IndexedDB store and reconnects fresh,
295
+ * tier 3 falls back to `mem://` for the session. Only ever drops the bucket
296
+ * being opened — other users' buckets hold their own caches AND un-pushed
297
+ * mutation outboxes, which must survive another bucket's corruption.
298
+ */
299
+ private async openWithRecovery(
300
+ client: Surreal,
301
+ storeUrl: string,
302
+ namespace: string,
303
+ database: string,
304
+ bucketId: string,
305
+ store: string
306
+ ): Promise<void> {
71
307
  try {
72
- await this.openStore(storeUrl, namespace, database);
308
+ await this.openStore(client, storeUrl, namespace, database);
73
309
  this.logger.info(
74
310
  { Category: 'sp00ky-client::LocalDatabaseService::connect' },
75
311
  'Connected to local database'
@@ -101,13 +337,13 @@ export class LocalDatabaseService extends AbstractDatabaseService {
101
337
  // the cache on every reload, making warm loads as slow as cold ones.
102
338
  for (let attempt = 1; attempt <= 2; attempt++) {
103
339
  try {
104
- await this.client.close();
340
+ await client.close();
105
341
  } catch {
106
342
  /* ignore */
107
343
  }
108
344
  await delay(150 * attempt);
109
345
  try {
110
- await this.openStore(storeUrl, namespace, database);
346
+ await this.openStore(client, storeUrl, namespace, database);
111
347
  this.logger.info(
112
348
  { attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
113
349
  'Connected to local database on retry (cache preserved)'
@@ -121,18 +357,18 @@ export class LocalDatabaseService extends AbstractDatabaseService {
121
357
  }
122
358
  }
123
359
 
124
- // Tier 2 — the store is genuinely unopenable; drop it and reconnect fresh.
125
- // This loses the cache (re-syncs from the server), so it's the last resort
126
- // before in-memory.
360
+ // Tier 2 — the store is genuinely unopenable; drop THIS bucket and reconnect
361
+ // fresh. This loses the bucket's cache (re-syncs from the server), so it's
362
+ // the last resort before in-memory.
127
363
  try {
128
- await this.client.close();
364
+ await client.close();
129
365
  } catch {
130
366
  /* ignore — closing a half-open connection is best-effort */
131
367
  }
132
- await dropLocalIndexedDbStores(this.logger);
368
+ await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
133
369
 
134
370
  try {
135
- await this.openStore(storeUrl, namespace, database);
371
+ await this.openStore(client, storeUrl, namespace, database);
136
372
  this.logger.info(
137
373
  { Category: 'sp00ky-client::LocalDatabaseService::connect' },
138
374
  'Reconnected to local database after clearing the corrupt store'
@@ -146,11 +382,11 @@ export class LocalDatabaseService extends AbstractDatabaseService {
146
382
  'Local store still failing after clear; falling back to in-memory'
147
383
  );
148
384
  try {
149
- await this.client.close();
385
+ await client.close();
150
386
  } catch {
151
387
  /* ignore */
152
388
  }
153
- await this.openStore('mem://', namespace, database);
389
+ await this.openStore(client, 'mem://', namespace, database);
154
390
  this.logger.warn(
155
391
  { Category: 'sp00ky-client::LocalDatabaseService::connect' },
156
392
  'Connected to local database (in-memory fallback)'
@@ -169,6 +405,7 @@ export class LocalDatabaseService extends AbstractDatabaseService {
169
405
  * reload, making warm loads as slow as cold ones. `pagehide` is the reliable
170
406
  * unload signal (fires on bfcache + normal navigation); `close()` is async but
171
407
  * the WASM worker initiates the IndexedDB connection teardown synchronously.
408
+ * Also closes a mid-switch incoming client so its fresh handle doesn't linger.
172
409
  */
173
410
  private registerUnloadClose(): void {
174
411
  if (this.unloadCloseRegistered || typeof window === 'undefined') return;
@@ -179,22 +416,32 @@ export class LocalDatabaseService extends AbstractDatabaseService {
179
416
  } catch {
180
417
  /* best-effort */
181
418
  }
419
+ try {
420
+ void this.pendingSwitchClient?.close();
421
+ } catch {
422
+ /* best-effort */
423
+ }
182
424
  };
183
425
  window.addEventListener('pagehide', close);
184
426
  window.addEventListener('beforeunload', close);
185
427
  }
186
428
 
187
- private async openStore(storeUrl: string, namespace: string, database: string): Promise<void> {
429
+ private async openStore(
430
+ client: Surreal,
431
+ storeUrl: string,
432
+ namespace: string,
433
+ database: string
434
+ ): Promise<void> {
188
435
  this.logger.debug(
189
436
  { storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
190
437
  '[LocalDatabaseService] Calling client.connect'
191
438
  );
192
- await this.client.connect(storeUrl, {});
439
+ await client.connect(storeUrl, {});
193
440
  this.logger.debug(
194
441
  { namespace, database, Category: 'sp00ky-client::LocalDatabaseService::connect' },
195
442
  '[LocalDatabaseService] client.connect returned. Calling client.use'
196
443
  );
197
- await this.client.use({ namespace, database });
444
+ await client.use({ namespace, database });
198
445
  this.logger.debug(
199
446
  { Category: 'sp00ky-client::LocalDatabaseService::connect' },
200
447
  '[LocalDatabaseService] client.use returned'
@@ -218,34 +465,25 @@ export function isLocalStoreOpenError(err: unknown): boolean {
218
465
  );
219
466
  }
220
467
 
221
- /** Best-effort delete of this client's IndexedDB store(s). The persistent local
222
- * DB lives at `indxdb://sp00ky`; SurrealDB-WASM backs it with one or more
223
- * IndexedDB databases whose names include `sp00ky`. Resolves even on
224
- * error/blocked so startup can proceed. No-op outside a browser. */
225
- async function dropLocalIndexedDbStores(logger: Logger): Promise<void> {
468
+ /** Best-effort delete of ONE bucket's IndexedDB store(s). SurrealDB-WASM backs
469
+ * `indxdb://<name>` with one or more IndexedDB databases whose names include
470
+ * `<name>`. Scoped to the given store name — never wipe by the bare `sp00ky`
471
+ * substring, that would take every user's bucket (and their un-pushed mutation
472
+ * outboxes) down with one corrupt store. Resolves even on error/blocked so
473
+ * startup can proceed. No-op outside a browser. Exported for unit tests. */
474
+ export async function dropLocalIndexedDbStores(logger: Logger, storeName: string): Promise<void> {
226
475
  if (typeof indexedDB === 'undefined') return;
227
- const remove = (name: string): Promise<void> =>
228
- new Promise((resolve) => {
229
- try {
230
- const req = indexedDB.deleteDatabase(name);
231
- req.onsuccess = () => resolve();
232
- req.onerror = () => resolve();
233
- req.onblocked = () => resolve();
234
- } catch {
235
- resolve();
236
- }
237
- });
238
476
  try {
239
477
  let names: string[] = [];
240
478
  if (typeof indexedDB.databases === 'function') {
241
479
  const dbs = await indexedDB.databases();
242
480
  names = dbs
243
481
  .map((d) => d.name)
244
- .filter((n): n is string => !!n && n.toLowerCase().includes('sp00ky'));
482
+ .filter((n): n is string => !!n && matchesBucketStore(n, storeName));
245
483
  }
246
484
  // Fall back to the known store name if enumeration is unavailable/empty.
247
- if (names.length === 0) names = ['sp00ky'];
248
- await Promise.all(names.map(remove));
485
+ if (names.length === 0) names = [storeName];
486
+ await Promise.all(names.map(deleteIndexedDb));
249
487
  logger.info(
250
488
  { names, Category: 'sp00ky-client::LocalDatabaseService::connect' },
251
489
  'Cleared local IndexedDB store(s)'
@@ -257,3 +495,55 @@ async function dropLocalIndexedDbStores(logger: Logger): Promise<void> {
257
495
  );
258
496
  }
259
497
  }
498
+
499
+ /** True when idb database `name` belongs to the bucket store `storeName` —
500
+ * exact match or a derived name (`<storeName>`, `<storeName>-*`, `*<storeName>*`
501
+ * with a non-alphanumeric boundary so `sp00ky-abc` never matches
502
+ * `sp00ky-abcdef`'s store). Exported for unit tests. */
503
+ export function matchesBucketStore(name: string, storeName: string): boolean {
504
+ const lower = name.toLowerCase();
505
+ const target = storeName.toLowerCase();
506
+ const idx = lower.indexOf(target);
507
+ if (idx === -1) return false;
508
+ const after = lower[idx + target.length];
509
+ return after === undefined || !/[a-z0-9_]/.test(after);
510
+ }
511
+
512
+ /** Nuke EVERY sp00ky local bucket on this device (manual full reset only —
513
+ * the automated corruption recovery is scoped to one bucket). */
514
+ export async function dropAllSp00kyIndexedDbStores(logger: Logger): Promise<void> {
515
+ if (typeof indexedDB === 'undefined') return;
516
+ try {
517
+ let names: string[] = [];
518
+ if (typeof indexedDB.databases === 'function') {
519
+ const dbs = await indexedDB.databases();
520
+ names = dbs
521
+ .map((d) => d.name)
522
+ .filter((n): n is string => !!n && n.toLowerCase().includes('sp00ky'));
523
+ }
524
+ if (names.length === 0) names = ['sp00ky'];
525
+ await Promise.all(names.map(deleteIndexedDb));
526
+ logger.info(
527
+ { names, Category: 'sp00ky-client::LocalDatabaseService::reset' },
528
+ 'Cleared ALL sp00ky IndexedDB stores'
529
+ );
530
+ } catch (e) {
531
+ logger.warn(
532
+ { err: e, Category: 'sp00ky-client::LocalDatabaseService::reset' },
533
+ 'Failed to enumerate/clear IndexedDB; proceeding anyway'
534
+ );
535
+ }
536
+ }
537
+
538
+ function deleteIndexedDb(name: string): Promise<void> {
539
+ return new Promise((resolve) => {
540
+ try {
541
+ const req = indexedDB.deleteDatabase(name);
542
+ req.onsuccess = () => resolve();
543
+ req.onerror = () => resolve();
544
+ req.onblocked = () => resolve();
545
+ } catch {
546
+ resolve();
547
+ }
548
+ });
549
+ }