@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.
- package/AGENTS.md +58 -21
- package/README.md +59 -16
- package/dist/index.d.ts +2235 -908
- package/dist/index.js +20424 -5052
- package/dist/live.d.ts +149 -0
- package/dist/live.js +739 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/pure.d.ts +401 -0
- package/dist/pure.js +24 -0
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2639 -0
- package/dist/sqlite-open.js +392 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +439 -0
- package/dist/sw.d.ts +207 -0
- package/dist/sw.js +393 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +477 -0
- package/dist/types.d.ts +2084 -82
- package/dist/worker-edges.js +498 -0
- package/dist/worker-impersonation.js +60 -0
- package/dist/worker-ref-tables.d.ts +48 -0
- package/dist/worker-types.d.ts +112 -0
- package/dist/worker-types.js +73 -0
- package/package.json +39 -8
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +186 -0
- package/skills/sp00ky-core/SKILL.md +44 -8
- package/skills/sp00ky-core/references/config.md +8 -2
- package/src/boot/auth-flip.saga.test.ts +174 -0
- package/src/boot/auth-flip.saga.ts +77 -0
- package/src/boot/boot.saga.test.ts +203 -0
- package/src/boot/boot.saga.ts +146 -0
- package/src/boot/bucket-switch.saga.test.ts +191 -0
- package/src/boot/bucket-switch.saga.ts +151 -0
- package/src/boot/preload.saga.test.ts +96 -0
- package/src/boot/preload.saga.ts +45 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/client/bucket-handle.test.ts +195 -0
- package/src/client/bucket-handle.ts +372 -0
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/router.test.ts +59 -0
- package/src/client/router.ts +104 -0
- package/src/client/runtime.test.ts +319 -0
- package/src/client/runtime.ts +307 -0
- package/src/client/services.test.ts +74 -0
- package/src/client/services.ts +440 -0
- package/src/client/sp00ky-client.test.ts +570 -0
- package/src/client/sp00ky-client.ts +875 -0
- package/src/index.ts +87 -0
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +94 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +181 -0
- package/src/kernel/events.ts +60 -0
- package/src/kernel/interpreter.test.ts +133 -0
- package/src/kernel/interpreter.ts +151 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/live/index.test.ts +512 -0
- package/src/live/index.ts +1059 -0
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +209 -0
- package/src/modules/auth/auth.local-first.test.ts +228 -0
- package/src/modules/auth/auth.session-recheck.test.ts +140 -0
- package/src/modules/auth/events/index.ts +7 -1
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.integration.test.ts +209 -0
- package/src/modules/auth/impersonation.test.ts +377 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +516 -34
- package/src/modules/channel/channel.test.ts +752 -0
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +1497 -0
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +472 -0
- package/src/modules/crdt/acceptance.ts +75 -0
- package/src/modules/crdt/bytes.ts +50 -0
- package/src/modules/crdt/crdt-field.ts +82 -238
- package/src/modules/crdt/crdt.test.ts +546 -0
- package/src/modules/crdt/hash.ts +103 -0
- package/src/modules/crdt/index.ts +740 -271
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/crdt/mirror.ts +37 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +661 -99
- package/src/modules/devtools/mutations.test.ts +92 -0
- package/src/modules/devtools/mutations.ts +160 -0
- package/src/modules/devtools/notify-throttle.test.ts +166 -0
- package/src/modules/devtools/state-shape.test.ts +263 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +169 -0
- package/src/modules/devtools/versions.ts +29 -0
- package/src/modules/feature-flag/index.test.ts +179 -1
- package/src/modules/feature-flag/index.ts +117 -10
- package/src/modules/ref-tables.test.ts +28 -1
- package/src/modules/ref-tables.ts +23 -1
- package/src/modules/web-push/index.test.ts +824 -0
- package/src/modules/web-push/index.ts +1027 -0
- package/src/mutation/ingest-outage.integration.test.ts +400 -0
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/mutation/mutation-id.test.ts +37 -0
- package/src/mutation/mutation-id.ts +35 -0
- package/src/mutation/pending-writes.integration.test.ts +175 -0
- package/src/mutation/push.saga.test.ts +361 -0
- package/src/mutation/push.saga.ts +245 -0
- package/src/mutation/rows.test.ts +278 -0
- package/src/mutation/rows.ts +515 -0
- package/src/mutation/tray.saga.test.ts +63 -0
- package/src/mutation/tray.saga.ts +48 -0
- package/src/mutation/write.saga.test.ts +436 -0
- package/src/mutation/write.saga.ts +384 -0
- package/src/pure.ts +66 -0
- package/src/push/types.ts +174 -0
- package/src/query/anon-query-isolation.integration.test.ts +531 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +65 -0
- package/src/query/fetch.saga.test.ts +199 -0
- package/src/query/fetch.saga.ts +120 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/query/id-set-plan.test.ts +132 -0
- package/src/query/lifecycle.saga.test.ts +274 -0
- package/src/query/lifecycle.saga.ts +186 -0
- package/src/query/list-ref-live.integration.test.ts +203 -0
- package/src/query/materialize.saga.test.ts +216 -0
- package/src/query/materialize.saga.ts +83 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +133 -0
- package/src/query/membership.saga.test.ts +514 -0
- package/src/query/membership.saga.ts +339 -0
- package/src/query/membership.test.ts +151 -0
- package/src/query/membership.ts +234 -0
- package/src/query/register.saga.test.ts +430 -0
- package/src/query/register.saga.ts +330 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/session-guard.integration.test.ts +304 -0
- package/src/query/sql.test.ts +118 -0
- package/src/query/sql.ts +174 -0
- package/src/{modules/data → query}/window-query.test.ts +22 -4
- package/src/{modules/data → query}/window-query.ts +86 -8
- package/src/services/blobs/blob-cache.test.ts +359 -0
- package/src/services/blobs/blob-cache.ts +603 -0
- package/src/services/blobs/blob-manifest.ts +227 -0
- package/src/services/blobs/blob-store.test.ts +77 -0
- package/src/services/blobs/blob-store.ts +359 -0
- package/src/services/blobs/blob.fixture.ts +90 -0
- package/src/services/blobs/index.ts +70 -0
- package/src/services/database/cache-engine.ts +223 -0
- package/src/services/database/connection-supervisor.test.ts +318 -0
- package/src/services/database/connection-supervisor.ts +422 -0
- package/src/services/database/database.query-timeout.test.ts +140 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +151 -56
- package/src/services/database/engine-factory.ts +40 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/index.ts +8 -0
- package/src/services/database/landed-body-clear.integration.test.ts +236 -0
- package/src/services/database/local-migrator.integration.test.ts +110 -0
- package/src/services/database/local-migrator.ts +54 -9
- package/src/services/database/local.test.ts +117 -0
- package/src/services/database/local.ts +364 -74
- package/src/services/database/plan-render.test.ts +159 -0
- package/src/services/database/plan-render.ts +108 -0
- package/src/services/database/relation-resolver.test.ts +484 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +283 -4
- package/src/services/database/rows-cache-engine.test.ts +1014 -0
- package/src/services/database/rows-cache-engine.ts +921 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +225 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +588 -0
- package/src/services/database/sqlite-cache-engine.test.ts +649 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1422 -0
- package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
- package/src/services/database/sqlite-column-reset.ts +91 -0
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
- package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
- package/src/services/database/sqlite-lock-verify.test.ts +33 -0
- package/src/services/database/sqlite-lock-verify.ts +45 -0
- package/src/services/database/sqlite-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +164 -0
- package/src/services/database/sqlite-plan-sql.ts +196 -0
- package/src/services/database/sqlite-projection.test.ts +121 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +261 -0
- package/src/services/database/sqlite-select.ts +131 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +231 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +417 -0
- package/src/services/database/surreal-cache-engine.ts +163 -0
- package/src/services/logger/index.test.ts +132 -0
- package/src/services/logger/index.ts +187 -6
- package/src/services/persistence/surrealdb.ts +2 -2
- package/src/services/stream-processor/index.ts +621 -93
- package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
- package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
- package/src/services/stream-processor/wasm-types.ts +41 -1
- package/src/services/tabs/broker-client.ts +284 -0
- package/src/services/tabs/broker.test.ts +381 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +646 -0
- package/src/services/tabs/fake-ports.fixture.ts +112 -0
- package/src/services/tabs/leader-locks.ts +75 -0
- package/src/services/tabs/protocol.ts +262 -0
- package/src/services/tabs/support.ts +38 -0
- package/src/services/tabs/tabs-broker-worker.ts +652 -0
- package/src/sp00ky.ts +5 -648
- package/src/state/client-state.ts +231 -0
- package/src/state/lifecycle.test.ts +184 -0
- package/src/state/lifecycle.ts +127 -0
- package/src/state/reducers.test.ts +337 -0
- package/src/state/reducers.ts +571 -0
- package/src/state/selectors.test.ts +203 -0
- package/src/state/selectors.ts +264 -0
- package/src/sw/index.test.ts +582 -0
- package/src/sw/index.ts +607 -0
- package/src/sw/store.ts +96 -0
- package/src/sync/connection.saga.test.ts +97 -0
- package/src/sync/connection.saga.ts +89 -0
- package/src/sync/live.saga.test.ts +229 -0
- package/src/sync/live.saga.ts +116 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
- package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +78 -0
- package/src/sync/tabs.saga.ts +96 -0
- package/src/testing/adapters.ts +137 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +63 -0
- package/src/testing/run-pure.test.ts +92 -0
- package/src/testing/run-pure.ts +128 -0
- package/src/testing/services.ts +17 -0
- package/src/types.ts +601 -25
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/edges.ts +57 -0
- package/src/utils/error-classification.test.ts +116 -0
- package/src/utils/error-classification.ts +74 -0
- package/src/utils/index.ts +58 -3
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +62 -1
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/sha256.ts +15 -0
- package/src/utils/surql.ts +17 -15
- package/src/utils/utils.test.ts +3 -2
- package/tsdown.config.ts +105 -4
- package/vitest.config.ts +52 -0
- package/src/modules/cache/index.ts +0 -253
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/crdt/crdt-hydration.test.ts +0 -206
- package/src/modules/data/data.status.test.ts +0 -108
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -1491
- package/src/modules/sync/engine.ts +0 -227
- package/src/modules/sync/events/index.ts +0 -84
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.ts +0 -90
- package/src/modules/sync/queue/queue-up.ts +0 -224
- package/src/modules/sync/scheduler.ts +0 -121
- package/src/modules/sync/sync.ts +0 -1244
- 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:
|
|
96
|
-
sync:
|
|
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
|
-
|
|
139
|
-
|
|
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(
|
|
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
|
-
|
|
206
|
-
|
|
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
|
}
|