@mhjuma/traverse 0.1.0

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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +46 -0
  3. package/src/bootstrap.spec.tsx +290 -0
  4. package/src/bootstrap.tsx +195 -0
  5. package/src/colors.ts +23 -0
  6. package/src/components/ChartPanel/ChartPanel.logic.spec.ts +358 -0
  7. package/src/components/ChartPanel/ChartPanel.logic.ts +318 -0
  8. package/src/components/ChartPanel/ChartPanel.spec.tsx +331 -0
  9. package/src/components/ChartPanel/ChartPanel.styles.ts +14 -0
  10. package/src/components/ChartPanel/ChartPanel.tsx +151 -0
  11. package/src/components/ConnectionDialog/ConnectionDialog.spec.tsx +767 -0
  12. package/src/components/ConnectionDialog/ConnectionDialog.tsx +652 -0
  13. package/src/components/ConnectionDialog/ConnectionRow.spec.tsx +104 -0
  14. package/src/components/ConnectionDialog/ConnectionRow.tsx +177 -0
  15. package/src/components/EditorToolbar/EditorToolbar.spec.tsx +599 -0
  16. package/src/components/EditorToolbar/EditorToolbar.tsx +259 -0
  17. package/src/components/Explorer/Explorer.spec.tsx +615 -0
  18. package/src/components/Explorer/Explorer.tsx +49 -0
  19. package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.spec.ts +715 -0
  20. package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.ts +324 -0
  21. package/src/components/ExplorerWorkspace/ExplorerWorkspace.spec.tsx +450 -0
  22. package/src/components/ExplorerWorkspace/ExplorerWorkspace.styles.ts +478 -0
  23. package/src/components/ExplorerWorkspace/ExplorerWorkspace.tsx +648 -0
  24. package/src/components/ExplorerWorkspace/kqlLanguage.spec.ts +321 -0
  25. package/src/components/ExplorerWorkspace/kqlLanguage.ts +155 -0
  26. package/src/components/ResultsPanel/ElapsedTimer.spec.tsx +51 -0
  27. package/src/components/ResultsPanel/ElapsedTimer.tsx +15 -0
  28. package/src/components/ResultsPanel/HistoryItem.spec.tsx +123 -0
  29. package/src/components/ResultsPanel/HistoryItem.tsx +56 -0
  30. package/src/components/ResultsPanel/ResultSetTab.tsx +18 -0
  31. package/src/components/ResultsPanel/ResultsPanel.spec.tsx +1194 -0
  32. package/src/components/ResultsPanel/ResultsPanel.tsx +321 -0
  33. package/src/components/ResultsPanel/TabButton.tsx +11 -0
  34. package/src/components/ResultsTable/ColumnHeader.tsx +42 -0
  35. package/src/components/ResultsTable/ColumnPickerItem.tsx +16 -0
  36. package/src/components/ResultsTable/FilterCell.tsx +24 -0
  37. package/src/components/ResultsTable/ResultsTable.logic.spec.ts +655 -0
  38. package/src/components/ResultsTable/ResultsTable.logic.ts +264 -0
  39. package/src/components/ResultsTable/ResultsTable.spec.tsx +930 -0
  40. package/src/components/ResultsTable/ResultsTable.styles.ts +108 -0
  41. package/src/components/ResultsTable/ResultsTable.tsx +501 -0
  42. package/src/components/ResultsTable/VirtualCell.spec.tsx +55 -0
  43. package/src/components/ResultsTable/VirtualCell.tsx +32 -0
  44. package/src/components/ResultsTable/VirtualRow.tsx +55 -0
  45. package/src/components/SchemaSidebar/FolderRow.tsx +35 -0
  46. package/src/components/SchemaSidebar/SchemaColumnItem.tsx +41 -0
  47. package/src/components/SchemaSidebar/SchemaContextMenu.spec.tsx +148 -0
  48. package/src/components/SchemaSidebar/SchemaContextMenu.tsx +49 -0
  49. package/src/components/SchemaSidebar/SchemaSidebar.logic.spec.ts +230 -0
  50. package/src/components/SchemaSidebar/SchemaSidebar.logic.ts +74 -0
  51. package/src/components/SchemaSidebar/SchemaSidebar.spec.tsx +1111 -0
  52. package/src/components/SchemaSidebar/SchemaSidebar.tsx +244 -0
  53. package/src/components/SchemaSidebar/SchemaTableItem.tsx +77 -0
  54. package/src/components/TabBar/TabBar.logic.spec.ts +127 -0
  55. package/src/components/TabBar/TabBar.logic.ts +35 -0
  56. package/src/components/TabBar/TabBar.spec.tsx +929 -0
  57. package/src/components/TabBar/TabBar.tsx +284 -0
  58. package/src/components/TabBar/TabItem.tsx +166 -0
  59. package/src/components/VegaChart/VegaChart.spec.tsx +126 -0
  60. package/src/components/VegaChart/VegaChart.tsx +224 -0
  61. package/src/config.spec.ts +44 -0
  62. package/src/config.ts +47 -0
  63. package/src/context/ExplorerColorContext.ts +14 -0
  64. package/src/context/ExplorerStateContext.ts +49 -0
  65. package/src/context/KustoClientContext.ts +12 -0
  66. package/src/context/context.spec.tsx +183 -0
  67. package/src/index.ts +14 -0
  68. package/src/services/cache.spec.ts +31 -0
  69. package/src/services/cache.ts +16 -0
  70. package/src/services/concurrency.spec.ts +139 -0
  71. package/src/services/concurrency.ts +46 -0
  72. package/src/services/kusto.spec.ts +919 -0
  73. package/src/services/kusto.ts +472 -0
  74. package/src/services/queryHistory.spec.ts +287 -0
  75. package/src/services/queryHistory.ts +146 -0
  76. package/src/services/schema.spec.ts +618 -0
  77. package/src/services/schema.ts +294 -0
  78. package/src/services/state-service.spec.ts +670 -0
  79. package/src/services/state-service.ts +602 -0
  80. package/src/services/useKustoQuery.spec.ts +234 -0
  81. package/src/services/useKustoQuery.ts +124 -0
  82. package/src/state/actions.ts +50 -0
  83. package/src/state/index.ts +3 -0
  84. package/src/state/reducer.spec.ts +644 -0
  85. package/src/state/reducer.ts +207 -0
  86. package/src/state/types.ts +54 -0
  87. package/tsconfig.json +7 -0
  88. package/tsconfig.lint.json +4 -0
  89. package/tsconfig.spec.json +7 -0
  90. package/vitest.config.ts +34 -0
