@buoy-gg/zustand 7.0.35 → 7.0.38

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 (64) hide show
  1. package/README.md +27 -5
  2. package/lib/commonjs/index.js +1 -105
  3. package/lib/commonjs/preset.js +1 -102
  4. package/lib/commonjs/zustand/components/ZustandActionButton.js +1 -118
  5. package/lib/commonjs/zustand/components/ZustandDetailViewToggle.js +1 -48
  6. package/lib/commonjs/zustand/components/ZustandEventFilterView.js +1 -43
  7. package/lib/commonjs/zustand/components/ZustandIcon.js +1 -18
  8. package/lib/commonjs/zustand/components/ZustandModal.js +1 -772
  9. package/lib/commonjs/zustand/components/ZustandStateChangeItem.js +1 -117
  10. package/lib/commonjs/zustand/components/ZustandStateDetailContent.js +1 -372
  11. package/lib/commonjs/zustand/components/ZustandStateInfoView.js +1 -488
  12. package/lib/commonjs/zustand/components/ZustandStoreBrowser.js +1 -204
  13. package/lib/commonjs/zustand/components/ZustandStoreDetailContent.js +1 -471
  14. package/lib/commonjs/zustand/components/ZustandStoreEditorScreen.js +1 -393
  15. package/lib/commonjs/zustand/hooks/useZustandStateChanges.js +1 -72
  16. package/lib/commonjs/zustand/sync/zustandSyncAdapter.js +1 -219
  17. package/lib/commonjs/zustand/utils/buoyZustandMiddleware.js +1 -284
  18. package/lib/commonjs/zustand/utils/editableState.js +1 -139
  19. package/lib/commonjs/zustand/utils/snapshotProvider.js +1 -209
  20. package/lib/commonjs/zustand/utils/testIDs.js +1 -82
  21. package/lib/commonjs/zustand/utils/zustandStateStore.js +1 -375
  22. package/lib/module/index.js +1 -90
  23. package/lib/module/preset.js +1 -98
  24. package/lib/module/zustand/components/ZustandActionButton.js +1 -114
  25. package/lib/module/zustand/components/ZustandDetailViewToggle.js +1 -43
  26. package/lib/module/zustand/components/ZustandEventFilterView.js +1 -39
  27. package/lib/module/zustand/components/ZustandIcon.js +1 -11
  28. package/lib/module/zustand/components/ZustandModal.js +1 -767
  29. package/lib/module/zustand/components/ZustandStateChangeItem.js +1 -113
  30. package/lib/module/zustand/components/ZustandStateDetailContent.js +1 -368
  31. package/lib/module/zustand/components/ZustandStateInfoView.js +1 -483
  32. package/lib/module/zustand/components/ZustandStoreBrowser.js +1 -200
  33. package/lib/module/zustand/components/ZustandStoreDetailContent.js +1 -469
  34. package/lib/module/zustand/components/ZustandStoreEditorScreen.js +1 -389
  35. package/lib/module/zustand/hooks/useZustandStateChanges.js +1 -68
  36. package/lib/module/zustand/sync/zustandSyncAdapter.js +1 -216
  37. package/lib/module/zustand/utils/buoyZustandMiddleware.js +1 -278
  38. package/lib/module/zustand/utils/editableState.js +1 -131
  39. package/lib/module/zustand/utils/snapshotProvider.js +1 -209
  40. package/lib/module/zustand/utils/testIDs.js +1 -74
  41. package/lib/module/zustand/utils/zustandStateStore.js +1 -371
  42. package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts +33 -0
  43. package/package.json +4 -4
  44. package/lib/typescript/index.d.ts.map +0 -1
  45. package/lib/typescript/preset.d.ts.map +0 -1
  46. package/lib/typescript/zustand/components/ZustandActionButton.d.ts.map +0 -1
  47. package/lib/typescript/zustand/components/ZustandDetailViewToggle.d.ts.map +0 -1
  48. package/lib/typescript/zustand/components/ZustandEventFilterView.d.ts.map +0 -1
  49. package/lib/typescript/zustand/components/ZustandIcon.d.ts.map +0 -1
  50. package/lib/typescript/zustand/components/ZustandModal.d.ts.map +0 -1
  51. package/lib/typescript/zustand/components/ZustandStateChangeItem.d.ts.map +0 -1
  52. package/lib/typescript/zustand/components/ZustandStateDetailContent.d.ts.map +0 -1
  53. package/lib/typescript/zustand/components/ZustandStateInfoView.d.ts.map +0 -1
  54. package/lib/typescript/zustand/components/ZustandStoreBrowser.d.ts.map +0 -1
  55. package/lib/typescript/zustand/components/ZustandStoreDetailContent.d.ts.map +0 -1
  56. package/lib/typescript/zustand/components/ZustandStoreEditorScreen.d.ts.map +0 -1
  57. package/lib/typescript/zustand/hooks/useZustandStateChanges.d.ts.map +0 -1
  58. package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts.map +0 -1
  59. package/lib/typescript/zustand/types/index.d.ts.map +0 -1
  60. package/lib/typescript/zustand/utils/buoyZustandMiddleware.d.ts.map +0 -1
  61. package/lib/typescript/zustand/utils/editableState.d.ts.map +0 -1
  62. package/lib/typescript/zustand/utils/snapshotProvider.d.ts.map +0 -1
  63. package/lib/typescript/zustand/utils/testIDs.d.ts.map +0 -1
  64. package/lib/typescript/zustand/utils/zustandStateStore.d.ts.map +0 -1
