@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10

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 (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  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/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -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 +512 -0
  61. package/src/live/index.ts +1059 -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 +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -0,0 +1,79 @@
1
+ import { describe, it, expect, afterEach, vi } from 'vitest';
2
+ import { walkOpfs } from './storage-info';
3
+
4
+ /** Minimal in-memory OPFS: directories are nested objects, files are numbers
5
+ * (their size) or 'locked' (getFile() throws, like a live SAHPool handle). */
6
+ type FakeTree = { [name: string]: FakeTree | number | 'locked' };
7
+
8
+ function makeDirHandle(tree: FakeTree): any {
9
+ return {
10
+ kind: 'directory',
11
+ entries: async function* () {
12
+ for (const [name, node] of Object.entries(tree)) {
13
+ if (typeof node === 'object') {
14
+ yield [name, makeDirHandle(node)];
15
+ } else {
16
+ yield [
17
+ name,
18
+ {
19
+ kind: 'file',
20
+ getFile: async () => {
21
+ if (node === 'locked') throw new DOMException('locked', 'NoModificationAllowedError');
22
+ return { size: node };
23
+ },
24
+ },
25
+ ];
26
+ }
27
+ }
28
+ },
29
+ };
30
+ }
31
+
32
+ function stubOpfs(tree: FakeTree | null) {
33
+ vi.stubGlobal('navigator', tree === null ? {} : {
34
+ storage: { getDirectory: async () => makeDirHandle(tree) },
35
+ });
36
+ }
37
+
38
+ afterEach(() => {
39
+ vi.unstubAllGlobals();
40
+ });
41
+
42
+ describe('walkOpfs', () => {
43
+ it('reports unsupported without OPFS APIs', async () => {
44
+ stubOpfs(null);
45
+ expect(await walkOpfs()).toEqual({
46
+ supported: false,
47
+ entries: [],
48
+ totalBytes: 0,
49
+ truncated: false,
50
+ });
51
+ });
52
+
53
+ it('walks recursively, sums readable sizes, and omits size for locked files', async () => {
54
+ stubOpfs({
55
+ '.sp00ky-anon': { '0000000001': 4096, '0000000002': 'locked' },
56
+ 'other.txt': 10,
57
+ });
58
+ const res = await walkOpfs();
59
+ expect(res.supported).toBe(true);
60
+ expect(res.truncated).toBe(false);
61
+ // Locked file present but without a size; total counts only readable bytes.
62
+ expect(res.totalBytes).toBe(4106);
63
+ expect(res.entries).toEqual([
64
+ { path: '.sp00ky-anon', kind: 'directory' },
65
+ { path: '.sp00ky-anon/0000000001', kind: 'file', size: 4096 },
66
+ { path: '.sp00ky-anon/0000000002', kind: 'file' },
67
+ { path: 'other.txt', kind: 'file', size: 10 },
68
+ ]);
69
+ });
70
+
71
+ it('caps the listing and flags truncation', async () => {
72
+ const big: FakeTree = {};
73
+ for (let i = 0; i < 10; i++) big[`f${i}`] = 1;
74
+ stubOpfs(big);
75
+ const res = await walkOpfs(5);
76
+ expect(res.truncated).toBe(true);
77
+ expect(res.entries.length).toBe(5);
78
+ });
79
+ });
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Storage diagnostics for the DevTools Storage tab: what engine backs the
3
+ * local cache, whether it actually persists, how much of the device's quota
4
+ * the origin uses, and what is physically sitting in OPFS. Assembled by
5
+ * `DevToolsService.getStorageInfo()`; everything here is JSON-safe.
6
+ */
7
+
8
+ export interface OpfsEntry {
9
+ /** Path relative to the OPFS root, e.g. `.sp00ky-anon/0000000000000001`. */
10
+ path: string;
11
+ kind: 'file' | 'directory';
12
+ /** Absent when the file's size can't be read (e.g. an exclusive sync access
13
+ * handle is held on it — exactly the case during SAHPool contention). */
14
+ size?: number;
15
+ }
16
+
17
+ /** Engine-side numbers only the engine can produce (worker round-trips). */
18
+ export interface EngineStorageDiagnostics {
19
+ engine: 'sqlite' | 'rows';
20
+ bucketId: string;
21
+ useOpfs: boolean;
22
+ workerSelectConfigured: boolean;
23
+ /** `false` while configured `true` means the runtime downgraded to the
24
+ * legacy multi-hop select (stale cached worker bundle). */
25
+ workerSelectEffective: boolean;
26
+ /** page_count * page_size. */
27
+ dbSizeBytes?: number;
28
+ /** freelist_count * page_size — reclaimable via VACUUM. On the row store:
29
+ * dead bytes in the log, reclaimed by its next compaction. */
30
+ freelistBytes?: number;
31
+ tableCounts?: { table: string; rows: number }[];
32
+ error?: string;
33
+ }
34
+
35
+ /**
36
+ * Shared-tabs coordination state. Reported ONLY when `sharedTabs: true` was
37
+ * configured (apps that never asked for it get `null`, so the panel shows
38
+ * nothing). `active: false` with a `reason` is itself the useful signal: the
39
+ * app asked to share one store and this tab is not, so it owns or contends for
40
+ * the OPFS pool alone.
41
+ */
42
+ export interface SharedTabsInfo {
43
+ active: boolean;
44
+ /** Why inactive: a capability gate reason, or 'fell-back' when the broker
45
+ * was reachable but no role landed (election timeout, rejected tab). */
46
+ reason?: string;
47
+ role?: 'solo' | 'leader' | 'follower';
48
+ /** This tab's id (also the suffix of every mutation id it mints). */
49
+ tabId?: string;
50
+ /** Monotonic id of the current leadership term; embedded in the worker lock. */
51
+ leadershipId?: number;
52
+ /** Who owns the store: this tab when leader, else the leader's tab id. */
53
+ leaderTabId?: string | null;
54
+ /** Leader only: attached follower tabs. */
55
+ followers?: number;
56
+ /** Leader only: ingest batches relayed to followers so far. */
57
+ relayedBatches?: number;
58
+ }
59
+
60
+ export interface StorageInfo {
61
+ at: number;
62
+ engine: { kind: 'surrealdb' | 'sqlite' | 'rows' | 'custom'; store: string; bucketId: string };
63
+ health: { status: 'unknown' | 'persistent' | 'memory'; fallback: boolean; error?: string };
64
+ /** Shared-tabs state, or null when the feature was never requested. */
65
+ tabs?: SharedTabsInfo | null;
66
+ browser: {
67
+ /** `navigator.storage.persisted()` — whether the origin's storage is
68
+ * exempt from eviction (unrelated to the OPFS pool lock). */
69
+ persisted?: boolean;
70
+ usage?: number;
71
+ quota?: number;
72
+ /** Chrome-only per-system breakdown from `estimate()`. */
73
+ usageDetails?: Record<string, number>;
74
+ error?: string;
75
+ };
76
+ opfs: {
77
+ supported: boolean;
78
+ entries: OpfsEntry[];
79
+ totalBytes: number;
80
+ truncated: boolean;
81
+ error?: string;
82
+ };
83
+ /**
84
+ * Bucket-file cache counters. `evicted*` is cumulative for this tab's
85
+ * session, so a number that climbs while `totalBytes` sits at the budget is
86
+ * the signal that `blobCache.maxBytes` is too small for the working set.
87
+ */
88
+ blobs?: BlobCacheInfo;
89
+ /** Snapshot of `globalThis.__sqliteStats` (SQLite engine only). */
90
+ sqliteStats?: Record<string, unknown>;
91
+ engineDiagnostics?: EngineStorageDiagnostics;
92
+ }
93
+
94
+ export interface BlobCacheInfo {
95
+ entries: number;
96
+ totalBytes: number;
97
+ budgetBytes: number;
98
+ pinnedBytes: number;
99
+ evictedEntries: number;
100
+ evictedBytes: number;
101
+ /** Manifest rows rebuilt from disk at the last reconcile. */
102
+ reconciledEntries: number;
103
+ hits: number;
104
+ misses: number;
105
+ /** False when OPFS is unwritable or the quota was exhausted — the cache is
106
+ * running in per-tab memory and nothing survives a reload. */
107
+ persistent: boolean;
108
+ /** Over budget with only pinned or on-screen entries left: new files are no
109
+ * longer written rather than pinned ones being discarded. */
110
+ persistPaused: boolean;
111
+ }
112
+
113
+ /**
114
+ * Recursively list the origin's OPFS. Sizes come from `handle.getFile()`,
115
+ * which throws for a file another context holds an exclusive sync access
116
+ * handle on — SAHPool does exactly that for its whole pool, so a locked file
117
+ * (size omitted) is a live "who has the pool" signal, not a failure.
118
+ */
119
+ export async function walkOpfs(maxEntries = 2000, maxDepth = 8): Promise<StorageInfo['opfs']> {
120
+ const nav = typeof navigator !== 'undefined' ? navigator : undefined;
121
+ if (!nav?.storage?.getDirectory) {
122
+ return { supported: false, entries: [], totalBytes: 0, truncated: false };
123
+ }
124
+ const entries: OpfsEntry[] = [];
125
+ let totalBytes = 0;
126
+ let truncated = false;
127
+ try {
128
+ const root = await nav.storage.getDirectory();
129
+ const walk = async (dir: FileSystemDirectoryHandle, prefix: string, depth: number) => {
130
+ if (depth > maxDepth) return;
131
+ // entries() is standard; older lib.dom typings may lack it.
132
+ for await (const [name, handle] of (dir as any).entries() as AsyncIterable<
133
+ [string, FileSystemHandle]
134
+ >) {
135
+ if (entries.length >= maxEntries) {
136
+ truncated = true;
137
+ return;
138
+ }
139
+ const path = prefix ? `${prefix}/${name}` : name;
140
+ if (handle.kind === 'directory') {
141
+ entries.push({ path, kind: 'directory' });
142
+ await walk(handle as FileSystemDirectoryHandle, path, depth + 1);
143
+ } else {
144
+ let size: number | undefined;
145
+ try {
146
+ size = (await (handle as FileSystemFileHandle).getFile()).size;
147
+ totalBytes += size;
148
+ } catch {
149
+ // Locked by an exclusive access handle (e.g. a live SAHPool).
150
+ }
151
+ const entry: OpfsEntry = { path, kind: 'file' };
152
+ if (size !== undefined) entry.size = size;
153
+ entries.push(entry);
154
+ }
155
+ }
156
+ };
157
+ await walk(root, '', 0);
158
+ entries.sort((a, b) => a.path.localeCompare(b.path));
159
+ return { supported: true, entries, totalBytes, truncated };
160
+ } catch (e) {
161
+ return {
162
+ supported: true,
163
+ entries,
164
+ totalBytes,
165
+ truncated,
166
+ error: e instanceof Error ? e.message : String(e),
167
+ };
168
+ }
169
+ }
@@ -16,6 +16,33 @@ export const UNAVAILABLE = 'unavailable';
16
16
  * backend). Carries far more than versions — status, uptime, ip, views — so the
