@weasel-js/labkit 1.4.3 → 1.5.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 (229) hide show
  1. package/README.md +13 -2
  2. package/dist/_dts/{CanvasStackContext-Dde8_1my.d.ts → CanvasStackContext-CqkxkFJW.d.ts} +1 -1
  3. package/dist/_dts/ToggleBar.d-DbHoWKIA.d.ts +116 -0
  4. package/dist/_dts/{frac-B5mB8LsJ.d.ts → frac-8R6UmlvN.d.ts} +256 -33
  5. package/dist/_dts/index-B8uu2ba7.d.ts +237 -0
  6. package/dist/_dts/{index-DelFfeV0.d.ts → index-retnAut7.d.ts} +45 -12
  7. package/dist/_dts/{types-B9_zrHmb.d.ts → types-Ca2LCnPq.d.ts} +65 -2
  8. package/dist/_dts/usePanZoom-nS798rOF.d.ts +160 -0
  9. package/dist/_dts/useTrialState-jcx_TdU6.d.ts +212 -0
  10. package/dist/canvas/index.d.ts +17 -128
  11. package/dist/canvas/index.js +4 -2
  12. package/dist/chrome/index.d.ts +4 -92
  13. package/dist/chrome/index.js +9 -5
  14. package/dist/chunk-67SJLMC7.js +704 -0
  15. package/dist/chunk-67SJLMC7.js.map +1 -0
  16. package/dist/chunk-6ZDGOZQV.js +310 -0
  17. package/dist/chunk-6ZDGOZQV.js.map +1 -0
  18. package/dist/{chunk-QAGAHJKZ.js → chunk-EKIICY6X.js} +111 -25
  19. package/dist/chunk-EKIICY6X.js.map +1 -0
  20. package/dist/{chunk-CTRKTLYZ.js → chunk-H6ZAOWNE.js} +11 -11
  21. package/dist/chunk-H6ZAOWNE.js.map +1 -0
  22. package/dist/{chunk-2RQPGOQF.js → chunk-KJALCDWE.js} +9 -7
  23. package/dist/chunk-KJALCDWE.js.map +1 -0
  24. package/dist/{chunk-ISCOFAUO.js → chunk-MUKOW3TC.js} +3 -3
  25. package/dist/{chunk-ISCOFAUO.js.map → chunk-MUKOW3TC.js.map} +1 -1
  26. package/dist/chunk-NDRYLVOW.js +15 -0
  27. package/dist/chunk-NDRYLVOW.js.map +1 -0
  28. package/dist/{chunk-C42T6DJT.js → chunk-NS64DXMN.js} +226 -159
  29. package/dist/chunk-NS64DXMN.js.map +1 -0
  30. package/dist/{chunk-I6JCVE24.js → chunk-PGETSEDK.js} +135 -13
  31. package/dist/chunk-PGETSEDK.js.map +1 -0
  32. package/dist/{chunk-FQMJUVHJ.js → chunk-QLSV2N3G.js} +32 -37
  33. package/dist/chunk-QLSV2N3G.js.map +1 -0
  34. package/dist/chunk-RWNDDKOH.js +682 -0
  35. package/dist/chunk-RWNDDKOH.js.map +1 -0
  36. package/dist/chunk-S2SHZRD7.js +7681 -0
  37. package/dist/chunk-S2SHZRD7.js.map +1 -0
  38. package/dist/{chunk-ASWKLRKJ.js → chunk-TQBBYTAF.js} +19 -82
  39. package/dist/chunk-TQBBYTAF.js.map +1 -0
  40. package/dist/chunk-UU3NJO6N.js +72 -0
  41. package/dist/chunk-UU3NJO6N.js.map +1 -0
  42. package/dist/chunk-WIG6XHJ7.js +35 -0
  43. package/dist/chunk-WIG6XHJ7.js.map +1 -0
  44. package/dist/{chunk-TJ7QY3OC.js → chunk-ZPH5WTWF.js} +21 -15
  45. package/dist/chunk-ZPH5WTWF.js.map +1 -0
  46. package/dist/config/index.d.ts +232 -0
  47. package/dist/config/index.js +6 -0
  48. package/dist/config/index.js.map +1 -0
  49. package/dist/controls/index.d.ts +2 -3
  50. package/dist/controls/index.js +3 -2
  51. package/dist/dragdrop/index.d.ts +2 -4
  52. package/dist/index.d.ts +123 -348
  53. package/dist/index.js +794 -837
  54. package/dist/index.js.map +1 -1
  55. package/dist/layers/index.d.ts +3 -5
  56. package/dist/layers/index.js +2 -2
  57. package/dist/loupe/index.d.ts +6 -8
  58. package/dist/loupe/index.js +2 -2
  59. package/dist/passthrough/weasel-ui.d.ts +169 -117
  60. package/dist/passthrough/weasel-ui.js +1 -1
  61. package/dist/primitives/index.d.ts +53 -6
  62. package/dist/primitives/index.js +6 -4
  63. package/dist/state/index.d.ts +12 -7
  64. package/dist/state/index.js +16 -13
  65. package/dist/state/index.js.map +1 -1
  66. package/dist/styles.css +163 -62
  67. package/dist/surface/index.d.ts +44 -7
  68. package/dist/surface/index.js +2 -1
  69. package/dist/ui/layers/index.js +1 -1
  70. package/dist/undo/index.d.ts +2 -4
  71. package/package.json +15 -8
  72. package/src/annotations/AnnotationOverlay.tsx +53 -5
  73. package/src/annotations/Annotations.overlay.test.tsx +85 -6
  74. package/src/annotations/drawOne.test.ts +1 -1
  75. package/src/annotations/drawOne.ts +2 -2
  76. package/src/annotations/frac.test.ts +4 -4
  77. package/src/annotations/frac.ts +3 -2
  78. package/src/annotations/index.ts +1 -1
  79. package/src/annotations/paint.test.ts +2 -2
  80. package/src/annotations/paint.ts +1 -1
  81. package/src/annotations/preload.ts +6 -0
  82. package/src/annotations/store.test.ts +18 -0
  83. package/src/annotations/store.ts +7 -6
  84. package/src/annotations/svgNodes.test.ts +2 -2
  85. package/src/annotations/svgNodes.ts +1 -2
  86. package/src/annotations/toolMap.ts +3 -3
  87. package/src/annotations/types.ts +6 -3
  88. package/src/canvas/CameraWheelContext.ts +12 -0
  89. package/src/canvas/CanvasStack.test.tsx +25 -0
  90. package/src/canvas/CanvasStack.tsx +31 -4
  91. package/src/canvas/Stage.less +18 -0
  92. package/src/canvas/Stage.test.tsx +186 -0
  93. package/src/canvas/Stage.tsx +134 -0
  94. package/src/canvas/camera.test.ts +17 -2
  95. package/src/canvas/camera.ts +9 -9
  96. package/src/canvas/index.ts +4 -0
  97. package/src/canvas/usePanZoom.ts +10 -5
  98. package/src/chrome/ChromeRegions.stories.tsx +0 -3
  99. package/src/chrome/LabChrome.tsx +114 -0
  100. package/src/chrome/builtins.tsx +20 -31
  101. package/src/chrome/index.ts +15 -0
  102. package/src/chrome/labRegions.test.tsx +208 -0
  103. package/src/chrome/labTypes.ts +50 -0
  104. package/src/chrome/merge.ts +7 -9
  105. package/src/chrome/regions/PaletteRegion.test.tsx +6 -4
  106. package/src/chrome/regions/PaletteRegion.tsx +21 -9
  107. package/src/chrome/regions/SidebarRegion.tsx +25 -13
  108. package/src/chrome/regions/StatusRegion.tsx +15 -8
  109. package/src/chrome/regions/ToolbarRegion.tsx +30 -16
  110. package/src/chrome/types.ts +47 -20
  111. package/src/config/builder.test.ts +4 -0
  112. package/src/config/builder.ts +16 -10
  113. package/src/config/declarationEmit.fixture.ts +11 -0
  114. package/src/config/declarationEmit.test.ts +51 -0
  115. package/src/config/entry.test.ts +46 -0
  116. package/src/config/index.ts +13 -1
  117. package/src/config/nodeClasses.test.ts +18 -0
  118. package/src/config/types.ts +3 -1
  119. package/src/controls/ControlPanel.test.tsx +16 -0
  120. package/src/controls/ControlPanel.tsx +5 -2
  121. package/src/fake-indexeddb-auto.d.ts +5 -0
  122. package/src/index.test.ts +7 -0
  123. package/src/index.ts +39 -6
  124. package/src/instrument/serializers.test.ts +22 -0
  125. package/src/instrument/serializers.ts +11 -0
  126. package/src/instrument/types.ts +25 -1
  127. package/src/lab/Lab.less +4 -13
  128. package/src/lab/Lab.persist.test.tsx +147 -0
  129. package/src/lab/Lab.stories.tsx +0 -2
  130. package/src/lab/Lab.surface.test.tsx +66 -3
  131. package/src/lab/Lab.test.tsx +91 -17
  132. package/src/lab/Lab.tsx +337 -124
  133. package/src/lab/LabFit.stories.less +18 -0
  134. package/src/lab/LabFit.stories.tsx +219 -0
  135. package/src/lab/LabFullChrome.stories.tsx +0 -3
  136. package/src/lab/LabHeader.test.tsx +40 -9
  137. package/src/lab/LabHeader.tsx +7 -13
  138. package/src/lab/LabPalette.tsx +13 -26
  139. package/src/lab/LabShell.less +49 -12
  140. package/src/lab/LabShell.tsx +14 -2
  141. package/src/lab/LabSwitcher.less +92 -0
  142. package/src/lab/LabSwitcher.test.tsx +96 -0
  143. package/src/lab/LabSwitcher.tsx +112 -0
  144. package/src/lab/Workspace.surface.test.tsx +2 -1
  145. package/src/lab/fitCheck.test.ts +57 -0
  146. package/src/lab/fitCheck.ts +125 -0
  147. package/src/lab/index.ts +2 -0
  148. package/src/loupe/AGENTS.md +1 -1
  149. package/src/loupe/Loupe.less +1 -1
  150. package/src/loupe/canvasLens.ts +1 -1
  151. package/src/loupe/types.ts +1 -1
  152. package/src/loupe/useLoupe.test.tsx +1 -1
  153. package/src/loupe/useLoupe.ts +1 -1
  154. package/src/passthrough/weasel-ui.ts +9 -0
  155. package/src/primitives/FloatingPanel.stories.tsx +13 -1
  156. package/src/primitives/FloatingPanel.test.tsx +47 -16
  157. package/src/primitives/FloatingPanel.tsx +11 -25
  158. package/src/primitives/Split.less +14 -0
  159. package/src/primitives/Split.test.tsx +108 -0
  160. package/src/primitives/Split.tsx +159 -0
  161. package/src/primitives/ZoomControl.tsx +5 -2
  162. package/src/primitives/index.ts +2 -0
  163. package/src/state/Persistence.stories.tsx +75 -0
  164. package/src/state/Persistence.tsx +33 -0
  165. package/src/state/SingletonExperiment.test.tsx +47 -53
  166. package/src/state/SingletonExperiment.tsx +24 -13
  167. package/src/state/adapterContract.ts +116 -0
  168. package/src/state/adapters.test.ts +113 -61
  169. package/src/state/adapters.ts +328 -69
  170. package/src/state/document.test.ts +71 -96
  171. package/src/state/document.ts +66 -52
  172. package/src/state/helpers.test.ts +20 -0
  173. package/src/state/helpers.ts +16 -0
  174. package/src/state/index.ts +8 -0
  175. package/src/state/labRecords.test.ts +105 -0
  176. package/src/state/labRecords.ts +160 -0
  177. package/src/state/openLabStore.test.ts +658 -0
  178. package/src/state/openLabStore.ts +403 -0
  179. package/src/state/records.test.ts +234 -0
  180. package/src/state/records.ts +219 -0
  181. package/src/state/store.test.ts +104 -635
  182. package/src/state/store.ts +117 -158
  183. package/src/state/toolSlot.test.ts +1 -1
  184. package/src/state/types.ts +39 -15
  185. package/src/state/useOpenOnce.ts +68 -0
  186. package/src/state/usePersistedState.test.tsx +125 -0
  187. package/src/state/usePersistedState.ts +66 -0
  188. package/src/state/useTrialState.test.tsx +2 -3
  189. package/src/state/view.test.ts +49 -15
  190. package/src/state/view.ts +18 -1
  191. package/src/styles.less +3 -0
  192. package/src/surface/AGENTS.md +39 -7
  193. package/src/surface/SurfaceContext.ts +26 -3
  194. package/src/surface/index.ts +2 -0
  195. package/src/surface/useSurfaceTile.test.tsx +2 -1
  196. package/src/surface/useSurfaceTile.ts +6 -5
  197. package/src/surface/useTiledSurface.test.tsx +175 -0
  198. package/src/surface/useTiledSurface.ts +54 -5
  199. package/src/theme/Interstellar.stories.tsx +7 -7
  200. package/src/theme/base.less +4 -4
  201. package/src/theme/interstellar.test.ts +1 -1
  202. package/src/theme/interstellar.tokens.json +2 -2
  203. package/src/tools/labTool.ts +11 -0
  204. package/src/trial/Trial.annotations.persist.test.tsx +100 -58
  205. package/src/trial/Trial.annotations.test.tsx +47 -4
  206. package/src/trial/Trial.job.test.tsx +3 -3
  207. package/src/trial/Trial.less +1 -26
  208. package/src/trial/Trial.stories.tsx +1 -2
  209. package/src/trial/Trial.test.tsx +28 -4
  210. package/src/trial/Trial.trialId.test.tsx +23 -1
  211. package/src/trial/Trial.tsx +118 -38
  212. package/src/trial/TrialBody.tsx +17 -141
  213. package/src/trial/TrialChrome.tsx +7 -4
  214. package/src/trial/trialOps.ts +7 -4
  215. package/dist/_dts/types-BP2OCcpg.d.ts +0 -155
  216. package/dist/_dts/types-x92Kfeme.d.ts +0 -62
  217. package/dist/_dts/useTrialState-D6Vb3T-g.d.ts +0 -99
  218. package/dist/chunk-2RQPGOQF.js.map +0 -1
  219. package/dist/chunk-5TROQVQ2.js +0 -547
  220. package/dist/chunk-5TROQVQ2.js.map +0 -1
  221. package/dist/chunk-ASWKLRKJ.js.map +0 -1
  222. package/dist/chunk-C42T6DJT.js.map +0 -1
  223. package/dist/chunk-CTRKTLYZ.js.map +0 -1
  224. package/dist/chunk-FQMJUVHJ.js.map +0 -1
  225. package/dist/chunk-I6JCVE24.js.map +0 -1
  226. package/dist/chunk-MHAGC6VD.js +0 -7320
  227. package/dist/chunk-MHAGC6VD.js.map +0 -1
  228. package/dist/chunk-QAGAHJKZ.js.map +0 -1
  229. package/dist/chunk-TJ7QY3OC.js.map +0 -1
