@spooky-sync/core 0.0.1-canary.33 → 0.0.1-canary.331

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 (266) hide show
  1. package/AGENTS.md +84 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2080 -142
  4. package/dist/index.js +16009 -2480
  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/otel/index.js +3 -3
  9. package/dist/pure.d.ts +373 -0
  10. package/dist/pure.js +24 -0
  11. package/dist/sqlite-open.js +392 -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 +477 -0
  18. package/dist/types.d.ts +1857 -38
  19. package/dist/worker-edges.js +480 -0
  20. package/dist/worker-impersonation.js +60 -0
  21. package/dist/worker-ref-tables.d.ts +48 -0
  22. package/dist/worker-types.d.ts +112 -0
  23. package/dist/worker-types.js +73 -0
  24. package/package.json +28 -7
  25. package/scripts/check-broker-bundle.mjs +33 -0
  26. package/scripts/check-worker-entries.mjs +173 -0
  27. package/skills/sp00ky-core/SKILL.md +32 -7
  28. package/skills/sp00ky-core/references/config.md +7 -1
  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 +203 -0
  32. package/src/boot/boot.saga.ts +146 -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 +80 -0
  36. package/src/boot/preload.saga.ts +40 -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 +195 -0
  40. package/src/client/bucket-handle.ts +352 -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.test.ts +74 -0
  46. package/src/client/services.ts +434 -0
  47. package/src/client/sp00ky-client.test.ts +341 -0
  48. package/src/client/sp00ky-client.ts +625 -0
  49. package/src/events/events.test.ts +2 -1
  50. package/src/events/index.ts +3 -0
  51. package/src/index.ts +69 -1
  52. package/src/kernel/constants.test.ts +19 -0
  53. package/src/kernel/constants.ts +80 -0
  54. package/src/kernel/effects.test.ts +40 -0
  55. package/src/kernel/effects.ts +167 -0
  56. package/src/kernel/events.ts +57 -0
  57. package/src/kernel/interpreter.test.ts +116 -0
  58. package/src/kernel/interpreter.ts +148 -0
  59. package/src/kernel/saga.test.ts +89 -0
  60. package/src/kernel/saga.ts +73 -0
  61. package/src/live/index.test.ts +512 -0
  62. package/src/live/index.ts +1059 -0
  63. package/src/modules/app-release/index.test.ts +125 -0
  64. package/src/modules/app-release/index.ts +209 -0
  65. package/src/modules/auth/auth.local-first.test.ts +228 -0
  66. package/src/modules/auth/events/index.ts +9 -2
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +205 -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 +476 -22
  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 +125 -0
  75. package/src/modules/crdt/crdt.test.ts +469 -0
  76. package/src/modules/crdt/hash.ts +103 -0
  77. package/src/modules/crdt/index.ts +757 -0
  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 +746 -95
  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.test.ts +74 -0
  89. package/src/modules/devtools/versions.ts +110 -0
  90. package/src/modules/feature-flag/index.test.ts +298 -0
  91. package/src/modules/feature-flag/index.ts +316 -0
  92. package/src/modules/ref-tables.test.ts +93 -0
  93. package/src/modules/ref-tables.ts +91 -0
  94. package/src/modules/web-push/index.test.ts +824 -0
  95. package/src/modules/web-push/index.ts +1027 -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 +301 -0
  102. package/src/mutation/push.saga.ts +225 -0
  103. package/src/mutation/rows.test.ts +231 -0
  104. package/src/mutation/rows.ts +427 -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 +316 -0
  108. package/src/mutation/write.saga.ts +268 -0
  109. package/src/otel/index.ts +10 -7
  110. package/src/pure.ts +66 -0
  111. package/src/push/types.ts +174 -0
  112. package/src/query/anon-query-isolation.integration.test.ts +527 -0
  113. package/src/query/env.test.ts +23 -0
  114. package/src/query/env.ts +65 -0
  115. package/src/query/fetch.saga.test.ts +199 -0
  116. package/src/query/fetch.saga.ts +120 -0
  117. package/src/query/hash.test.ts +14 -0
  118. package/src/query/hash.ts +18 -0
  119. package/src/query/id-set-plan.test.ts +132 -0
  120. package/src/query/lifecycle.saga.test.ts +274 -0
  121. package/src/query/lifecycle.saga.ts +186 -0
  122. package/src/query/list-ref-live.integration.test.ts +203 -0
  123. package/src/query/materialize.saga.test.ts +115 -0
  124. package/src/query/materialize.saga.ts +84 -0
  125. package/src/query/materialize.test.ts +58 -0
  126. package/src/query/materialize.ts +57 -0
  127. package/src/query/membership.saga.test.ts +407 -0
  128. package/src/query/membership.saga.ts +282 -0
  129. package/src/query/membership.test.ts +118 -0
  130. package/src/query/membership.ts +201 -0
  131. package/src/query/register.saga.test.ts +311 -0
  132. package/src/query/register.saga.ts +235 -0
  133. package/src/query/render-set.test.ts +47 -0
  134. package/src/query/render-set.ts +71 -0
  135. package/src/query/sql.test.ts +118 -0
  136. package/src/query/sql.ts +157 -0
  137. package/src/query/window-query.test.ts +70 -0
  138. package/src/query/window-query.ts +208 -0
  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 +156 -61
  152. package/src/services/database/engine-factory.ts +33 -0
  153. package/src/services/database/errors.ts +34 -0
  154. package/src/services/database/events/index.ts +2 -1
  155. package/src/services/database/index.ts +7 -0
  156. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  157. package/src/services/database/local-migrator.integration.test.ts +110 -0
  158. package/src/services/database/local-migrator.ts +61 -16
  159. package/src/services/database/local.test.ts +150 -0
  160. package/src/services/database/local.ts +508 -63
  161. package/src/services/database/plan-render.test.ts +159 -0
  162. package/src/services/database/plan-render.ts +108 -0
  163. package/src/services/database/relation-resolver.test.ts +484 -0
  164. package/src/services/database/relation-resolver.ts +0 -0
  165. package/src/services/database/remote.ts +285 -6
  166. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  167. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  168. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  169. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  170. package/src/services/database/sqlite-column-reset.ts +91 -0
  171. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  172. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  173. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  174. package/src/services/database/sqlite-lock-verify.ts +45 -0
  175. package/src/services/database/sqlite-open.test.ts +150 -0
  176. package/src/services/database/sqlite-open.ts +164 -0
  177. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  178. package/src/services/database/sqlite-plan-sql.ts +196 -0
  179. package/src/services/database/sqlite-projection.test.ts +121 -0
  180. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  181. package/src/services/database/sqlite-select.test.ts +261 -0
  182. package/src/services/database/sqlite-select.ts +131 -0
  183. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  184. package/src/services/database/sqlite-transport.ts +224 -0
  185. package/src/services/database/sqlite-worker.ts +437 -0
  186. package/src/services/database/surql-translate.ts +417 -0
  187. package/src/services/database/surreal-cache-engine.ts +163 -0
  188. package/src/services/logger/index.test.ts +132 -0
  189. package/src/services/logger/index.ts +189 -7
  190. package/src/services/persistence/localstorage.ts +2 -2
  191. package/src/services/persistence/resilient.ts +10 -3
  192. package/src/services/persistence/surrealdb.ts +4 -4
  193. package/src/services/stream-processor/index.ts +806 -67
  194. package/src/services/stream-processor/permissions.test.ts +47 -0
  195. package/src/services/stream-processor/permissions.ts +53 -0
  196. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  197. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  198. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  199. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  200. package/src/services/stream-processor/wasm-types.ts +58 -2
  201. package/src/services/tabs/broker-client.ts +284 -0
  202. package/src/services/tabs/broker.test.ts +381 -0
  203. package/src/services/tabs/coordinator.test.ts +386 -0
  204. package/src/services/tabs/coordinator.ts +646 -0
  205. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  206. package/src/services/tabs/leader-locks.ts +75 -0
  207. package/src/services/tabs/protocol.ts +262 -0
  208. package/src/services/tabs/support.ts +36 -0
  209. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  210. package/src/sp00ky.ts +5 -395
  211. package/src/state/client-state.ts +208 -0
  212. package/src/state/lifecycle.test.ts +141 -0
  213. package/src/state/lifecycle.ts +99 -0
  214. package/src/state/reducers.test.ts +306 -0
  215. package/src/state/reducers.ts +531 -0
  216. package/src/state/selectors.test.ts +188 -0
  217. package/src/state/selectors.ts +258 -0
  218. package/src/sw/index.test.ts +582 -0
  219. package/src/sw/index.ts +607 -0
  220. package/src/sw/store.ts +96 -0
  221. package/src/sync/connection.saga.test.ts +97 -0
  222. package/src/sync/connection.saga.ts +89 -0
  223. package/src/sync/live.saga.test.ts +178 -0
  224. package/src/sync/live.saga.ts +107 -0
  225. package/src/sync/policy.health.test.ts +56 -0
  226. package/src/sync/policy.test.ts +663 -0
  227. package/src/sync/policy.ts +515 -0
  228. package/src/sync/poll.saga.test.ts +51 -0
  229. package/src/sync/poll.saga.ts +36 -0
  230. package/src/sync/tabs.saga.test.ts +78 -0
  231. package/src/sync/tabs.saga.ts +96 -0
  232. package/src/testing/adapters.ts +137 -0
  233. package/src/testing/build.ts +63 -0
  234. package/src/testing/fake-services.ts +63 -0
  235. package/src/testing/run-pure.test.ts +92 -0
  236. package/src/testing/run-pure.ts +128 -0
  237. package/src/testing/services.ts +17 -0
  238. package/src/types.ts +633 -10
  239. package/src/utils/blurhash.ts +90 -0
  240. package/src/utils/edges.ts +39 -0
  241. package/src/utils/error-classification.test.ts +54 -0
  242. package/src/utils/error-classification.ts +25 -0
  243. package/src/utils/index.ts +89 -12
  244. package/src/utils/parser.test.ts +67 -102
  245. package/src/utils/parser.ts +64 -2
  246. package/src/utils/semver.test.ts +32 -0
  247. package/src/utils/semver.ts +30 -0
  248. package/src/utils/sha256.ts +15 -0
  249. package/src/utils/surql.ts +29 -18
  250. package/src/utils/utils.test.ts +3 -2
  251. package/tsdown.config.ts +117 -3
  252. package/vitest.config.ts +48 -0
  253. package/src/modules/cache/index.ts +0 -241
  254. package/src/modules/cache/types.ts +0 -19
  255. package/src/modules/data/data.test.ts +0 -58
  256. package/src/modules/data/index.ts +0 -879
  257. package/src/modules/sync/engine.ts +0 -173
  258. package/src/modules/sync/events/index.ts +0 -77
  259. package/src/modules/sync/index.ts +0 -3
  260. package/src/modules/sync/queue/index.ts +0 -2
  261. package/src/modules/sync/queue/queue-down.ts +0 -89
  262. package/src/modules/sync/queue/queue-up.ts +0 -223
  263. package/src/modules/sync/scheduler.ts +0 -84
  264. package/src/modules/sync/sync.ts +0 -421
  265. package/src/modules/sync/utils.test.ts +0 -311
  266. package/src/modules/sync/utils.ts +0 -167