17
17
  * DevTools can render the whole stack. Extra fields are preserved verbatim.
18
18
  */
19
+ /** One end-to-end sync-pipeline probe cycle recorded by the scheduler. */
20
+ export interface HeartbeatSample {
21
+ ts: number;
22
+ /** `null` for a failed cycle. */
23
+ ms: number | null;
24
+ ok: boolean;
25
+ }
26
+
27
+ /**
28
+ * E2E heartbeat state, reported on the scheduler entity only. The scheduler
29
+ * times a probe row's full round trip (DB event → ingest → broadcast → SSP
30
+ * circuit step); `samples` is its rolling window of recent cycles, which the
31
+ * DevTools sparkline renders.
32
+ */
33
+ export interface HeartbeatInfo {
34
+ enabled: boolean;
35
+ stale: boolean;
36
+ /** Nothing to measure right now (e.g. no ready SSPs mid-bootstrap). */
37
+ blocked?: boolean;
38
+ blocked_reason?: string | null;
39
+ last_e2e_ms: number | null;
40
+ last_ok_epoch_ms: number | null;
41
+ consecutive_failures: number;
42
+ interval_secs: number;
43
+ samples?: HeartbeatSample[];
44
+ }
45
+
19
46
  export interface BackendEntity {
20
47
  entity: string;
21
48
  id?: string;
@@ -25,6 +52,8 @@ export interface BackendEntity {
25
52
  surrealdb_version?: string;
26
53
  uptime_seconds?: number;
27
54
  views?: number;
55
+ /** Scheduler entity only. */
56
+ heartbeat?: HeartbeatInfo;
28
57
  [key: string]: unknown;
29
58
  }
30
59
 
@@ -1,5 +1,21 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
2
3
  import { FeatureFlagModule } from './index';
4
+ import { AuthService } from '../auth/index';
5
+
6
+ // vitest runs in the `node` environment here, so there is no localStorage.
7
+ // The module guards every access with `globalThis.localStorage?.`, which keeps
8
+ // overrides in-memory-only — this shim lets the persistence path be tested.
9
+ function installLocalStorage() {
10
+ const store = new Map<string, string>();
11
+ const shim = {
12
+ getItem: (k: string) => store.get(k) ?? null,
13
+ setItem: (k: string, v: string) => void store.set(k, v),
14
+ removeItem: (k: string) => void store.delete(k),
15
+ };
16
+ (globalThis as any).localStorage = shim;
17
+ return { store, uninstall: () => delete (globalThis as any).localStorage };
18
+ }
3
19
 
4
20
  // Minimal mocks for the three deps the module touches. The DataModule mock
5
21
  // captures the single subscribe callback so a test can push live results, and
@@ -118,3 +134,165 @@ describe('FeatureFlagModule', () => {
118
134
  expect(env.hasSub()).toBe(true); // re-registered for the new user
119
135
  });
120
136
  });