@@ -1,7 +1,10 @@
1
- import { type ReactNode, useRef } from 'react';
1
+ import type { ReactNode } from 'react';
2
+ import { defaultStorage } from './adapters';
2
3
  import { LabStoreProvider, TrialIdProvider } from './context';
3
- import { createLabStore, type LabStore } from './store';
4
+ import { openLabStore } from './openLabStore';
5
+ import { PersistenceContext } from './Persistence';
4
6
  import type { StorageAdapter } from './types';
7
+ import { useOpenOnce, useWarnIgnoredChange } from './useOpenOnce';
5
8
 
6
9
  const SINGLETON_INSTRUMENT = '__singleton__';
7
10
 
@@ -12,8 +15,11 @@ export interface SingletonExperimentProviderProps<TS, TC> {
12
15
  id: string;
13
16
  initialConfig: TC;
14
17
  initialState: TS;
15
- storage: StorageAdapter;
16
18
  storageKey: string;
19
+ /** Default: IndexedDB, or localStorage where IndexedDB will not open. */
20
+ storage?: StorageAdapter;
21
+ /** Rendered until the stored experiment has loaded. Default: nothing. */
22
+ fallback?: ReactNode;
17
23
  children: ReactNode;
18
24
  }
19
25
 
@@ -21,7 +27,8 @@ export interface SingletonExperimentProviderProps<TS, TC> {
21
27
  * One-trial `<Lab>` substitute for single-screen experiments. Mounts
22
28
  * a `LabStoreProvider` + `TrialIdProvider` with one synthetic
23
29
  * trial, so `useTrialState` works without going through the
24
- * full `<Lab instruments={...}>` runtime.
30
+ * full `<Lab instruments={...}>` runtime. `storageKey` and `storage` are read
31
+ * once, at mount.
25
32
  */
26
33
  export function SingletonExperimentProvider<TS, TC>({
27
34
  id,
@@ -29,13 +36,14 @@ export function SingletonExperimentProvider<TS, TC>({
29
36
  initialState,
30
37
  storage,
31
38
  storageKey,
39
+ fallback = null,
32
40
  children,
33
41
  }: SingletonExperimentProviderProps<TS, TC>) {
34
- const storeRef = useRef<LabStore | null>(null);
35
- if (storeRef.current === null) {
36
- const store = createLabStore({ storageKey, storage });
37
- if (!store.getState().trials.some((w) => w.id === id)) {
38
- store.getState().addTrial({
42
+ useWarnIgnoredChange('<SingletonExperimentProvider>', { storageKey, storage });
43
+ const opened = useOpenOnce(async () => {
44
+ const lab = await openLabStore({ storageKey, storage: storage ?? (await defaultStorage()) });
45
+ if (!lab.store.getState().trials.some((w) => w.id === id)) {
46
+ lab.store.getState().addTrial({
39
47
  id,
40
48
  instrumentName: SINGLETON_INSTRUMENT,
41
49
  config: initialConfig,
@@ -43,11 +51,14 @@ export function SingletonExperimentProvider<TS, TC>({
43
51
  view: { zoom: 1, pan: { x: 0, y: 0 } },
44
52
  });
45
53
  }
46
- storeRef.current = store;
47
- }
54
+ return lab;
55
+ });
56
+ if (!opened) return <>{fallback}</>;
48
57
  return (
49
- <LabStoreProvider store={storeRef.current}>
50
- <TrialIdProvider trialId={id}>{children}</TrialIdProvider>
58
+ <LabStoreProvider store={opened.store}>
59
+ <PersistenceContext.Provider value={opened.records}>
60
+ <TrialIdProvider trialId={id}>{children}</TrialIdProvider>
61
+ </PersistenceContext.Provider>
51
62
  </LabStoreProvider>
52
63
  );
53
64
  }
@@ -0,0 +1,116 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { StorageAdapter, StorageChange } from './types';
3
+
4
+ /** How the contract suite drives one adapter. */
5
+ export interface AdapterHarness {
6
+ adapter: StorageAdapter;
7
+ /** Whether a `Uint8Array` survives the round trip unchanged. */
8
+ binary: boolean;
9
+ /** Make a change the way another writer would, or omit when the adapter
10
+ * has no `subscribe`. */
11
+ foreign?: {
12
+ set(key: string, value: unknown): Promise<void> | void;
13
+ delete(key: string): Promise<void> | void;
14
+ };
15
+ }
16
+
17
+ async function until(check: () => boolean, ms = 1000): Promise<void> {
18
+ const end = Date.now() + ms;
19
+ while (!check()) {
20
+ if (Date.now() > end) throw new Error('timed out waiting for a change');
21
+ await new Promise((r) => setTimeout(r, 5));
22
+ }
23
+ }
24
+
25
+ const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 50));
26
+
27
+ /** Every shipped adapter answers to these. `setup` runs once per test. */
28
+ export function describeAdapterContract(name: string, setup: () => AdapterHarness): void {
29
+ describe(`${name} — the adapter contract`, () => {
30
+ it('reads back what it stored, as a copy', async () => {
31
+ const { adapter } = setup();
32
+ const value = { trial: 'a', nested: { n: 1, list: [1, 'two', null] } };
33
+ await adapter.set('lk:x:one', value);
34
+ value.nested.n = 99;
35
+ expect(await adapter.get('lk:x:one')).toEqual({
36
+ trial: 'a',
37
+ nested: { n: 1, list: [1, 'two', null] },
38
+ });
39
+ });
40
+
41
+ it('answers undefined for a key it never held', async () => {
42
+ const { adapter } = setup();
43
+ expect(await adapter.get('lk:x:absent')).toBeUndefined();
44
+ });
45
+
46
+ it('lists only the keys under a prefix', async () => {
47
+ const { adapter } = setup();
48
+ await adapter.set('lk:x:a', 1);
49
+ await adapter.set('lk:x:b', 2);
50
+ await adapter.set('lk:y:a', 3);
51
+ const listed = await adapter.list('lk:x:');
52
+ expect(new Map(listed)).toEqual(
53
+ new Map<string, unknown>([
54
+ ['lk:x:a', 1],
55
+ ['lk:x:b', 2],
56
+ ]),
57
+ );
58
+ });
59
+
60
+ it('deletes a key', async () => {
61
+ const { adapter } = setup();
62
+ await adapter.set('lk:x:gone', { a: 1 });
63
+ await adapter.delete('lk:x:gone');
64
+ expect(await adapter.get('lk:x:gone')).toBeUndefined();
65
+ expect(await adapter.list('lk:x:')).toEqual([]);
66
+ });
67
+
68
+ it('keeps binary values exactly when it says it can', async () => {
69
+ const { adapter, binary } = setup();
70
+ if (!binary) return;
71
+ await adapter.set('lk:x:bytes', new Uint8Array([1, 2, 255]));
72
+ const back = await adapter.get('lk:x:bytes');
73
+ // Not `toBeInstanceOf`: under jsdom, structuredClone hands back Node's
74
+ // Uint8Array, which is not the test realm's.
75
+ expect(Object.prototype.toString.call(back)).toBe('[object Uint8Array]');
76
+ expect([...(back as Uint8Array)]).toEqual([1, 2, 255]);
77
+ });
78
+
79
+ it("reports another writer's changes under its prefix, and nothing else", async () => {
80
+ const { adapter, foreign } = setup();
81
+ if (!foreign) {
82
+ expect(adapter.subscribe).toBeUndefined();
83
+ return;
84
+ }
85
+ if (!adapter.subscribe) throw new Error(`${name} has a foreign writer but no subscribe`);
86
+ const heard: StorageChange[] = [];
87
+ const off = adapter.subscribe('lk:x:', (changes) => heard.push(...changes));
88
+ try {
89
+ await adapter.set('lk:x:own', 'mine');
90
+ await foreign.set('lk:y:elsewhere', 'not this prefix');
91
+ await settle();
92
+ expect(heard).toEqual([]);
93
+
94
+ await foreign.set('lk:x:theirs', { from: 'peer' });
95
+ await until(() => heard.length > 0);
96
+ expect(heard).toEqual([['lk:x:theirs', { from: 'peer' }]]);
97
+
98
+ await foreign.delete('lk:x:theirs');
99
+ await until(() => heard.length > 1);
100
+ expect(heard[1]).toEqual(['lk:x:theirs', undefined]);
101
+ } finally {
102
+ off();
103
+ }
104
+ });
105
+
106
+ it('stops reporting once unsubscribed', async () => {
107
+ const { adapter, foreign } = setup();
108
+ if (!foreign || !adapter.subscribe) return;
109
+ const heard: StorageChange[] = [];
110
+ adapter.subscribe('lk:x:', (changes) => heard.push(...changes))();
111
+ await foreign.set('lk:x:late', 1);
112
+ await settle();
113
+ expect(heard).toEqual([]);
114
+ });
115
+ });
116
+ }
@@ -1,94 +1,146 @@
1
- import { beforeEach, describe, expect, it, vi } from 'vitest';
1
+ import 'fake-indexeddb/auto';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { describeAdapterContract } from './adapterContract';
2
4
  import {
5
+ createIndexedDbAdapter,
3
6
  createMemoryAdapter,
7
+ defaultStorage,
8
+ indexedDbAdapter,
4
9
  localStorageAdapter,
5
10
  noneAdapter,
11
+ resetDefaultStorage,
6
12
  sessionStorageAdapter,
7
13
  urlHashAdapter,
8
14
  } from './adapters';
15
+ import { decodeUrlHash, encodeUrlHash } from './helpers';
9
16
 
10
- describe('localStorageAdapter', () => {
11
- beforeEach(() => localStorage.clear());
17
+ describeAdapterContract('createMemoryAdapter', () => {
18
+ const backing = new Map<string, unknown>();
19
+ const peer = createMemoryAdapter(backing);
20
+ return { adapter: createMemoryAdapter(backing), binary: true, foreign: peer };
21
+ });
12
22
 
13
- it('writes and reads a value', () => {
14
- localStorageAdapter.write('k', 'v');
15
- expect(localStorageAdapter.read('k')).toBe('v');
16
- });
23
+ let database = 0;
24
+ describeAdapterContract('createIndexedDbAdapter', () => {
25
+ const name = `contract-${database++}`;
26
+ return {
27
+ adapter: createIndexedDbAdapter({ database: name }),
28
+ binary: true,
29
+ foreign: createIndexedDbAdapter({ database: name }),
30
+ };
31
+ });
17
32
 
18
- it('returns null for missing key', () => {
19
- expect(localStorageAdapter.read('missing')).toBeNull();
20
- });
33
+ /** jsdom has one window, so no `storage` event ever arrives from another tab.
34
+ * This writes the key and dispatches the event another tab's write would —
35
+ * a stand-in for the browser, not a test of it. */
36
+ function foreignWebStorage(area: Storage) {
37
+ const fire = (key: string, newValue: string | null): void => {
38
+ window.dispatchEvent(new StorageEvent('storage', { key, newValue, storageArea: area }));
39
+ };
40
+ return {
41
+ set: (key: string, value: unknown) => {
42
+ const raw = JSON.stringify(value);
43
+ area.setItem(key, raw);
44
+ fire(key, raw);
45
+ },
46
+ delete: (key: string) => {
47
+ area.removeItem(key);
48
+ fire(key, null);
49
+ },
50
+ };
51
+ }
21
52
 
22
- it('deletes a key', () => {
23
- localStorageAdapter.write('k', 'v');
24
- localStorageAdapter.delete?.('k');
25
- expect(localStorageAdapter.read('k')).toBeNull();
26
- });
53
+ describeAdapterContract('localStorageAdapter', () => {
54
+ localStorage.clear();
55
+ return { adapter: localStorageAdapter, binary: false, foreign: foreignWebStorage(localStorage) };
56
+ });
27
57
 
28
- it('handles QuotaExceededError gracefully', () => {
29
- vi.spyOn(Storage.prototype, 'setItem').mockImplementationOnce(() => {
30
- throw new DOMException('QuotaExceeded', 'QuotaExceededError');
31
- });
32
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
33
- expect(() => localStorageAdapter.write('k', 'v')).not.toThrow();
34
- expect(warn).toHaveBeenCalled();
35
- warn.mockRestore();
36
- });
58
+ describeAdapterContract('sessionStorageAdapter', () => {
59
+ sessionStorage.clear();
60
+ return { adapter: sessionStorageAdapter, binary: false };
37
61
  });
38
62
 
39
- describe('sessionStorageAdapter', () => {
40
- beforeEach(() => sessionStorage.clear());
63
+ function foreignHash() {
64
+ const edit = (change: (map: Record<string, string>) => void): void => {
65
+ const raw = decodeUrlHash(window.location.hash.replace(/^#/, ''));
66
+ const map = raw ? (JSON.parse(raw) as Record<string, string>) : {};
67
+ change(map);
68
+ window.location.hash = encodeUrlHash(JSON.stringify(map));
69
+ };
70
+ return {
71
+ set: (key: string, value: unknown) =>
72
+ edit((map) => {
73
+ map[key] = JSON.stringify(value);
74
+ }),
75
+ delete: (key: string) =>
76
+ edit((map) => {
77
+ delete map[key];
78
+ }),
79
+ };
80
+ }
41
81
 
42
- it('writes and reads a value', () => {
43
- sessionStorageAdapter.write('k', 'v');
44
- expect(sessionStorageAdapter.read('k')).toBe('v');
45
- });
82
+ describeAdapterContract('urlHashAdapter', () => {
83
+ window.history.replaceState(null, '', '#');
84
+ return { adapter: urlHashAdapter, binary: false, foreign: foreignHash() };
46
85
  });
47
86
 
48
- describe('urlHashAdapter', () => {
49
- beforeEach(() => {
50
- window.location.hash = '';
51
- });
87
+ describe('localStorageAdapter', () => {
88
+ beforeEach(() => localStorage.clear());
52
89
 
53
- it('writes and reads back through the hash', () => {
54
- urlHashAdapter.write('any-key', 'hello world');
55
- expect(urlHashAdapter.read('any-key')).toBe('hello world');
90
+ it('reads a value stored before records existed, raw or JSON', async () => {
91
+ localStorage.setItem('lk:old:theme', 'dark');
92
+ localStorage.setItem('lk:old:doc', '{"version":3}');
93
+ expect(await localStorageAdapter.get('lk:old:theme')).toBe('dark');
94
+ expect(await localStorageAdapter.get('lk:old:doc')).toEqual({ version: 3 });
56
95
  });
57
96
 
58
- it('returns null when hash is empty', () => {
59
- expect(urlHashAdapter.read('any-key')).toBeNull();
97
+ it('rejects a write that does not land', async () => {
98
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementationOnce(() => {
99
+ throw new DOMException('QuotaExceeded', 'QuotaExceededError');
100
+ });
101
+ await expect(localStorageAdapter.set('k', 'v')).rejects.toThrow('QuotaExceeded');
60
102
  });
61
103
 
62
- it('uses replaceState (not pushState)', () => {
63
- const spy = vi.spyOn(window.history, 'replaceState');
64
- urlHashAdapter.write('k', 'v');
65
- expect(spy).toHaveBeenCalled();
66
- spy.mockRestore();
104
+ it('warns once per key when JSON would change the value, and stores what JSON keeps', async () => {
105
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
106
+ await localStorageAdapter.set('lk:w:a', { at: new Set([1]) });
107
+ await localStorageAdapter.set('lk:w:a', { at: new Set([2]) });
108
+ await localStorageAdapter.set('lk:w:b', { fine: [1, 'x', null], skipped: undefined });
109
+ expect(warn).toHaveBeenCalledTimes(1);
110
+ expect(await localStorageAdapter.get('lk:w:a')).toEqual({ at: {} });
111
+ warn.mockRestore();
67
112
  });
68
113
  });
69
114
 
70
- describe('createMemoryAdapter', () => {
71
- it('two instances are isolated', () => {
72
- const a = createMemoryAdapter();
73
- const b = createMemoryAdapter();
74
- a.write('k', 'from-a');
75
- expect(b.read('k')).toBeNull();
115
+ describe('noneAdapter', () => {
116
+ it('stores nothing', async () => {
117
+ await noneAdapter.set('k', 'v');
118
+ expect(await noneAdapter.get('k')).toBeUndefined();
119
+ expect(await noneAdapter.list('')).toEqual([]);
76
120
  });
121
+ });
77
122
 
78
- it('delete removes the key', () => {
79
- const m = createMemoryAdapter();
80
- m.write('k', 'v');
81
- m.delete?.('k');
82
- expect(m.read('k')).toBeNull();
123
+ describe('defaultStorage', () => {
124
+ afterEach(() => {
125
+ resetDefaultStorage();
126
+ vi.unstubAllGlobals();
83
127
  });
84
- });
85
128
 
86
- describe('noneAdapter', () => {
87
- it('read always returns null', () => {
88
- expect(noneAdapter.read('anything')).toBeNull();
129
+ it('is IndexedDB where it opens', async () => {
130
+ expect(await defaultStorage()).toBe(indexedDbAdapter);
89
131
  });
90
132
 
91
- it('write is a no-op', () => {
92
- expect(() => noneAdapter.write('k', 'v')).not.toThrow();
133
+ it('falls back to localStorage, with a warning, where it will not', async () => {
134
+ vi.stubGlobal('indexedDB', undefined);
135
+ // The shared adapter may already hold an open database from the case above.
136
+ vi.resetModules();
137
+ const fresh = await import('./adapters');
138
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
139
+ expect(await fresh.defaultStorage()).toBe(fresh.localStorageAdapter);
140
+ expect(warn).toHaveBeenCalledWith(
141
+ expect.stringContaining('IndexedDB would not open'),
142
+ expect.anything(),
143
+ );
144
+ warn.mockRestore();
93
145
  });
94
146
  });