@@ -0,0 +1,670 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { StateService, STORE_NAMES } from './state-service';
3
+ import type { StoreEntry } from './state-service';
4
+
5
+ // ---------------------------------------------------------------------------
6
+ // Helpers
7
+ // ---------------------------------------------------------------------------
8
+
9
+ function createMockLocalStorage(): Storage {
10
+ const store = new Map<string, string>();
11
+ return {
12
+ getItem: (key: string) => store.get(key) ?? null,
13
+ setItem: (key: string, value: string) => { store.set(key, value); },
14
+ removeItem: (key: string) => { store.delete(key); },
15
+ clear: () => store.clear(),
16
+ get length() { return store.size; },
17
+ key: (index: number) => [...store.keys()][index] ?? null,
18
+ };
19
+ }
20
+
21
+ // Stub IndexedDB as unavailable by default — tests that need IDB override this
22
+ function stubIDBUnavailable(): void {
23
+ vi.stubGlobal('indexedDB', {
24
+ open: () => {
25
+ const req = { onerror: null as (() => void) | null, onsuccess: null as (() => void) | null, onupgradeneeded: null as (() => void) | null };
26
+ queueMicrotask(() => req.onerror?.());
27
+ return req;
28
+ },
29
+ });
30
+ }
31
+
32
+ describe('StateService', () => {
33
+ let mockLS: Storage;
34
+
35
+ beforeEach(() => {
36
+ vi.spyOn(console, 'error').mockImplementation(() => {});
37
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
38
+ mockLS = createMockLocalStorage();
39
+ vi.stubGlobal('localStorage', mockLS);
40
+ stubIDBUnavailable();
41
+ });
42
+
43
+ afterEach(() => {
44
+ vi.restoreAllMocks();
45
+ vi.unstubAllGlobals();
46
+ });
47
+
48
+ describe('constructor', () => {
49
+ it('initializes all store maps', () => {
50
+ const svc = new StateService();
51
+ for (const name of STORE_NAMES) {
52
+ expect(svc.keys(name)).toEqual([]);
53
+ }
54
+ });
55
+
56
+ it('bootstraps config from localStorage', () => {
57
+ const entry: StoreEntry = { value: 'dark', timestamp: Date.now() };
58
+ mockLS.setItem('traverse-state:config:theme', JSON.stringify(entry));
59
+ const svc = new StateService();
60
+ expect(svc.get('config', 'theme')).toBe('dark');
61
+ });
62
+
63
+ it('bootstraps explorerConnections from localStorage', () => {
64
+ const entry: StoreEntry = { value: [{ name: 'test' }], timestamp: Date.now() };
65
+ mockLS.setItem('traverse-state:explorerConnections:list', JSON.stringify(entry));
66
+ const svc = new StateService();
67
+ expect(svc.get<{ name: string }[]>('explorerConnections', 'list')).toEqual([{ name: 'test' }]);
68
+ });
69
+
70
+ it('skips expired bootstrap entries', () => {
71
+ const entry: StoreEntry = { value: 'old', timestamp: Date.now() - 999999999, ttl: 1 };
72
+ mockLS.setItem('traverse-state:config:stale', JSON.stringify(entry));
73
+ const svc = new StateService();
74
+ expect(svc.get('config', 'stale')).toBeNull();
75
+ });
76
+
77
+ it('handles corrupt localStorage entries gracefully', () => {
78
+ mockLS.setItem('traverse-state:config:corrupt', 'not-json{{{');
79
+ const svc = new StateService();
80
+ expect(svc.get('config', 'corrupt')).toBeNull();
81
+ });
82
+
83
+ it('handles inaccessible localStorage gracefully', () => {
84
+ vi.stubGlobal('localStorage', {
85
+ get length() { throw new Error('blocked'); },
86
+ key: () => null,
87
+ getItem: () => null,
88
+ setItem: () => {},
89
+ removeItem: () => {},
90
+ clear: () => {},
91
+ });
92
+ expect(() => new StateService()).not.toThrow();
93
+ });
94
+ });
95
+
96
+ describe('get / set', () => {
97
+ it('returns null for missing key', () => {
98
+ const svc = new StateService();
99
+ expect(svc.get('config', 'missing')).toBeNull();
100
+ });
101
+
102
+ it('stores and retrieves a value', () => {
103
+ const svc = new StateService();
104
+ svc.set('config', 'theme', 'dark');
105
+ expect(svc.get('config', 'theme')).toBe('dark');
106
+ });
107
+
108
+ it('stores complex objects', () => {
109
+ const svc = new StateService();
110
+ const data = { columns: ['a'], rows: [{ a: 1 }] };
111
+ svc.set('queryCache', 'q1', data);
112
+ expect(svc.get('queryCache', 'q1')).toEqual(data);
113
+ });
114
+
115
+ it('overwrites existing value', () => {
116
+ const svc = new StateService();
117
+ svc.set('config', 'theme', 'dark');
118
+ svc.set('config', 'theme', 'light');
119
+ expect(svc.get('config', 'theme')).toBe('light');
120
+ });
121
+ });
122
+
123
+ describe('has', () => {
124
+ it('returns false for missing key', () => {
125
+ const svc = new StateService();
126
+ expect(svc.has('config', 'missing')).toBe(false);
127
+ });
128
+
129
+ it('returns true for existing key', () => {
130
+ const svc = new StateService();
131
+ svc.set('config', 'theme', 'dark');
132
+ expect(svc.has('config', 'theme')).toBe(true);
133
+ });
134
+ });
135
+
136
+ describe('TTL expiration', () => {
137
+ it('evicts expired entries on read (queryCache)', () => {
138
+ vi.useFakeTimers();
139
+ try {
140
+ const svc = new StateService();
141
+ svc.set('queryCache', 'q1', { data: 1 });
142
+ expect(svc.get('queryCache', 'q1')).toEqual({ data: 1 });
143
+ // Advance past 15 min TTL
144
+ vi.advanceTimersByTime(16 * 60 * 1000);
145
+ expect(svc.get('queryCache', 'q1')).toBeNull();
146
+ } finally {
147
+ vi.useRealTimers();
148
+ }
149
+ });
150
+
151
+ it('evicts expired entries on read (queryCache)', () => {
152
+ vi.useFakeTimers();
153
+ try {
154
+ const svc = new StateService();
155
+ svc.set('queryCache', 'q1', { rows: [1, 2, 3] });
156
+ expect(svc.get('queryCache', 'q1')).toEqual({ rows: [1, 2, 3] });
157
+ // Advance past 15 min TTL
158
+ vi.advanceTimersByTime(16 * 60 * 1000);
159
+ expect(svc.get('queryCache', 'q1')).toBeNull();
160
+ } finally {
161
+ vi.useRealTimers();
162
+ }
163
+ });
164
+
165
+ it('respects per-entry TTL override', () => {
166
+ vi.useFakeTimers();
167
+ try {
168
+ const svc = new StateService();
169
+ svc.set('queryCache', 'short', 'data', { ttl: 1000 });
170
+ expect(svc.get('queryCache', 'short')).toBe('data');
171
+ vi.advanceTimersByTime(2000);
172
+ expect(svc.get('queryCache', 'short')).toBeNull();
173
+ } finally {
174
+ vi.useRealTimers();
175
+ }
176
+ });
177
+
178
+ it('config entries never expire by default', () => {
179
+ vi.useFakeTimers();
180
+ try {
181
+ const svc = new StateService();
182
+ svc.set('config', 'theme', 'dark');
183
+ vi.advanceTimersByTime(365 * 24 * 60 * 60 * 1000); // 1 year
184
+ expect(svc.get('config', 'theme')).toBe('dark');
185
+ } finally {
186
+ vi.useRealTimers();
187
+ }
188
+ });
189
+ });
190
+
191
+ describe('max entries eviction', () => {
192
+ it('evicts oldest entries when explorerCache exceeds 200', () => {
193
+ const svc = new StateService();
194
+ // Fill with 200 entries
195
+ for (let i = 0; i < 200; i++) {
196
+ svc.set('explorerCache', `q${i}`, { n: i });
197
+ }
198
+ expect(svc.entryCount('explorerCache')).toBe(200);
199
+
200
+ // Adding one more should evict the oldest
201
+ svc.set('explorerCache', 'q200', { n: 200 });
202
+ expect(svc.entryCount('explorerCache')).toBe(200);
203
+ expect(svc.get('explorerCache', 'q200')).toEqual({ n: 200 });
204
+ // q0 was the oldest and should be evicted
205
+ expect(svc.get('explorerCache', 'q0')).toBeNull();
206
+ });
207
+ });
208
+
209
+ describe('delete', () => {
210
+ it('removes an existing entry', () => {
211
+ const svc = new StateService();
212
+ svc.set('config', 'theme', 'dark');
213
+ svc.delete('config', 'theme');
214
+ expect(svc.get('config', 'theme')).toBeNull();
215
+ });
216
+
217
+ it('removes localStorage bootstrap key', () => {
218
+ const svc = new StateService();
219
+ svc.set('config', 'theme', 'dark');
220
+ expect(mockLS.getItem('traverse-state:config:theme')).not.toBeNull();
221
+ svc.delete('config', 'theme');
222
+ expect(mockLS.getItem('traverse-state:config:theme')).toBeNull();
223
+ });
224
+
225
+ it('does nothing for missing key', () => {
226
+ const svc = new StateService();
227
+ expect(() => svc.delete('config', 'nonexistent')).not.toThrow();
228
+ });
229
+ });
230
+
231
+ describe('clear', () => {
232
+ it('removes all entries in a store', () => {
233
+ const svc = new StateService();
234
+ svc.set('queryCache', 'q1', 'a');
235
+ svc.set('queryCache', 'q2', 'b');
236
+ svc.set('config', 'theme', 'dark'); // other store untouched
237
+ svc.clear('queryCache');
238
+ expect(svc.keys('queryCache')).toEqual([]);
239
+ expect(svc.get('config', 'theme')).toBe('dark');
240
+ });
241
+
242
+ it('clears localStorage bootstrap keys', () => {
243
+ const svc = new StateService();
244
+ svc.set('config', 'theme', 'dark');
245
+ svc.set('config', 'model', 'opus');
246
+ mockLS.setItem('unrelated', 'keep');
247
+ svc.clear('config');
248
+ expect(mockLS.getItem('traverse-state:config:theme')).toBeNull();
249
+ expect(mockLS.getItem('traverse-state:config:model')).toBeNull();
250
+ expect(mockLS.getItem('unrelated')).toBe('keep');
251
+ });
252
+
253
+ it('does nothing on empty store', () => {
254
+ const svc = new StateService();
255
+ expect(() => svc.clear('queryCache')).not.toThrow();
256
+ });
257
+ });
258
+
259
+ describe('keys / entries / entryCount', () => {
260
+ it('returns keys for a store', () => {
261
+ const svc = new StateService();
262
+ svc.set('config', 'a', 1);
263
+ svc.set('config', 'b', 2);
264
+ expect(svc.keys('config').sort()).toEqual(['a', 'b']);
265
+ });
266
+
267
+ it('excludes expired entries from keys()', () => {
268
+ vi.useFakeTimers();
269
+ try {
270
+ const svc = new StateService();
271
+ svc.set('queryCache', 'fresh', 'ok');
272
+ svc.set('queryCache', 'stale', 'old', { ttl: 1 });
273
+ vi.advanceTimersByTime(100);
274
+ expect(svc.keys('queryCache')).toEqual(['fresh']);
275
+ } finally {
276
+ vi.useRealTimers();
277
+ }
278
+ });
279
+
280
+ it('entries() returns sorted by timestamp descending', () => {
281
+ vi.useFakeTimers();
282
+ try {
283
+ const svc = new StateService();
284
+ svc.set('config', 'first', 'a');
285
+ vi.advanceTimersByTime(100);
286
+ svc.set('config', 'second', 'b');
287
+ const entries = svc.entries('config');
288
+ expect(entries[0].key).toBe('second'); // newest first
289
+ expect(entries[1].key).toBe('first');
290
+ } finally {
291
+ vi.useRealTimers();
292
+ }
293
+ });
294
+
295
+ it('entries() includes size estimates', () => {
296
+ const svc = new StateService();
297
+ svc.set('config', 'theme', 'dark');
298
+ const entries = svc.entries('config');
299
+ expect(entries[0].size).toBeGreaterThan(0);
300
+ });
301
+
302
+ it('entryCount() matches keys length', () => {
303
+ const svc = new StateService();
304
+ svc.set('config', 'a', 1);
305
+ svc.set('config', 'b', 2);
306
+ expect(svc.entryCount('config')).toBe(2);
307
+ });
308
+ });
309
+
310
+ describe('stats', () => {
311
+ it('returns aggregate statistics', () => {
312
+ const svc = new StateService();
313
+ svc.set('config', 'theme', 'dark');
314
+ svc.set('queryCache', 'q1', { data: [1, 2, 3] });
315
+ const s = svc.stats();
316
+ expect(s.totalEntries).toBe(2);
317
+ expect(s.totalSize).toBeGreaterThan(0);
318
+ expect(s.stores.config.entries).toBe(1);
319
+ expect(s.stores.queryCache.entries).toBe(1);
320
+ expect(s.stores.config.oldestTimestamp).not.toBeNull();
321
+ });
322
+
323
+ it('returns zero stats for empty service', () => {
324
+ const svc = new StateService();
325
+ const s = svc.stats();
326
+ expect(s.totalEntries).toBe(0);
327
+ expect(s.totalSize).toBe(0);
328
+ for (const name of STORE_NAMES) {
329
+ expect(s.stores[name].entries).toBe(0);
330
+ expect(s.stores[name].oldestTimestamp).toBeNull();
331
+ }
332
+ });
333
+
334
+ it('returns cached stats on second call without changes', () => {
335
+ const svc = new StateService();
336
+ svc.set('config', 'x', 'hello');
337
+ const s1 = svc.stats();
338
+ const s2 = svc.stats();
339
+ // Same reference because cache is hit
340
+ expect(s1).toBe(s2);
341
+ });
342
+
343
+ it('invalidates stats cache after set', () => {
344
+ const svc = new StateService();
345
+ const s1 = svc.stats();
346
+ svc.set('config', 'y', 'world');
347
+ const s2 = svc.stats();
348
+ expect(s2.totalEntries).toBe(1);
349
+ expect(s1).not.toBe(s2);
350
+ });
351
+
352
+ it('entries returns cached result on second call', () => {
353
+ const svc = new StateService();
354
+ svc.set('config', 'a', 'value');
355
+ const e1 = svc.entries('config');
356
+ const e2 = svc.entries('config');
357
+ expect(e1).toBe(e2);
358
+ });
359
+ });
360
+
361
+ describe('subscribe', () => {
362
+ it('notifies on set', () => {
363
+ const svc = new StateService();
364
+ const cb = vi.fn();
365
+ svc.subscribe('config', 'theme', cb);
366
+ svc.set('config', 'theme', 'dark');
367
+ expect(cb).toHaveBeenCalledTimes(1);
368
+ });
369
+
370
+ it('notifies on delete', () => {
371
+ const svc = new StateService();
372
+ svc.set('config', 'theme', 'dark');
373
+ const cb = vi.fn();
374
+ svc.subscribe('config', 'theme', cb);
375
+ svc.delete('config', 'theme');
376
+ expect(cb).toHaveBeenCalledTimes(1);
377
+ });
378
+
379
+ it('notifies on clear', () => {
380
+ const svc = new StateService();
381
+ svc.set('config', 'a', 1);
382
+ svc.set('config', 'b', 2);
383
+ const cbA = vi.fn();
384
+ const cbB = vi.fn();
385
+ svc.subscribe('config', 'a', cbA);
386
+ svc.subscribe('config', 'b', cbB);
387
+ svc.clear('config');
388
+ expect(cbA).toHaveBeenCalledTimes(1);
389
+ expect(cbB).toHaveBeenCalledTimes(1);
390
+ });
391
+
392
+ it('does not notify other stores', () => {
393
+ const svc = new StateService();
394
+ const cb = vi.fn();
395
+ svc.subscribe('config', 'theme', cb);
396
+ svc.set('queryCache', 'q1', 'data');
397
+ expect(cb).not.toHaveBeenCalled();
398
+ });
399
+
400
+ it('does not notify other keys', () => {
401
+ const svc = new StateService();
402
+ const cb = vi.fn();
403
+ svc.subscribe('config', 'theme', cb);
404
+ svc.set('config', 'model', 'opus');
405
+ expect(cb).not.toHaveBeenCalled();
406
+ });
407
+
408
+ it('unsubscribe stops notifications', () => {
409
+ const svc = new StateService();
410
+ const cb = vi.fn();
411
+ const unsub = svc.subscribe('config', 'theme', cb);
412
+ svc.set('config', 'theme', 'dark');
413
+ expect(cb).toHaveBeenCalledTimes(1);
414
+ unsub();
415
+ svc.set('config', 'theme', 'light');
416
+ expect(cb).toHaveBeenCalledTimes(1);
417
+ });
418
+
419
+ it('subscribeStore notifies on any key change', () => {
420
+ const svc = new StateService();
421
+ const cb = vi.fn();
422
+ svc.subscribeStore('config', cb);
423
+ svc.set('config', 'theme', 'dark');
424
+ svc.set('config', 'model', 'opus');
425
+ expect(cb).toHaveBeenCalledTimes(2);
426
+ });
427
+
428
+ it('subscribeStore unsubscribe works', () => {
429
+ const svc = new StateService();
430
+ const cb = vi.fn();
431
+ const unsub = svc.subscribeStore('config', cb);
432
+ svc.set('config', 'theme', 'dark');
433
+ expect(cb).toHaveBeenCalledTimes(1);
434
+ unsub();
435
+ svc.set('config', 'theme', 'light');
436
+ expect(cb).toHaveBeenCalledTimes(1);
437
+ });
438
+
439
+ it('subscribe cleanup removes empty listener maps', () => {
440
+ const svc = new StateService();
441
+ const cb = vi.fn();
442
+ const unsub = svc.subscribe('config', 'only-key', cb);
443
+ svc.set('config', 'only-key', 'test');
444
+ expect(cb).toHaveBeenCalledTimes(1);
445
+ unsub();
446
+ // After unsubscribe, the listener map for 'only-key' should be cleaned up
447
+ svc.set('config', 'only-key', 'test2');
448
+ expect(cb).toHaveBeenCalledTimes(1);
449
+ });
450
+
451
+ it('subscribeStore cleanup removes empty listener maps', () => {
452
+ const svc = new StateService();
453
+ const cb = vi.fn();
454
+ const unsub = svc.subscribeStore('queryCache', cb);
455
+ svc.set('queryCache', 'q1', 'test');
456
+ expect(cb).toHaveBeenCalledTimes(1);
457
+ unsub();
458
+ svc.set('queryCache', 'q1', 'test2');
459
+ expect(cb).toHaveBeenCalledTimes(1);
460
+ });
461
+
462
+ it('clear notifies listeners for all keys', () => {
463
+ const svc = new StateService();
464
+ const cb = vi.fn();
465
+ svc.subscribeStore('config', cb);
466
+ svc.set('config', 'a', '1');
467
+ svc.set('config', 'b', '2');
468
+ cb.mockClear();
469
+ svc.clear('config');
470
+ // Should notify for each cleared key
471
+ expect(cb).toHaveBeenCalled();
472
+ });
473
+
474
+ it('delete notifies listeners', () => {
475
+ const svc = new StateService();
476
+ const cb = vi.fn();
477
+ svc.subscribe('config', 'del-key', cb);
478
+ svc.set('config', 'del-key', 'value');
479
+ cb.mockClear();
480
+ svc.delete('config', 'del-key');
481
+ expect(cb).toHaveBeenCalledTimes(1);
482
+ });
483
+ });
484
+
485
+ describe('sync bootstrap (config store)', () => {
486
+ it('writes to localStorage on set', () => {
487
+ const svc = new StateService();
488
+ svc.set('config', 'theme', 'dark');
489
+ const raw = mockLS.getItem('traverse-state:config:theme');
490
+ expect(raw).not.toBeNull();
491
+ const parsed = JSON.parse(raw!);
492
+ expect(parsed.value).toBe('dark');
493
+ });
494
+
495
+ it('does not write queryCache to localStorage', () => {
496
+ const svc = new StateService();
497
+ svc.set('queryCache', 'q1', 'data');
498
+ const raw = mockLS.getItem('traverse-state:queryCache:q1');
499
+ expect(raw).toBeNull();
500
+ });
501
+ });
502
+
503
+ describe('exportState / importState', () => {
504
+ it('round-trips state through export/import', () => {
505
+ const svc = new StateService();
506
+ svc.set('config', 'theme', 'dark');
507
+ svc.set('queryCache', 'q1', { rows: [1] });
508
+ const json = svc.exportState();
509
+
510
+ const svc2 = new StateService();
511
+ svc2.importState(json);
512
+ expect(svc2.get('config', 'theme')).toBe('dark');
513
+ expect(svc2.get('queryCache', 'q1')).toEqual({ rows: [1] });
514
+ });
515
+
516
+ it('export produces valid JSON', () => {
517
+ const svc = new StateService();
518
+ svc.set('config', 'theme', 'dark');
519
+ const json = svc.exportState();
520
+ expect(() => JSON.parse(json)).not.toThrow();
521
+ });
522
+
523
+ it('import ignores unknown store names', () => {
524
+ const svc = new StateService();
525
+ expect(() => svc.importState('{"unknownStore":{"k":{"value":1,"timestamp":0}}}')).not.toThrow();
526
+ });
527
+
528
+ it('importState throws on invalid JSON', () => {
529
+ const svc = new StateService();
530
+ expect(() => svc.importState('not-json')).toThrow('invalid JSON');
531
+ });
532
+
533
+ it('importState throws on non-object JSON', () => {
534
+ const svc = new StateService();
535
+ expect(() => svc.importState('"just a string"')).toThrow('expected a JSON object');
536
+ expect(() => svc.importState('[1,2,3]')).toThrow('expected a JSON object');
537
+ expect(() => svc.importState('null')).toThrow('expected a JSON object');
538
+ });
539
+
540
+ it('importState skips entries without value field', () => {
541
+ const svc = new StateService();
542
+ svc.importState('{"config":{"k":{"noValue":true}}}');
543
+ expect(svc.get('config', 'k')).toBeNull();
544
+ });
545
+
546
+ it('importState skips non-object entries', () => {
547
+ const svc = new StateService();
548
+ svc.importState('{"config":{"k":"not-an-object"}}');
549
+ expect(svc.get('config', 'k')).toBeNull();
550
+ });
551
+
552
+ it('importState skips non-object store values', () => {
553
+ const svc = new StateService();
554
+ svc.importState('{"config":"not-an-object"}');
555
+ expect(svc.entryCount('config')).toBe(0);
556
+ });
557
+
558
+ it('export skips empty stores', () => {
559
+ const svc = new StateService();
560
+ const json = svc.exportState();
561
+ const parsed = JSON.parse(json);
562
+ expect(Object.keys(parsed)).toHaveLength(0);
563
+ });
564
+ });
565
+
566
+ describe('dump', () => {
567
+ it('returns all values without metadata', () => {
568
+ const svc = new StateService();
569
+ svc.set('config', 'theme', 'dark');
570
+ svc.set('config', 'model', 'opus');
571
+ const d = svc.dump();
572
+ expect(d['config']).toEqual({ theme: 'dark', model: 'opus' });
573
+ });
574
+ });
575
+
576
+ describe('hydrate (without real IndexedDB)', () => {
577
+ it('sets hydrated flag', async () => {
578
+ const svc = new StateService();
579
+ expect(svc.hydrated).toBe(false);
580
+ await svc.hydrate();
581
+ expect(svc.hydrated).toBe(true);
582
+ });
583
+
584
+ it('calling hydrate twice returns the same promise', () => {
585
+ const svc = new StateService();
586
+ const p1 = svc.hydrate();
587
+ const p2 = svc.hydrate();
588
+ expect(p1).toBe(p2);
589
+ });
590
+
591
+ it('does not throw when IndexedDB is unavailable', async () => {
592
+ const svc = new StateService();
593
+ await expect(svc.hydrate()).resolves.toBeUndefined();
594
+ });
595
+ });
596
+
597
+ describe('hydrate with mocked IndexedDB', () => {
598
+ it('persists to IDB after hydration', async () => {
599
+ const idbEntry = { value: 'from-idb', timestamp: Date.now() };
600
+ const expiredEntry = { value: 'old', timestamp: 1, ttl: 1 };
601
+ let cursorIdx = 0;
602
+ const cursorData = [
603
+ { key: 'hydrated-key', value: idbEntry },
604
+ { key: 'expired-key', value: expiredEntry },
605
+ ];
606
+ const mockObjectStore = {
607
+ put: vi.fn(() => ({ onsuccess: null, onerror: null })),
608
+ delete: vi.fn(() => ({ onsuccess: null, onerror: null })),
609
+ clear: vi.fn(() => ({ onsuccess: null, onerror: null })),
610
+ openCursor: vi.fn(() => {
611
+ cursorIdx = 0;
612
+ const entry = cursorData[cursorIdx];
613
+ const req = {
614
+ result: entry ? { key: entry.key, value: entry.value, continue: () => {
615
+ cursorIdx++;
616
+ req.result = cursorData[cursorIdx] ? { key: cursorData[cursorIdx].key, value: cursorData[cursorIdx].value, continue: () => { cursorIdx++; req.result = null; setTimeout(() => req.onsuccess?.(), 0); } } : null;
617
+ setTimeout(() => req.onsuccess?.(), 0);
618
+ } } : null,
619
+ onsuccess: null as (() => void) | null,
620
+ onerror: null,
621
+ };
622
+ setTimeout(() => req.onsuccess?.(), 0);
623
+ return req;
624
+ }),
625
+ };
626
+ const mockDb = {
627
+ objectStoreNames: { contains: vi.fn(() => false) },
628
+ createObjectStore: vi.fn(() => ({ createIndex: vi.fn() })),
629
+ transaction: vi.fn(() => {
630
+ const tx = {
631
+ objectStore: vi.fn(() => mockObjectStore),
632
+ oncomplete: null as (() => void) | null,
633
+ onerror: null,
634
+ };
635
+ setTimeout(() => tx.oncomplete?.(), 10);
636
+ return tx;
637
+ }),
638
+ close: vi.fn(),
639
+ };
640
+ const mockOpenReq = {
641
+ result: mockDb,
642
+ onsuccess: null as (() => void) | null,
643
+ onerror: null as (() => void) | null,
644
+ onupgradeneeded: null as (() => void) | null,
645
+ error: null,
646
+ };
647
+ vi.stubGlobal('indexedDB', {
648
+ open: vi.fn(() => {
649
+ setTimeout(() => {
650
+ mockOpenReq.onupgradeneeded?.();
651
+ mockOpenReq.onsuccess?.();
652
+ }, 0);
653
+ return mockOpenReq;
654
+ }),
655
+ });
656
+
657
+ mockLS.setItem('traverse-state:config:theme', JSON.stringify({ value: 'dark', timestamp: Date.now() }));
658
+
659
+ const svc = new StateService();
660
+ await svc.hydrate();
661
+
662
+ svc.set('queryCache', 'q1', 'data');
663
+ svc.delete('queryCache', 'q1');
664
+ svc.set('queryCache', 'q2', 'data2');
665
+ svc.clear('queryCache');
666
+
667
+ vi.unstubAllGlobals();
668
+ });
669
+ });
670
+ });