137
+
138
+ // Local overrides force a variant in THIS browser only. They must win over the
139
+ // server assignment on every read path — `variant()`, `payload()`, `enabled()`
140
+ // and `subscribe()` all funnel through the same resolver, so a gap in any one
141
+ // of them is a gap in all of them.
142
+ describe('FeatureFlagModule local overrides', () => {
143
+ let env: ReturnType<typeof makeDeps>;
144
+ let mod: FeatureFlagModule<any>;
145
+ let ls: ReturnType<typeof installLocalStorage>;
146
+
147
+ beforeEach(() => {
148
+ ls = installLocalStorage();
149
+ env = makeDeps();
150
+ mod = new FeatureFlagModule(env.deps);
151
+ });
152
+
153
+ afterEach(() => ls.uninstall());
154
+
155
+ it('wins over the server assignment', async () => {
156
+ const flag = mod.feature('alpha', { fallback: 'off' });
157
+ await tick();
158
+ env.push([{ key: 'alpha', variant: 'off' }]);
159
+ expect(flag.enabled()).toBe(false);
160
+
161
+ mod.setLocalOverride('alpha', 'on');
162
+ expect(flag.variant()).toBe('on');
163
+ expect(flag.enabled()).toBe(true);
164
+ });
165
+
166
+ it('survives a later live result for the same key', async () => {
167
+ const flag = mod.feature('alpha', { fallback: 'off' });
168
+ await tick();
169
+ mod.setLocalOverride('alpha', 'on');
170
+
171
+ env.push([{ key: 'alpha', variant: 'off' }]); // server disagrees
172
+ expect(flag.variant()).toBe('on');
173
+ });
174
+
175
+ it('applies before the first result, without a fallback flash', () => {
176
+ mod.setLocalOverride('alpha', 'on');
177
+ const flag = mod.feature('alpha', { fallback: 'off' });
178
+ expect(flag.variant()).toBe('on'); // seeded even though nothing loaded yet
179
+ });
180
+
181
+ it('carries its own payload', async () => {
182
+ const flag = mod.feature('alpha', { fallback: 'off' });
183
+ await tick();
184
+ env.push([{ key: 'alpha', variant: 'off', payload: { copy: 'server' } }]);
185
+
186
+ mod.setLocalOverride('alpha', 'on', { copy: 'local' });
187
+ expect(flag.payload()).toEqual({ copy: 'local' });
188
+ });
189
+
190
+ it('notifies subscribers when set and cleared', async () => {
191
+ const flag = mod.feature('alpha', { fallback: 'off' });
192
+ await tick();
193
+ env.push([{ key: 'alpha', variant: 'off' }]);
194
+
195
+ const seen: (string | undefined)[] = [];
196
+ flag.subscribe((s) => seen.push(s.variant));
197
+ expect(seen).toEqual(['off']); // immediate call
198
+
199
+ mod.setLocalOverride('alpha', 'on');
200
+ mod.setLocalOverride('alpha', null);
201
+ expect(seen).toEqual(['off', 'on', 'off']);
202
+ });
203
+
204
+ it('restores the server assignment when cleared', async () => {
205
+ const flag = mod.feature('alpha', { fallback: 'off' });
206
+ await tick();
207
+ env.push([{ key: 'alpha', variant: 'treatment', payload: { copy: 'server' } }]);
208
+
209
+ mod.setLocalOverride('alpha', 'off');
210
+ expect(flag.variant()).toBe('off');
211
+
212
+ mod.clearLocalOverrides();
213
+ expect(flag.variant()).toBe('treatment');
214
+ expect(flag.payload()).toEqual({ copy: 'server' });
215
+ });
216
+
217
+ it('survives a user change — it is a browser setting, not a session one', async () => {
218
+ mod.init();
219
+ const flag = mod.feature('alpha', { fallback: 'off' });
220
+ await tick();
221
+ mod.setLocalOverride('alpha', 'on');
222
+
223
+ env.setUser('user:other');
224
+ await tick();
225
+ expect(flag.variant()).toBe('on');
226
+ });
227
+
228
+ it('persists to localStorage and reloads into a fresh module', () => {
229
+ mod.setLocalOverride('alpha', 'on', { copy: 'local' });
230
+ expect(mod.getLocalOverrides()).toEqual({ alpha: { variant: 'on', payload: { copy: 'local' } } });
231
+
232
+ // A new module reads the same page-origin store, as after a reload.
233
+ const reloaded = new FeatureFlagModule(makeDeps().deps);
234
+ expect(reloaded.getLocalOverrides()).toEqual({
235
+ alpha: { variant: 'on', payload: { copy: 'local' } },
236
+ });
237
+ expect(reloaded.feature('alpha', { fallback: 'off' }).variant()).toBe('on');
238
+ });
239
+
240
+ it('drops the storage key entirely once the last override is cleared', () => {
241
+ mod.setLocalOverride('alpha', 'on');
242
+ expect(ls.store.size).toBe(1);
243
+
244
+ mod.setLocalOverride('alpha', null);
245
+ expect(ls.store.size).toBe(0);
246
+ expect(new FeatureFlagModule(makeDeps().deps).getLocalOverrides()).toEqual({});
247
+ });
248
+
249
+ it('ignores a corrupt store rather than failing to construct', () => {
250
+ ls.store.set('sp00ky:feature-overrides', '{not json');
251
+ expect(() => new FeatureFlagModule(makeDeps().deps)).not.toThrow();
252
+ });
253
+ });
254
+
255
+ describe('FeatureFlagModule across a reload', () => {
256
+ // A reload restores the session from the cached token (the id as a string),
257
+ // then the server check lands the user row (the id as a RecordId) a few
258
+ // seconds later. Same user: an assigned flag must stay on throughout, not
259
+ // blink off while the module re-registers its query.
260
+ it('keeps flags through the server verification of the same user', async () => {
261
+ const b64 = Buffer.from(JSON.stringify({ AC: 'account', ID: 'user:5abc' })).toString('base64url');
262
+ const token = `h.${b64}.s`;
263
+ const store = new Map<string, unknown>([['sp00ky_auth_token', token]]);
264
+ const persistence = {
265
+ get: async (k: string) => store.get(k) ?? null,
266
+ set: async (k: string, v: unknown) => void store.set(k, v),
267
+ remove: async (k: string) => void store.delete(k),
268
+ } as any;
269
+ const remote = {
270
+ query: async () => [{ id: new RecordId('user', '5abc') }],
271
+ setAuthToken: () => undefined,
272
+ getClient: () => ({ authenticate: async () => undefined, invalidate: async () => undefined }),
273
+ } as any;
274
+ const silent: any = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
275
+ silent.child = () => silent;
276
+ const auth = new AuthService({} as any, remote, persistence, silent);
277
+
278
+ const env = makeDeps();
279
+ const flags = new FeatureFlagModule({ ...env.deps, auth } as any);
280
+ flags.init();
281
+ await auth.restoreSessionFromToken();
282
+ const clubs = flags.feature('clubs');
283
+ const seen: (string | undefined)[] = [];
284
+ clubs.subscribe((s) => seen.push(s.variant));
285
+ await tick();
286
+ env.push([{ key: 'clubs', variant: 'on' }]);
287
+ expect(clubs.variant()).toBe('on');
288
+ const registrations = env.calls.length;
289
+
290
+ await auth.check();
291
+ await tick();
292
+
293
+ expect(clubs.variant()).toBe('on');
294
+ expect(seen.slice(seen.indexOf('on'))).not.toContain(undefined);
295
+ expect(env.calls.length).toBe(registrations);
296
+ });
297
+ });
298
+
@@ -1,6 +1,4 @@
1
1
  import type { SchemaStructure } from '@spooky-sync/query-builder';