@@ -1,216 +1 @@
1
- "use strict";
2
-
3
- import { zustandStateStore } from "../utils/zustandStateStore";
4
- import { WIRE_DETAIL_LIMIT_BYTES, createSyncAdapter, detailByIdAction, isJsonSerializable, isOverWireBudget, memoByIdentity, onDeviceMarker, readParams, toWire, truncatedNote } from "@buoy-gg/shared-ui";
5
-
6
- /**
7
- * Sentinel used in WIRE-FORM snapshots in place of raw prevState/nextState.
8
- * Same hazard as redux: up to 200 changes × 2 full trees on every snapshot
9
- * freeze/OOM-killed large apps. Dashboards fetch trees via `getChangeDetail`.
10
- */
11
- export const STATE_ON_DEVICE = onDeviceMarker("State", "State trees stay on the device — fetched on demand via getChangeDetail / getStoreState.");
12
-
13
- /** Wire-form sentinel for an oversized `partial` (replace can carry a whole tree). */
14
- export const PAYLOAD_ON_DEVICE = onDeviceMarker("Payload", "Partial stays on the device — fetched on demand via getChangeDetail.");
15
- /** Top-level keys of an object state, for the compact (no-values) view. */
16
- function topLevelKeys(state) {
17
- return state && typeof state === "object" && !Array.isArray(state) ? Object.keys(state) : undefined;
18
- }
19
-
20
- /**
21
- * Per-change wire cache. The store prepends and never mutates a recorded
22
- * change, so keying on identity is correct and self-invalidating — without it
23
- * every `partial` in the list is re-measured on all ~5 snapshots per second.
24
- */
25
- const toWireChange = memoByIdentity(change => ({
26
- ...change,
27
- prevState: STATE_ON_DEVICE,
28
- nextState: STATE_ON_DEVICE,
29
- partial: toWire(change.partial, PAYLOAD_ON_DEVICE)
30
- }));
31
- const toWireState = value => toWire(value, STATE_ON_DEVICE);
32
-
33
- /**
34
- * Sync adapter for the zustand tool, consumed by @buoy-gg/external-sync's
35
- * `useExternalSync`.
36
- *
37
- * State changes are captured by the middleware (watchStores/buoyDevTools),
38
- * independent of whether a dashboard is watching — subscribing here only
39
- * streams what the store already records. The snapshot carries both the
40
- * change timeline and the store registry (with each store's current state)
41
- * so the dashboard can render the store browser.
42
- *
43
- * v2: change-log prevState/nextState are replaced with on-device markers
44
- * (see STATE_ON_DEVICE). Dashboards fetch trees via `getChangeDetail`.
45
- * Oversized / unserializable `stores[].currentState` uses the same marker
46
- * and is fetched via `getStoreState`.
47
- *
48
- * The `setState` action powers remote time-travel/reset from the dashboard.
49
- */
50
- export const zustandSyncAdapter = createSyncAdapter({
51
- version: 2,
52
- getSnapshot: () => ({
53
- changes: zustandStateStore.getStateChanges().map(toWireChange),
54
- stores: zustandStateStore.getStoreSnapshots().map(store => ({
55
- ...store,
56
- currentState: toWireState(store.currentState)
57
- }))
58
- }),
59
- subscribe: [onChange => zustandStateStore.subscribe(onChange), onChange => zustandStateStore.subscribeToStores(onChange)],
60
- actions: {
61
- clearEvents: () => {
62
- zustandStateStore.clearStateChanges();
63
- },
64
- /**
65
- * On-demand detail: one change's real prevState/nextState/partial.
66
- * The per-snapshot stream stays tree-free; this is the explicit,
67
- * size-guarded channel for the detail pane.
68
- */
69
- getChangeDetail: detailByIdAction(id => zustandStateStore.getStateChangeById(id), (change, cap) => ({
70
- prevState: cap(change.prevState),
71
- nextState: cap(change.nextState),
72
- partial: cap(change.partial)
73
- })),
74
- /**
75
- * On-demand current state for one store. Wire-form snapshots replace
76
- * oversized / unserializable `currentState` with STATE_ON_DEVICE.
77
- */
78
- getStoreState: params => {
79
- const {
80
- storeName
81
- } = readParams(params);
82
- if (!storeName) return {
83
- found: false,
84
- reason: "missing storeName"
85
- };
86
- const store = zustandStateStore.getStore(storeName);
87
- if (!store) return {
88
- found: false,
89
- reason: "unknown storeName"
90
- };
91
- let currentState;
92
- try {
93
- currentState = store.api.getState();
94
- } catch {
95
- currentState = undefined;
96
- }
97
- if (!isOverWireBudget(currentState, WIRE_DETAIL_LIMIT_BYTES)) {
98
- return {
99
- found: true,
100
- storeName,
101
- currentState
102
- };
103
- }
104
- return {
105
- found: true,
106
- storeName,
107
- currentState: isJsonSerializable(currentState) ? truncatedNote(WIRE_DETAIL_LIMIT_BYTES) : STATE_ON_DEVICE
108
- };
109
- },
110
- /**
111
- * Compact current-state reader for a remote driver (MCP/LLM): the registered
112
- * stores with light metadata; each store's full `currentState` object stays
113
- * on the device unless `includeValues` is set (compact view returns just the
114
- * top-level `keys` so the shape is visible cheaply).
115
- */
116
- listStores: params => {
117
- const {
118
- includeValues = false,
119
- limit
120
- } = readParams(params);
121
- const all = zustandStateStore.getStoreSnapshots();
122
- const capped = typeof limit === "number" && limit > 0 ? all.slice(0, limit) : all;
123
- const stores = capped.map(s => ({
124
- name: s.name,
125
- changes: s.stateChangeCount,
126
- isPersisted: s.isPersisted,
127
- persistName: s.persistName,
128
- canRehydrate: s.canRehydrate,
129
- ...(includeValues ? {
130
- currentState: s.currentState
131
- } : {
132
- keys: topLevelKeys(s.currentState)
133
- })
134
- }));
135
- return {
136
- stores,
137
- total: all.length,
138
- returned: stores.length,
139
- includedValues: includeValues
140
- };
141
- },
142
- setState: params => {
143
- const {
144
- storeName,
145
- state,
146
- replace
147
- } = readParams(params);
148
- if (!storeName) return {
149
- ok: false,
150
- error: "Missing storeName."
151
- };
152
- const store = zustandStateStore.getStore(storeName);
153
- if (!store) return {
154
- ok: false,
155
- error: `No store named "${storeName}".`
156
- };
157
- store.api.setState(state, replace ?? true);
158
- return {
159
- ok: true
160
- };
161
- },
162
- /**
163
- * Re-read a persisted store's saved value and merge it into the live store.
164
- *
165
- * This is what makes editing a store's storage key mean anything. The app
166
- * reads that key once at startup and then holds the state in memory, so an
167
- * outside write — the Storage tool, a scenario, an agent — changes the disk
168
- * and nothing else, and the next time the store saves it writes its own
169
- * copy straight back over the edit.
170
- *
171
- * `persist.rehydrate()` is plain zustand, not a devtools hook, so unlike
172
- * reloading the app this also works in a release build. It merges the saved
173
- * value OVER current state (zustand's default merge is
174
- * `{...current, ...persisted}`), so the store's action functions survive,
175
- * and it does not write back to storage unless a version migration ran —
176
- * the edit stays exactly as it was typed.
177
- *
178
- * Two honest limits, both inherent to persist rather than to this action:
179
- * a key the store's `partialize` excludes is not in the saved value and so
180
- * cannot be applied, and because the merge is shallow, DELETING a top-level
181
- * key from the saved JSON does not remove it from the live store.
182
- */
183
- rehydrate: async params => {
184
- const {
185
- storeName
186
- } = readParams(params);
187
- if (!storeName) return {
188
- ok: false,
189
- error: "Missing storeName."
190
- };
191
- const store = zustandStateStore.getStore(storeName);
192
- if (!store) return {
193
- ok: false,
194
- error: `No store named "${storeName}".`
195
- };
196
- if (!store.isPersisted) {
197
- return {
198
- ok: false,
199
- error: `"${storeName}" is not a persisted store — it has no saved copy to re-read.`
200
- };
201
- }
202
- if (!store.rehydrate) {
203
- return {
204
- ok: false,
205
- error: `"${storeName}" is persisted but Buoy has no rehydrate handle for it. It was probably registered before the app's persist middleware attached.`
206
- };
207
- }
208
- await store.rehydrate();
209
- return {
210
- ok: true,
211
- storeName,
212
- persistName: store.persistName
213
- };
214
- }
215
- }
216
- });
1
+ "use strict";import{expandKeyedArrays,patchFromPath,readPath,refusalText,shapeSummary,suggestedPatch,typedEditViolations,unshapedLists}from"@buoy-gg/shared-ui";import{zustandStateStore}from"../utils/zustandStateStore";import{WIRE_DETAIL_LIMIT_BYTES,createSyncAdapter,detailByIdAction,isJsonSerializable,isOverWireBudget,memoByIdentity,onDeviceMarker,readParams,toWire,truncatedNote}from"@buoy-gg/shared-ui";export const STATE_ON_DEVICE=onDeviceMarker("State","State trees stay on the device — fetched on demand via getChangeDetail / getStoreState.");export const PAYLOAD_ON_DEVICE=onDeviceMarker("Payload","Partial stays on the device — fetched on demand via getChangeDetail.");const isPlainObject=e=>!!e&&"object"==typeof e&&!Array.isArray(e);function touchesList(e,t){let r=e;for(const e of t.split(".")){if(!r||"object"!=typeof r||Array.isArray(r))return!1;if(!(e in r))return!1;r=r[e]}return Array.isArray(r)?r.length>0:!!r&&"object"==typeof r}function topLevelKeys(e){return e&&"object"==typeof e&&!Array.isArray(e)?Object.keys(e):void 0}const toWireChange=memoByIdentity(e=>({...e,prevState:STATE_ON_DEVICE,nextState:STATE_ON_DEVICE,partial:toWire(e.partial,PAYLOAD_ON_DEVICE)})),toWireState=e=>toWire(e,STATE_ON_DEVICE);export const zustandSyncAdapter=createSyncAdapter({version:2,getSnapshot:()=>({changes:zustandStateStore.getStateChanges().map(toWireChange),stores:zustandStateStore.getStoreSnapshots().map(e=>({...e,currentState:toWireState(e.currentState)}))}),subscribe:[e=>zustandStateStore.subscribe(e),e=>zustandStateStore.subscribeToStores(e)],actions:{clearEvents:()=>{zustandStateStore.clearStateChanges()},getChangeDetail:detailByIdAction(e=>zustandStateStore.getStateChangeById(e),(e,t)=>({prevState:t(e.prevState),nextState:t(e.nextState),partial:t(e.partial)})),getStoreState:e=>{const{storeName:t,path:r}=readParams(e);if(!t)return{found:!1,reason:"missing storeName"};const a=zustandStateStore.getStore(t);if(!a)return{found:!1,reason:"unknown storeName"};let s;try{s=a.api.getState()}catch{s=void 0}if(r){const e=readPath(s,r);return e.ok?{found:!0,storeName:t,path:r,shape:shapeSummary(e.value),currentState:e.value}:{found:!1,reason:e.error}}const o=shapeSummary(s);return isOverWireBudget(s,WIRE_DETAIL_LIMIT_BYTES)?{found:!0,storeName:t,...o?{shape:o}:{},currentState:isJsonSerializable(s)?truncatedNote(WIRE_DETAIL_LIMIT_BYTES):STATE_ON_DEVICE}:{found:!0,storeName:t,...o?{shape:o}:{},currentState:s}},listStores:e=>{const{includeValues:t=!1,limit:r}=readParams(e),a=zustandStateStore.getStoreSnapshots(),s=("number"==typeof r&&r>0?a.slice(0,r):a).map(e=>({name:e.name,changes:e.stateChangeCount,isPersisted:e.isPersisted,persistName:e.persistName,canRehydrate:e.canRehydrate,...t?{currentState:e.currentState}:{keys:topLevelKeys(e.currentState)},...shapeSummary(e.currentState)?{shape:shapeSummary(e.currentState)}:{}}));return{stores:s,total:a.length,returned:s.length,includedValues:t}},setState:e=>{const{storeName:t,state:r,replace:a,force:s,path:o,value:n}=readParams(e);let i=r,d=[],u=[];if(!t)return{ok:!1,error:"Missing storeName."};const c=zustandStateStore.getStore(t);if(!c)return{ok:!1,error:`No store named "${t}".`};if(void 0===r&&void 0===o)return{ok:!1,error:"Refused: no change was described. Send `state` with the fields to merge, or `path` and `value` to set one value."};let h=!1;if(void 0!==o){if(void 0===n)return{ok:!1,error:`Refused: sent \`path\` without \`value\`. Say what to set "${o}" to; if you mean to clear it, send value:null and the field must already be nullable.`};let e;try{e=c.api.getState()}catch{e=void 0}const t=patchFromPath(e,o,n);if(!t.ok)return{ok:!1,error:`Refused: ${t.error}`};i=t.patch,h=!0}if(!s&&(!1===a||h)){let e;try{e=c.api.getState()}catch{e=void 0}if(void 0!==e){const t=expandKeyedArrays(e,i);if(t.error)return{ok:!1,error:`Refused: ${t.error}`};i=t.patch,d=t.notes}if(void 0!==e&&(u=unshapedLists(e).filter(e=>touchesList(i,e))),void 0!==e){const t=typedEditViolations(e,i,{noun:"store"});if(t.length>0)return{ok:!1,error:refusalText(t,"store",suggestedPatch(i,t)),...suggestedPatch(i,t)?{suggestedState:suggestedPatch(i,t)}:{},violations:t}}}return c.api.setState(i,!h&&(a??!0)),{ok:!0,...void 0!==o?{path:o}:{},...d.length?{keyed:d}:{},...u.length?{unchecked:u.map(e=>`\`${e}\` was empty, so nothing in the app knows what its items look like and the shape of what you added was NOT checked. If the app renders a field you left out, it will render undefined — read the store back and compare against how the screen uses it.`)}:{}}},rehydrate:async e=>{const{storeName:t}=readParams(e);if(!t)return{ok:!1,error:"Missing storeName."};const r=zustandStateStore.getStore(t);return r?r.isPersisted?r.rehydrate?(await r.rehydrate(),{ok:!0,storeName:t,persistName:r.persistName}):{ok:!1,error:`"${t}" is persisted but Buoy has no rehydrate handle for it. It was probably registered before the app's persist middleware attached.`}:{ok:!1,error:`"${t}" is not a persisted store — it has no saved copy to re-read.`}:{ok:!1,error:`No store named "${t}".`}}}});
@@ -1,278 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * Buoy Zustand DevTools — Store instrumentation
5
- *
6
- * Two approaches, from easiest to most detailed:
7
- *
8
- * 1. watchStores() — RECOMMENDED. One line, zero store modifications.
9
- * Uses store.subscribe() externally. Never touches setState.
10
- * Safe to add/remove — cannot break your stores even if our code has bugs.
11
- *
12
- * 2. buoyDevTools() — Opt-in middleware for advanced use.
13
- * Wraps setState to capture the partial argument and timing.
14
- * Requires modifying each store's create() call.
15
- */
16
-
17
- import { zustandStateStore } from "./zustandStateStore";
18
- /** Symbol to mark stores that have been watched/instrumented */
19
- const WATCHED_SYMBOL = Symbol.for("@@buoy-zustand/watched");
20
-
21
- /** The slice of zustand's persist API this module uses. */
22
-
23
- /**
24
- * Detect if a store is using the persist middleware by checking for persist API
25
- */
26
- function detectPersist(store) {
27
- const persist = store.persist;
28
- if (persist && typeof persist.getOptions === "function") {
29
- const options = persist.getOptions();
30
- return {
31
- isPersisted: true,
32
- persistName: options?.name,
33
- persistApi: persist
34
- };
35
- }
36
- return {
37
- isPersisted: false
38
- };
39
- }
40
-
41
- // =============================================================================
42
- // watchStores — Primary, non-intrusive approach
43
- // =============================================================================
44
-
45
- /** Minimal store shape — what Zustand's create() returns */
46
-
47
- /**
48
- * Watch multiple Zustand stores for state changes.
49
- *
50
- * This is the recommended, non-intrusive approach. It uses each store's
51
- * `.subscribe()` method to observe changes from the outside — it never
52
- * modifies `setState` or any store internals.
53
- *
54
- * **Safe by design:** Even if our listener code has a bug, it cannot break
55
- * your stores. All listener code is wrapped in try/catch.
56
- *
57
- * @example
58
- * ```tsx
59
- * // In your _layout.tsx or App.tsx — ONE line:
60
- * import { watchStores } from '@buoy-gg/zustand';
61
- * import { useCounterStore } from './stores/counter';
62
- * import { useAuthStore } from './stores/auth';
63
- * import { useCartStore } from './stores/cart';
64
- *
65
- * watchStores({
66
- * counterStore: useCounterStore,
67
- * authStore: useAuthStore,
68
- * cartStore: useCartStore,
69
- * });
70
- * ```
71
- *
72
- * @param stores - Object mapping store names to Zustand store hooks
73
- * @returns Cleanup function that removes all subscriptions
74
- */
75
- export function watchStores(stores) {
76
- const cleanups = [];
77
- for (const [name, store] of Object.entries(stores)) {
78
- // Skip if already watched
79
- const storeAny = store;
80
- if (storeAny[WATCHED_SYMBOL]) continue;
81
- storeAny[WATCHED_SYMBOL] = true;
82
- const {
83
- isPersisted,
84
- persistName,
85
- persistApi
86
- } = detectPersist(store);
87
-
88
- // Register the store for overview
89
- zustandStateStore.registerStore(name, {
90
- getState: store.getState,
91
- getInitialState: store.getInitialState,
92
- setState: store.setState,
93
- subscribe: store.subscribe
94
- }, {
95
- isPersisted,
96
- persistName,
97
- // Was detected and thrown away. Without it nothing can re-read the
98
- // saved copy after an outside edit — see ZustandStoreInfo.rehydrate.
99
- rehydrate: typeof persistApi?.rehydrate === "function" ? () => persistApi.rehydrate() : undefined
100
- });
101
-
102
- // The rehydration is a state change nobody's code asked for — the store
103
- // simply becomes what the disk said, seconds into the process. Drawn as an
104
- // ordinary setState it is the most surprising row in the list and the one
105
- // that looks most like a bug, so it gets its own category. Recognised
106
- // rather than announced: `hasHydrated()` is still false while the
107
- // rehydrating `set` is running, and this listener runs inside it.
108
- let sawHydration = false;
109
-
110
- // Subscribe to state changes — completely external, never touches setState
111
- const unsubscribe = store.subscribe((state, prevState) => {
112
- try {
113
- let category;
114
- if (!sawHydration && isPersisted) {
115
- let hydrating = false;
116
- try {
117
- hydrating = persistApi?.hasHydrated?.() === false;
118
- } catch {
119
- // An older persist API without hasHydrated — no worse than before.
120
- }
121
- if (hydrating) {
122
- sawHydration = true;
123
- category = "persist";
124
- }
125
- }
126
- zustandStateStore.addStateChange({
127
- storeName: name,
128
- partial: undefined,
129
- // Not available in subscribe-only mode
130
- replace: false,
131
- prevState,
132
- nextState: state,
133
- duration: undefined,
134
- // Not available in subscribe-only mode
135
- category,
136
- isPersisted
137
- });
138
- } catch {
139
- // Silently catch — our bug must never propagate into the store
140
- }
141
- });
142
- cleanups.push(() => {
143
- unsubscribe();
144
- delete store[WATCHED_SYMBOL];
145
- zustandStateStore.unregisterStore(name);
146
- });
147
- }
148
- return () => {
149
- cleanups.forEach(fn => fn());
150
- };
151
- }
152
-
153
- // =============================================================================
154
- // buoyDevTools — Opt-in middleware (advanced, more detail)
155
- // =============================================================================
156
-
157
- /** Auto-incrementing store name counter for unnamed stores */
158
- let unnamedCounter = 0;
159
-
160
- /**
161
- * Zustand middleware that instruments a store for Buoy DevTools.
162
- *
163
- * This is the advanced approach — it wraps setState to capture:
164
- * - The partial argument passed to setState
165
- * - Precise timing of each setState call
166
- *
167
- * Use this when you want maximum detail. For most cases, `watchStores()`
168
- * is simpler and safer.
169
- *
170
- * @example
171
- * ```tsx
172
- * import { create } from 'zustand';
173
- * import { buoyDevTools } from '@buoy-gg/zustand';
174
- *
175
- * const useCounterStore = create(
176
- * buoyDevTools(
177
- * (set) => ({
178
- * count: 0,
179
- * increment: () => set((s) => ({ count: s.count + 1 })),
180
- * }),
181
- * { name: 'counterStore' }
182
- * )
183
- * );
184
- * ```
185
- */
186
- /**
187
- * Zustand's own `set` shape (v5 types): with `replace: true` the argument must
188
- * be a FULL state, so a single `(partial, replace?: boolean)` signature is
189
- * incompatible in both directions — zustand's set is not assignable to it,
190
- * which made `create(buoyDevTools(...))` fail to typecheck for every strict-TS
191
- * user. Mirroring the overloads keeps buoyDevTools a drop-in for `create()`.
192
- */
193
-
194
- /**
195
- * The store api object zustand hands a middleware, described structurally so
196
- * this package never has to import zustand's own types (which differ between
197
- * v4 and v5). `Record<string, unknown>` was wrong here: `StoreApi<T>` has no
198
- * index signature, so `create(buoyDevTools(...))` failed to typecheck.
199
- */
200
-
201
- export function buoyDevTools(config, options) {
202
- return (set, get, api) => {
203
- const storeName = options?.name ?? `store-${++unnamedCounter}`;
204
- const enabled = options?.enabled !== false;
205
-
206
- // Forwarding a plain `replace?: boolean` through the overloads needs one
207
- // widening cast; runtime behavior is unchanged.
208
- const rawSet = set;
209
- const instrumentedSet = (partial, replace) => {
210
- if (!enabled) {
211
- return rawSet(partial, replace);
212
- }
213
- const startTime = performance.now();
214
- const prevState = get();
215
- rawSet(partial, replace);
216
- const nextState = get();
217
- const duration = performance.now() - startTime;
218
- const resolvedPartial = typeof partial === "function" ? "(updater fn)" : partial;
219
- zustandStateStore.addStateChange({
220
- storeName,
221
- partial: resolvedPartial,
222
- replace: replace ?? false,
223
- prevState,
224
- nextState,
225
- duration,
226
- // Read back off the registry rather than hardcoded false. Persistence
227
- // is a property of the STORE, and this middleware can be wrapped
228
- // around a persisted one — every change on such a store used to be
229
- // drawn as un-persisted, which is the opposite of what the badge is
230
- // for. Registration happens a tick after creation, so a set fired in
231
- // that first tick still reports false; the alternative is re-sniffing
232
- // `api.persist` on every set.
233
- isPersisted: zustandStateStore.getStore(storeName)?.isPersisted ?? false
234
- });
235
- };
236
- const result = config(instrumentedSet, get, api);
237
-
238
- // Register the store after creation
239
- setTimeout(() => {
240
- if (api[WATCHED_SYMBOL]) return;
241
- api[WATCHED_SYMBOL] = true;
242
- const {
243
- isPersisted,
244
- persistName
245
- } = detectPersist(api);
246
- zustandStateStore.registerStore(storeName, {
247
- getState: get,
248
- getInitialState: api.getInitialState,
249
- // The INSTRUMENTED set, not the raw one.
250
- //
251
- // This handle is what the tool's own JUMP and RESET STORE call, and
252
- // registering the raw `set` here made both of them invisible: the
253
- // store changed, the app re-rendered, and nothing appeared in the
254
- // log — so the newest row's "state after change" no longer described
255
- // the store, and the next diff compared against a state the device
256
- // had never been in. The watch path never had this problem, because
257
- // it observes the store from outside and cannot be gone around.
258
- setState: instrumentedSet,
259
- subscribe: api.subscribe
260
- }, {
261
- isPersisted,
262
- persistName
263
- });
264
- }, 0);
265
- return result;
266
- };
267
- }
268
-
269
- // =============================================================================
270
- // Utility
271
- // =============================================================================
272
-
273
- /**
274
- * Check if a store is being watched/instrumented
275
- */
276
- export function isStoreInstrumented(store) {
277
- return store[WATCHED_SYMBOL] === true;
278
- }
1
+ "use strict";import{zustandStateStore}from"./zustandStateStore";const WATCHED_SYMBOL=Symbol.for("@@buoy-zustand/watched");function detectPersist(t){const e=t.persist;if(e&&"function"==typeof e.getOptions){const t=e.getOptions();return{isPersisted:!0,persistName:t?.name,persistApi:e}}return{isPersisted:!1}}export function watchStores(t){const e=[];for(const[s,r]of Object.entries(t)){const t=r;if(t[WATCHED_SYMBOL])continue;t[WATCHED_SYMBOL]=!0;const{isPersisted:a,persistName:i,persistApi:n}=detectPersist(r);zustandStateStore.registerStore(s,{getState:r.getState,getInitialState:r.getInitialState,setState:r.setState,subscribe:r.subscribe},{isPersisted:a,persistName:i,rehydrate:"function"==typeof n?.rehydrate?()=>n.rehydrate():void 0});let o=!1;const S=r.subscribe((t,e)=>{try{let r;if(!o&&a){let t=!1;try{t=!1===n?.hasHydrated?.()}catch{}t&&(o=!0,r="persist")}zustandStateStore.addStateChange({storeName:s,partial:void 0,replace:!1,prevState:e,nextState:t,duration:void 0,category:r,isPersisted:a})}catch{}});e.push(()=>{S(),delete r[WATCHED_SYMBOL],zustandStateStore.unregisterStore(s)})}return()=>{e.forEach(t=>t())}}let unnamedCounter=0;export function buoyDevTools(t,e){return(s,r,a)=>{const i=e?.name??"store-"+ ++unnamedCounter,n=!1!==e?.enabled,o=s,S=(t,e)=>{if(!n)return o(t,e);const s=performance.now(),a=r();o(t,e);const S=r(),u=performance.now()-s,c="function"==typeof t?"(updater fn)":t;zustandStateStore.addStateChange({storeName:i,partial:c,replace:e??!1,prevState:a,nextState:S,duration:u,isPersisted:zustandStateStore.getStore(i)?.isPersisted??!1})},u=t(S,r,a);return setTimeout(()=>{if(a[WATCHED_SYMBOL])return;a[WATCHED_SYMBOL]=!0;const{isPersisted:t,persistName:e}=detectPersist(a);zustandStateStore.registerStore(i,{getState:r,getInitialState:a.getInitialState,setState:S,subscribe:a.subscribe},{isPersisted:t,persistName:e})},0),u}}export function isStoreInstrumented(t){return!0===t[WATCHED_SYMBOL]}
@@ -1,131 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * What of a zustand store's state can be EDITED, and how an edit is written.
5
- *
6
- * The two zustand facts every rule here follows from:
7
- *
8
- * 1. Stores conventionally keep their action functions IN state
9
- * (`increment: () => …`). Functions can't be typed into a tree editor and
10
- * don't survive serialization, so the editor works on a function-free view
11
- * of state.
12
- * 2. `setState` is either a TOP-LEVEL SHALLOW MERGE (`Object.assign({}, state,
13
- * partial)`) or a full replace that deletes every key not present — actions
14
- * included. So the editor writes merge-only, always: every edit, however
15
- * deep, is expressed as "replace the top-level key(s) that contain it"
16
- * ({@link computeMergePartial}), and the two edits a merge cannot express —
17
- * removing or renaming a top-level key — are refused rather than silently
18
- * not happening.
19
- *
20
- * `stripFunctions` lives here (the Time Machine snapshot provider imports it)
21
- * because capture and editing need the identical answer to "what is this
22
- * store's data".
23
- */
24
-
25
- /** Bounds every recursive walk over store state. */
26
- export const STRIP_MAX_DEPTH = 8;
27
- export function isPlainObjectLike(v) {
28
- return typeof v === "object" && v !== null && !Array.isArray(v);
29
- }
30
-
31
- /** Clone `value` without functions, recording their paths. */
32
- export function stripFunctions(value, path, fnPaths, seen, depth) {
33
- if (typeof value === "function") {
34
- fnPaths.push(path);
35
- return undefined;
36
- }
37
- if (typeof value !== "object" || value === null || depth >= STRIP_MAX_DEPTH) {
38
- return value;
39
- }
40
- if (seen.has(value)) return undefined; // cycle — drop the back-reference
41
- seen.add(value);
42
- if (Array.isArray(value)) {
43
- return value.map((item, i) => typeof item === "function" ? (fnPaths.push(`${path}[${i}]`), null) : stripFunctions(item, `${path}[${i}]`, fnPaths, seen, depth + 1));
44
- }
45
- if (!isPlainObjectLike(value)) return value; // Date/Map/Set/etc. — superjson handles
46
- const out = {};
47
- for (const [k, v] of Object.entries(value)) {
48
- if (typeof v === "function") {
49
- fnPaths.push(path ? `${path}.${k}` : k);
50
- continue;
51
- }
52
- out[k] = stripFunctions(v, path ? `${path}.${k}` : k, fnPaths, seen, depth + 1);
53
- }
54
- return out;
55
- }
56
- /**
57
- * The editor's view of one store's state, with the reasons it may refuse.
58
- *
59
- * - A remote mirror that hasn't hydrated yet holds a marker, not state — the
60
- * real value is one `getStoreState` round trip away, so "wait" rather than
61
- * "can't".
62
- * - Non-object state (`create(() => 5)`) has no top-level keys, so a merge
63
- * write cannot address any part of it. Editing it would require a replace,
64
- * which is the destructive path this editor exists to avoid.
65
- * - A function nested BELOW the top level (rare — the convention keeps actions
66
- * at the top) sits inside the very key an edit would rewrite, and a merge
67
- * write of that key would silently drop it. Refusing the whole store is
68
- * blunt but honest; per-key locks can come later if this ever bites.
69
- */
70
- export function editableStateOf(state) {
71
- if (isPlainObjectLike(state) && state.__buoyStateOnDevice === true) {
72
- return {
73
- data: null,
74
- fnPaths: [],
75
- blockedReason: "Store state hasn't synced from the device yet."
76
- };
77
- }
78
- if (!isPlainObjectLike(state)) {
79
- return {
80
- data: null,
81
- fnPaths: [],
82
- blockedReason: "Only stores whose state is a plain object can be edited — " + "a merge write has nothing to address in " + (Array.isArray(state) ? "an array" : `a ${typeof state}`) + "."
83
- };
84
- }
85
- const fnPaths = [];
86
- const data = stripFunctions(state, "", fnPaths, new WeakSet(), 0);
87
- const nested = fnPaths.filter(p => p.includes(".") || p.includes("["));
88
- if (nested.length > 0) {
89
- return {
90
- data: null,
91
- fnPaths,
92
- blockedReason: `State keeps a function inside "${nested[0]}" — a merge write of ` + "that key would drop it, so this store can't be edited here."
93
- };
94
- }
95
- return {
96
- data,
97
- fnPaths,
98
- blockedReason: null
99
- };
100
- }
101
-
102
- /**
103
- * Diff an edited draft against the state it was seeded from, as a `setState`
104
- * MERGE partial: only the top-level keys whose contents changed.
105
- *
106
- * Diffed against the SEED, not the live state at save time, on purpose — the
107
- * partial then carries exactly what the user changed, so a key the app wrote
108
- * while the editor was open and the user never touched keeps the app's value
109
- * (per-key last-write-wins, the same contract the draft's own dirtiness uses).
110
- *
111
- * Throws on the two edits a merge cannot express, naming the key: a draft
112
- * that dropped a top-level key (which is also what a raw-JSON rename produces
113
- * — the old key dropped, a new one added), because `setState(partial, false)`
114
- * would leave it exactly as it was while the editor showed it gone.
115
- */
116
- export function computeMergePartial(seed, draft) {
117
- if (!isPlainObjectLike(draft)) {
118
- throw new Error("The store's state must stay an object.");
119
- }
120
- const dropped = Object.keys(seed).filter(k => !(k in draft));
121
- if (dropped.length > 0) {
122
- throw new Error(`Can't remove top-level ${dropped.length === 1 ? "key" : "keys"} ` + `${dropped.map(k => `"${k}"`).join(", ")} — zustand merge writes ` + "can't delete. Edit the value instead.");
123
- }
124
- const partial = {};
125
- for (const key of Object.keys(draft)) {
126
- if (!(key in seed) || JSON.stringify(draft[key]) !== JSON.stringify(seed[key])) {
127
- partial[key] = draft[key];
128
- }
129
- }
130
- return partial;
131
- }
1
+ "use strict";export const STRIP_MAX_DEPTH=8;export function isPlainObjectLike(t){if("object"!=typeof t||null===t||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}export function stripFunctions(t,e,n,r,i){if("function"==typeof t)return void n.push(e);if("object"!=typeof t||null===t||i>=8)return t;if(r.has(t))return;if(r.add(t),Array.isArray(t))return t.map((t,o)=>"function"==typeof t?(n.push(`${e}[${o}]`),null):stripFunctions(t,`${e}[${o}]`,n,r,i+1));if(!isPlainObjectLike(t))return t;const o={};for(const[s,a]of Object.entries(t))"function"!=typeof a?o[s]=stripFunctions(a,e?`${e}.${s}`:s,n,r,i+1):n.push(e?`${e}.${s}`:s);return o}export function editableStateOf(t){if(isPlainObjectLike(t)&&!0===t.__buoyStateOnDevice)return{data:null,fnPaths:[],blockedReason:"Store state hasn't synced from the device yet."};if(!isPlainObjectLike(t))return{data:null,fnPaths:[],blockedReason:"Only stores whose state is a plain object can be edited — a merge write has nothing to address in "+(Array.isArray(t)?"an array":"a "+typeof t)+"."};const e=[],n=stripFunctions(t,"",e,new WeakSet,0),r=e.filter(t=>t.includes(".")||t.includes("["));return r.length>0?{data:null,fnPaths:e,blockedReason:`State keeps a function inside "${r[0]}" — a merge write of that key would drop it, so this store can't be edited here.`}:{data:n,fnPaths:e,blockedReason:null}}export function computeMergePartial(t,e){if(!isPlainObjectLike(e))throw new Error("The store's state must stay an object.");const n=Object.keys(t).filter(t=>!(t in e));if(n.length>0)throw new Error(`Can't remove top-level ${1===n.length?"key":"keys"} ${n.map(t=>`"${t}"`).join(", ")} — zustand merge writes can't delete. Edit the value instead.`);const r={};for(const n of Object.keys(e))n in t&&JSON.stringify(e[n])===JSON.stringify(t[n])||(r[n]=e[n]);return r}