@@ -0,0 +1,298 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
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
+ }
19
+
20
+ // Minimal mocks for the three deps the module touches. The DataModule mock
21
+ // captures the single subscribe callback so a test can push live results, and
22
+ // counts query() calls to assert the query is SHARED (one registration for all
23
+ // flags), not per-key.
24
+ function makeDeps() {
25
+ let subCb: ((records: unknown[]) => void) | null = null;
26
+ const calls: Array<{ sql: string; params: unknown }> = [];
27
+ let authCb: ((userId: string | null) => void) | null = null;
28
+
29
+ const dataModule = {
30
+ query: async (_table: string, sql: string, params: unknown) => {
31
+ calls.push({ sql, params });
32
+ return `hash:${calls.length}`;
33
+ },
34
+ subscribe: (_hash: string, cb: (records: unknown[]) => void) => {
35
+ subCb = cb;
36
+ return () => {
37
+ subCb = null;
38
+ };
39
+ },
40
+ };
41
+ const sync = { enqueueDownEvent: () => {} };
42
+ const auth = {
43
+ subscribe: (cb: (userId: string | null) => void) => {
44
+ authCb = cb;
45
+ return () => {
46
+ authCb = null;
47
+ };
48
+ },
49
+ };
50
+ const logger = { child: () => ({ warn: () => {} }) };
51
+
52
+ const deps = { dataModule, sync, auth, logger } as any;
53
+ return {
54
+ deps,
55
+ calls,
56
+ push: (records: unknown[]) => subCb?.(records),
57
+ setUser: (id: string | null) => authCb?.(id),
58
+ hasSub: () => subCb !== null,
59
+ };
60
+ }
61
+
62
+ const tick = () => new Promise((r) => setTimeout(r, 0));
63
+
64
+ describe('FeatureFlagModule', () => {
65
+ let env: ReturnType<typeof makeDeps>;
66
+ let mod: FeatureFlagModule<any>;
67
+
68
+ beforeEach(() => {
69
+ env = makeDeps();
70
+ mod = new FeatureFlagModule(env.deps);
71
+ });
72
+
73
+ it('registers ONE shared, unfiltered query for many flags', async () => {
74
+ mod.feature('alpha');
75
+ mod.feature('beta');
76
+ mod.feature('gamma');
77
+ await tick();
78
+
79
+ expect(env.calls.length).toBe(1);
80
+ expect(env.calls[0].sql).not.toContain('WHERE');
81
+ expect(env.calls[0].sql).toContain('FROM _00_user_feature');
82
+ expect(env.calls[0].params).toEqual({});
83
+ });
84
+
85
+ it('fans the shared result out to each handle by key', async () => {
86
+ const alpha = mod.feature('alpha', { fallback: 'off' });
87
+ const beta = mod.feature('beta', { fallback: 'off' });
88
+ const missing = mod.feature('missing', { fallback: 'off' });
89
+ await tick();
90
+
91
+ env.push([
92
+ { key: 'alpha', variant: 'on' },
93
+ { key: 'beta', variant: 'off' },
94
+ ]);
95
+
96
+ expect(alpha.enabled()).toBe(true);
97
+ expect(alpha.variant()).toBe('on');
98
+ expect(beta.enabled()).toBe(false); // assigned 'off'
99
+ expect(missing.enabled()).toBe(false); // no row → fallback 'off'
100
+ });
101
+
102
+ it('observes NEW assignments live without re-registering', async () => {
103
+ const flag = mod.feature('live', { fallback: 'off' });
104
+ await tick();
105
+
106
+ env.push([]); // user starts with no assignment
107
+ expect(flag.enabled()).toBe(false);
108
+
109
+ env.push([{ key: 'live', variant: 'on' }]); // assigned while observing
110
+ expect(flag.enabled()).toBe(true);
111
+
112
+ expect(env.calls.length).toBe(1); // still the same single query
113
+ });
114
+
115
+ it('seeds a late-created handle from the already-loaded snapshot', async () => {
116
+ mod.feature('alpha', { fallback: 'off' });
117
+ await tick();
118
+ env.push([{ key: 'alpha', variant: 'on' }]);
119
+
120
+ const late = mod.feature('alpha', { fallback: 'off' });
121
+ expect(late.enabled()).toBe(true); // no fallback flash
122
+ });
123
+
124
+ it('clears flags and re-observes on user change', async () => {
125
+ mod.init();
126
+ const flag = mod.feature('alpha', { fallback: 'off' });
127
+ await tick();
128
+ env.push([{ key: 'alpha', variant: 'on' }]);
129
+ expect(flag.enabled()).toBe(true);
130
+
131
+ env.setUser('user:other'); // sign-in as a different user
132
+ await tick();
133
+ expect(flag.enabled()).toBe(false); // cleared until the new query resolves
134
+ expect(env.hasSub()).toBe(true); // re-registered for the new user
135
+ });
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
+
@@ -0,0 +1,316 @@
1
+ import type { SchemaStructure } from '@spooky-sync/query-builder';
2
+ import type { AuthService } from '../auth/index';
3
+ import type { Logger } from '../../services/logger/index';
4
+ import type { QueryTimeToLive } from '../../types';
5
+
6
+ // One shared LIVE query over ALL of the signed-in user's assignments — the
7
+ // `_00_user_feature` select permission scopes it to `user = $auth.id`, so no
8
+ // per-key `WHERE key = $key` param is needed. A single registration means every
9
+ // flag the user is (or becomes) assigned is observed at once: new assignments
10
+ // stream in live, and a handle for an unassigned key simply resolves to its
11
+ // fallback. Avoids one-registration-per-flag and the param-filtered live query.
12
+ const FEATURE_QUERY = 'SELECT key, variant, payload FROM _00_user_feature';
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
+
20
+ interface FeatureRow {
21
+ key?: string;
22
+ variant?: string;
23
+ payload?: unknown;
24
+ }
25
+
26
+ export interface FeatureFlagSnapshot {
27
+ variant: string | undefined;
28
+ payload: unknown | undefined;
29
+ }
30
+
31
+ export interface FeatureFlagOptions {
32
+ fallback?: string;
33
+ ttl?: QueryTimeToLive;
34
+ }
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
+
46
+ export class FeatureFlagHandle {
47
+ private latest: FeatureFlagSnapshot = { variant: undefined, payload: undefined };
48
+ private listeners = new Set<(s: FeatureFlagSnapshot) => void>();
49
+ private unsubscribeFn: (() => void) | null = null;
50
+ private onCloseFn: (() => void) | null = null;
51
+ private closed = false;
52
+
53
+ constructor(
54
+ public readonly key: string,
55
+ public readonly fallback: string | undefined,
56
+ ) {}
57
+
58
+ attach(unsubscribe: () => void): void {
59
+ this.unsubscribeFn?.();
60
+ this.unsubscribeFn = unsubscribe;
61
+ }
62
+
63
+ detach(): void {
64
+ this.unsubscribeFn?.();
65
+ this.unsubscribeFn = null;
66
+ }
67
+
68
+ set(snapshot: FeatureFlagSnapshot): void {
69
+ if (this.closed) return;
70
+ this.latest = snapshot;
71
+ for (const cb of this.listeners) cb(snapshot);
72
+ }
73
+
74
+ variant(): string | undefined {
75
+ return this.latest.variant ?? this.fallback;
76
+ }
77
+
78
+ payload<T = unknown>(): T | undefined {
79
+ return this.latest.payload as T | undefined;
80
+ }
81
+
82
+ enabled(): boolean {
83
+ const v = this.variant();
84
+ return v !== undefined && v !== 'off';
85
+ }
86
+
87
+ subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void {
88
+ this.listeners.add(cb);
89
+ cb({ variant: this.variant(), payload: this.latest.payload });
90
+ return () => {
91
+ this.listeners.delete(cb);
92
+ };
93
+ }
94
+
95
+ onClose(cb: () => void): void {
96
+ this.onCloseFn = cb;
97
+ }
98
+
99
+ close(): void {
100
+ if (this.closed) return;
101
+ this.closed = true;
102
+ this.listeners.clear();
103
+ this.detach();
104
+ this.onCloseFn?.();
105
+ }
106
+ }
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
+
118
+ export interface FeatureFlagModuleDeps<S extends SchemaStructure> {
119
+ dataModule: LiveQueryPort;
120
+ sync: RemoteRegisterPort;
121
+ auth: Pick<AuthService<S>, 'subscribe'>;
122
+ logger: Logger;
123
+ }
124
+
125
+ export class FeatureFlagModule<S extends SchemaStructure> {
126
+ private logger: Logger;
127
+ private handles = new Set<FeatureFlagHandle>();
128
+ private authUnsubscribe: (() => void) | null = null;
129
+ private lastUserId: string | null = null;
130
+
131
+ // The single shared live query over the user's assignments.
132
+ private querySubscription: (() => void) | null = null;
133
+ private starting = false;
134
+ // Longest TTL any caller asked for (the query is shared across all flags).
135
+ private ttl: QueryTimeToLive = '10m';
136
+ // Latest assignment per key, plus whether the query has resolved at least
137
+ // once (so a handle created before the first result knows to wait vs. fall
138
+ // back). `snapshots` only holds ASSIGNED keys; an absent key → fallback.
139
+ private snapshots = new Map<string, FeatureFlagSnapshot>();
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>();
144
+
145
+ constructor(private deps: FeatureFlagModuleDeps<S>) {
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();
150
+ }
151
+
152
+ init(): void {
153
+ if (this.authUnsubscribe) return;
154
+ this.authUnsubscribe = this.deps.auth.subscribe((userId) => {
155
+ if (userId === this.lastUserId) return;
156
+ this.lastUserId = userId;
157
+ void this.refresh();
158
+ });
159
+ }
160
+
161
+ feature(key: string, options: FeatureFlagOptions = {}): FeatureFlagHandle {
162
+ const handle = new FeatureFlagHandle(key, options.fallback);
163
+ this.handles.add(handle);
164
+ handle.onClose(() => this.handles.delete(handle));
165
+ if (options.ttl) this.ttl = options.ttl;
166
+ // If the shared query already resolved, seed this handle immediately so a
167
+ // late `feature()` call doesn't flash the fallback for an assigned key.
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));
172
+ }
173
+ void this.ensureStarted();
174
+ return handle;
175
+ }
176
+
177
+ async closeAll(): Promise<void> {
178
+ this.authUnsubscribe?.();
179
+ this.authUnsubscribe = null;
180
+ this.teardownQuery();
181
+ for (const handle of [...this.handles]) handle.close();
182
+ }
183
+
184
+ /** Auth changed: drop the old user's query/snapshots and re-observe. */
185
+ private async refresh(): Promise<void> {
186
+ this.teardownQuery();
187
+ this.loaded = false;
188
+ this.snapshots.clear();
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.
192
+ for (const handle of this.handles) {
193
+ handle.set(this.resolve(handle.key));
194
+ }
195
+ await this.ensureStarted();
196
+ }
197
+
198
+ private teardownQuery(): void {
199
+ this.querySubscription?.();
200
+ this.querySubscription = null;
201
+ }
202
+
203
+ /** Start the single shared live query (idempotent; no-op with no handles). */
204
+ private async ensureStarted(): Promise<void> {
205
+ if (this.querySubscription || this.starting || this.handles.size === 0) return;
206
+ this.starting = true;
207
+ try {
208
+ const hash = await this.deps.dataModule.query(
209
+ '_00_user_feature' as any,
210
+ FEATURE_QUERY,
211
+ {},
212
+ this.ttl,
213
+ );
214
+ this.deps.sync.enqueueDownEvent({ type: 'register', payload: { hash } });
215
+ this.querySubscription = this.deps.dataModule.subscribe(
216
+ hash,
217
+ (records) => this.applyRecords(records as FeatureRow[]),
218
+ { immediate: true },
219
+ );
220
+ } catch (err) {
221
+ this.logger.warn(
222
+ { err, Category: 'sp00ky-client::FeatureFlagModule::register' },
223
+ 'Failed to register feature flag query',
224
+ );
225
+ } finally {
226
+ this.starting = false;
227
+ }
228
+ }
229
+
230
+ /** Live query result → per-key snapshots → push to every active handle. */
231
+ private applyRecords(records: FeatureRow[]): void {
232
+ this.snapshots.clear();
233
+ for (const row of records ?? []) {
234
+ if (row && typeof row.key === 'string') {
235
+ this.snapshots.set(row.key, { variant: row.variant, payload: row.payload });
236
+ }
237
+ }
238
+ this.loaded = true;
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
+ );
314
+ }
315
+ }
316
+ }