2
- import type { DataModule } from '../data/index';
3
- import type { Sp00kySync } from '../sync/index';
4
2
  import type { AuthService } from '../auth/index';
5
3
  import type { Logger } from '../../services/logger/index';
6
4
  import type { QueryTimeToLive } from '../../types';
@@ -13,6 +11,12 @@ import type { QueryTimeToLive } from '../../types';
13
11
  // fallback. Avoids one-registration-per-flag and the param-filtered live query.
14
12
  const FEATURE_QUERY = 'SELECT key, variant, payload FROM _00_user_feature';
15
13
 
14
+ // Local overrides live on the PAGE origin, so they survive reloads and are
15
+ // shared across tabs of the app. Deliberately not the DevTools panel's own
16
+ // storage — the panel runs on a different origin and would get a separate
17
+ // bucket.
18
+ const OVERRIDE_STORAGE_KEY = 'sp00ky:feature-overrides';
19
+
16
20
  interface FeatureRow {
17
21
  key?: string;
18
22
  variant?: string;
@@ -29,6 +33,16 @@ export interface FeatureFlagOptions {
29
33
  ttl?: QueryTimeToLive;
30
34
  }
31
35
 
36
+ /**
37
+ * A locally forced variant. Applies to THIS browser only and is never sent to
38
+ * the server — the assignment in `_00_user_feature` is untouched, so clearing
39
+ * the override restores whatever the server says.
40
+ */
41
+ export interface FeatureFlagOverride {
42
+ variant: string;
43
+ payload?: unknown;
44
+ }
45
+
32
46
  export class FeatureFlagHandle {
33
47
  private latest: FeatureFlagSnapshot = { variant: undefined, payload: undefined };
34
48
  private listeners = new Set<(s: FeatureFlagSnapshot) => void>();
@@ -91,10 +105,20 @@ export class FeatureFlagHandle {
91
105
  }
92
106
  }
93
107
 
108
+ /** The slice of the query engine this module drives: register a live query
109
+ * locally, ask for its remote registration, subscribe to its rows. */
110
+ export interface LiveQueryPort {
111
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
112
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: { immediate?: boolean }): () => void;
113
+ }
114
+ export interface RemoteRegisterPort {
115
+ enqueueDownEvent(event: { type: 'register'; payload: { hash: string } }): void;
116
+ }
117
+
94
118
  export interface FeatureFlagModuleDeps<S extends SchemaStructure> {
95
- dataModule: DataModule<S>;
96
- sync: Sp00kySync<S>;
97
- auth: AuthService<S>;
119
+ dataModule: LiveQueryPort;
120
+ sync: RemoteRegisterPort;
121
+ auth: Pick<AuthService<S>, 'subscribe'>;
98
122
  logger: Logger;
99
123
  }
100
124
 
@@ -114,9 +138,15 @@ export class FeatureFlagModule<S extends SchemaStructure> {
114
138
  // back). `snapshots` only holds ASSIGNED keys; an absent key → fallback.
115
139
  private snapshots = new Map<string, FeatureFlagSnapshot>();
116
140
  private loaded = false;
141
+ // Developer-forced variants, this browser only. Take precedence over the
142
+ // server assignment for every read path.
143
+ private overrides = new Map<string, FeatureFlagOverride>();
117
144
 
118
145
  constructor(private deps: FeatureFlagModuleDeps<S>) {
119
146
  this.logger = deps.logger.child({ service: 'FeatureFlagModule' });
147
+ // Loaded in the constructor rather than `init()` so an override applies
148
+ // even when `client.feature()` is called before auth resolves.
149
+ this.loadOverrides();
120
150
  }
121
151
 
122
152
  init(): void {
@@ -135,8 +165,10 @@ export class FeatureFlagModule<S extends SchemaStructure> {
135
165
  if (options.ttl) this.ttl = options.ttl;
136
166
  // If the shared query already resolved, seed this handle immediately so a
137
167
  // late `feature()` call doesn't flash the fallback for an assigned key.
138
- if (this.loaded) {
139
- handle.set(this.snapshots.get(key) ?? { variant: undefined, payload: undefined });
168
+ // An override seeds it too, even before the first result: forcing a
169
+ // variant should take effect instantly, not one round trip later.
170
+ if (this.loaded || this.overrides.has(key)) {
171
+ handle.set(this.resolve(key));
140
172
  }
141
173
  void this.ensureStarted();
142
174
  return handle;
@@ -155,8 +187,10 @@ export class FeatureFlagModule<S extends SchemaStructure> {
155
187
  this.loaded = false;
156
188
  this.snapshots.clear();
157
189
  // Clear handles immediately so a sign-out hides flag-gated UI without lag.
190
+ // `resolve` keeps any local override in place across the switch — it is a
191
+ // developer setting for this browser, not part of the session.
158
192
  for (const handle of this.handles) {
159
- handle.set({ variant: undefined, payload: undefined });
193
+ handle.set(this.resolve(handle.key));
160
194
  }
161
195
  await this.ensureStarted();
162
196
  }
@@ -202,8 +236,81 @@ export class FeatureFlagModule<S extends SchemaStructure> {
202
236
  }
203
237
  }
204
238
  this.loaded = true;
205
- for (const handle of this.handles) {
206
- handle.set(this.snapshots.get(handle.key) ?? { variant: undefined, payload: undefined });
239
+ this.pushAll();
240
+ }
241
+
242
+ // ===========================================================
243
+ // Local overrides (this browser only)
244
+ // ===========================================================
245
+
246
+ /**
247
+ * Force `key` to `variant` in THIS browser. Pass `null` to clear.
248
+ *
249
+ * Nothing is written to the server: the `_00_user_feature` assignment is
250
+ * untouched, so clearing restores whatever the server says. Persisted to
251
+ * localStorage on the page origin, so it survives a reload.
252
+ */
253
+ setLocalOverride(key: string, variant: string | null, payload?: unknown): void {
254
+ if (variant === null) this.overrides.delete(key);
255
+ else this.overrides.set(key, { variant, payload });
256
+ this.persistOverrides();
257
+ this.pushAll();
258
+ }
259
+
260
+ clearLocalOverrides(): void {
261
+ this.overrides.clear();
262
+ this.persistOverrides();
263
+ this.pushAll();
264
+ }
265
+
266
+ getLocalOverrides(): Record<string, FeatureFlagOverride> {
267
+ return Object.fromEntries(this.overrides);
268
+ }
269
+
270
+ /** The assignment for `key`, with any local override taking precedence. */
271
+ private resolve(key: string): FeatureFlagSnapshot {
272
+ const override = this.overrides.get(key);
273
+ if (override) return { variant: override.variant, payload: override.payload };
274
+ return this.snapshots.get(key) ?? { variant: undefined, payload: undefined };
275
+ }
276
+
277
+ private pushAll(): void {
278
+ for (const handle of this.handles) handle.set(this.resolve(handle.key));
279
+ }
280
+
281
+ private loadOverrides(): void {
282
+ try {
283
+ const raw = globalThis.localStorage?.getItem(OVERRIDE_STORAGE_KEY);
284
+ if (!raw) return;
285
+ const parsed = JSON.parse(raw) as Record<string, FeatureFlagOverride>;
286
+ for (const [key, value] of Object.entries(parsed ?? {})) {
287
+ if (value && typeof value.variant === 'string') this.overrides.set(key, value);
288
+ }
289
+ } catch (err) {
290
+ // Best-effort: a corrupt or unavailable store must never stop the
291
+ // client from booting. Same posture as the DevTools prefs helper.
292
+ this.logger.warn(
293
+ { err, Category: 'sp00ky-client::FeatureFlagModule::loadOverrides' },
294
+ 'Failed to read local feature flag overrides',
295
+ );
296
+ }
297
+ }
298
+
299
+ private persistOverrides(): void {
300
+ try {
301
+ if (this.overrides.size === 0) {
302
+ globalThis.localStorage?.removeItem(OVERRIDE_STORAGE_KEY);
303
+ return;
304
+ }
305
+ globalThis.localStorage?.setItem(
306
+ OVERRIDE_STORAGE_KEY,
307
+ JSON.stringify(this.getLocalOverrides()),
308
+ );
309
+ } catch (err) {
310
+ this.logger.warn(
311
+ { err, Category: 'sp00ky-client::FeatureFlagModule::persistOverrides' },
312
+ 'Failed to persist local feature flag overrides',
313
+ );
207
314
  }
208
315
  }
209
316
  }