@buoy-gg/zustand 7.0.38 → 7.0.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commonjs/index.js +105 -1
- package/lib/commonjs/preset.js +102 -1
- package/lib/commonjs/zustand/components/ZustandActionButton.js +118 -1
- package/lib/commonjs/zustand/components/ZustandDetailViewToggle.js +48 -1
- package/lib/commonjs/zustand/components/ZustandEventFilterView.js +43 -1
- package/lib/commonjs/zustand/components/ZustandIcon.js +18 -1
- package/lib/commonjs/zustand/components/ZustandModal.js +772 -1
- package/lib/commonjs/zustand/components/ZustandStateChangeItem.js +117 -1
- package/lib/commonjs/zustand/components/ZustandStateDetailContent.js +372 -1
- package/lib/commonjs/zustand/components/ZustandStateInfoView.js +488 -1
- package/lib/commonjs/zustand/components/ZustandStoreBrowser.js +204 -1
- package/lib/commonjs/zustand/components/ZustandStoreDetailContent.js +471 -1
- package/lib/commonjs/zustand/components/ZustandStoreEditorScreen.js +393 -1
- package/lib/commonjs/zustand/hooks/useZustandStateChanges.js +74 -1
- package/lib/commonjs/zustand/sync/zustandSyncAdapter.js +382 -1
- package/lib/commonjs/zustand/utils/buoyZustandMiddleware.js +284 -1
- package/lib/commonjs/zustand/utils/editableState.js +146 -1
- package/lib/commonjs/zustand/utils/snapshotProvider.js +209 -1
- package/lib/commonjs/zustand/utils/testIDs.js +82 -1
- package/lib/commonjs/zustand/utils/zustandStateStore.js +379 -1
- package/lib/module/index.js +90 -1
- package/lib/module/preset.js +98 -1
- package/lib/module/zustand/components/ZustandActionButton.js +114 -1
- package/lib/module/zustand/components/ZustandDetailViewToggle.js +43 -1
- package/lib/module/zustand/components/ZustandEventFilterView.js +39 -1
- package/lib/module/zustand/components/ZustandIcon.js +11 -1
- package/lib/module/zustand/components/ZustandModal.js +767 -1
- package/lib/module/zustand/components/ZustandStateChangeItem.js +113 -1
- package/lib/module/zustand/components/ZustandStateDetailContent.js +368 -1
- package/lib/module/zustand/components/ZustandStateInfoView.js +483 -1
- package/lib/module/zustand/components/ZustandStoreBrowser.js +200 -1
- package/lib/module/zustand/components/ZustandStoreDetailContent.js +469 -1
- package/lib/module/zustand/components/ZustandStoreEditorScreen.js +389 -1
- package/lib/module/zustand/hooks/useZustandStateChanges.js +70 -1
- package/lib/module/zustand/sync/zustandSyncAdapter.js +380 -1
- package/lib/module/zustand/utils/buoyZustandMiddleware.js +278 -1
- package/lib/module/zustand/utils/editableState.js +138 -1
- package/lib/module/zustand/utils/snapshotProvider.js +209 -1
- package/lib/module/zustand/utils/testIDs.js +74 -1
- package/lib/module/zustand/utils/zustandStateStore.js +375 -1
- package/lib/typescript/index.d.ts.map +1 -0
- package/lib/typescript/preset.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandActionButton.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandDetailViewToggle.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandEventFilterView.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandIcon.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandModal.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandStateChangeItem.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandStateDetailContent.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandStateInfoView.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandStoreBrowser.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandStoreDetailContent.d.ts.map +1 -0
- package/lib/typescript/zustand/components/ZustandStoreEditorScreen.d.ts.map +1 -0
- package/lib/typescript/zustand/hooks/useZustandStateChanges.d.ts.map +1 -0
- package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts.map +1 -0
- package/lib/typescript/zustand/types/index.d.ts.map +1 -0
- package/lib/typescript/zustand/utils/buoyZustandMiddleware.d.ts.map +1 -0
- package/lib/typescript/zustand/utils/editableState.d.ts.map +1 -0
- package/lib/typescript/zustand/utils/snapshotProvider.d.ts.map +1 -0
- package/lib/typescript/zustand/utils/testIDs.d.ts.map +1 -0
- package/lib/typescript/zustand/utils/zustandStateStore.d.ts.map +1 -0
- package/package.json +3 -3
|
@@ -1 +1,380 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { expandKeyedArrays, patchFromPath, readPath, refusalText, shapeSummary, suggestedPatch, typedEditViolations, unshapedLists } from "@buoy-gg/shared-ui";
|
|
4
|
+
import { zustandStateStore } from "../utils/zustandStateStore";
|
|
5
|
+
import { WIRE_DETAIL_LIMIT_BYTES, createSyncAdapter, detailByIdAction, isJsonSerializable, isOverWireBudget, memoByIdentity, onDeviceMarker, readParams, toWire, truncatedNote } from "@buoy-gg/shared-ui";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Sentinel used in WIRE-FORM snapshots in place of raw prevState/nextState.
|
|
9
|
+
* Same hazard as redux: up to 200 changes × 2 full trees on every snapshot
|
|
10
|
+
* freeze/OOM-killed large apps. Dashboards fetch trees via `getChangeDetail`.
|
|
11
|
+
*/
|
|
12
|
+
export const STATE_ON_DEVICE = onDeviceMarker("State", "State trees stay on the device — fetched on demand via getChangeDetail / getStoreState.");
|
|
13
|
+
|
|
14
|
+
/** Wire-form sentinel for an oversized `partial` (replace can carry a whole tree). */
|
|
15
|
+
export const PAYLOAD_ON_DEVICE = onDeviceMarker("Payload", "Partial stays on the device — fetched on demand via getChangeDetail.");
|
|
16
|
+
const isPlainObject = v => !!v && typeof v === "object" && !Array.isArray(v);
|
|
17
|
+
/**
|
|
18
|
+
* Does this patch write into the list at `path`? Only then is an unchecked-shape
|
|
19
|
+
* warning about that list worth saying — a patch that changes `promoCode` should
|
|
20
|
+
* not be told about an empty `lines`.
|
|
21
|
+
*/
|
|
22
|
+
function touchesList(patch, path) {
|
|
23
|
+
let cur = patch;
|
|
24
|
+
for (const seg of path.split(".")) {
|
|
25
|
+
if (!cur || typeof cur !== "object" || Array.isArray(cur)) return false;
|
|
26
|
+
if (!(seg in cur)) return false;
|
|
27
|
+
cur = cur[seg];
|
|
28
|
+
}
|
|
29
|
+
// An empty list stays empty; there is no new item to be unsure about.
|
|
30
|
+
return Array.isArray(cur) ? cur.length > 0 : !!cur && typeof cur === "object";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Top-level keys of an object state, for the compact (no-values) view. */
|
|
34
|
+
function topLevelKeys(state) {
|
|
35
|
+
return state && typeof state === "object" && !Array.isArray(state) ? Object.keys(state) : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Per-change wire cache. The store prepends and never mutates a recorded
|
|
40
|
+
* change, so keying on identity is correct and self-invalidating — without it
|
|
41
|
+
* every `partial` in the list is re-measured on all ~5 snapshots per second.
|
|
42
|
+
*/
|
|
43
|
+
const toWireChange = memoByIdentity(change => ({
|
|
44
|
+
...change,
|
|
45
|
+
prevState: STATE_ON_DEVICE,
|
|
46
|
+
nextState: STATE_ON_DEVICE,
|
|
47
|
+
partial: toWire(change.partial, PAYLOAD_ON_DEVICE)
|
|
48
|
+
}));
|
|
49
|
+
const toWireState = value => toWire(value, STATE_ON_DEVICE);
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Sync adapter for the zustand tool, consumed by @buoy-gg/external-sync's
|
|
53
|
+
* `useExternalSync`.
|
|
54
|
+
*
|
|
55
|
+
* State changes are captured by the middleware (watchStores/buoyDevTools),
|
|
56
|
+
* independent of whether a dashboard is watching — subscribing here only
|
|
57
|
+
* streams what the store already records. The snapshot carries both the
|
|
58
|
+
* change timeline and the store registry (with each store's current state)
|
|
59
|
+
* so the dashboard can render the store browser.
|
|
60
|
+
*
|
|
61
|
+
* v2: change-log prevState/nextState are replaced with on-device markers
|
|
62
|
+
* (see STATE_ON_DEVICE). Dashboards fetch trees via `getChangeDetail`.
|
|
63
|
+
* Oversized / unserializable `stores[].currentState` uses the same marker
|
|
64
|
+
* and is fetched via `getStoreState`.
|
|
65
|
+
*
|
|
66
|
+
* The `setState` action powers remote time-travel/reset from the dashboard.
|
|
67
|
+
*/
|
|
68
|
+
export const zustandSyncAdapter = createSyncAdapter({
|
|
69
|
+
version: 2,
|
|
70
|
+
getSnapshot: () => ({
|
|
71
|
+
changes: zustandStateStore.getStateChanges().map(toWireChange),
|
|
72
|
+
stores: zustandStateStore.getStoreSnapshots().map(store => ({
|
|
73
|
+
...store,
|
|
74
|
+
currentState: toWireState(store.currentState)
|
|
75
|
+
}))
|
|
76
|
+
}),
|
|
77
|
+
subscribe: [onChange => zustandStateStore.subscribe(onChange), onChange => zustandStateStore.subscribeToStores(onChange)],
|
|
78
|
+
actions: {
|
|
79
|
+
clearEvents: () => {
|
|
80
|
+
zustandStateStore.clearStateChanges();
|
|
81
|
+
},
|
|
82
|
+
/**
|
|
83
|
+
* On-demand detail: one change's real prevState/nextState/partial.
|
|
84
|
+
* The per-snapshot stream stays tree-free; this is the explicit,
|
|
85
|
+
* size-guarded channel for the detail pane.
|
|
86
|
+
*/
|
|
87
|
+
getChangeDetail: detailByIdAction(id => zustandStateStore.getStateChangeById(id), (change, cap) => ({
|
|
88
|
+
prevState: cap(change.prevState),
|
|
89
|
+
nextState: cap(change.nextState),
|
|
90
|
+
partial: cap(change.partial)
|
|
91
|
+
})),
|
|
92
|
+
/**
|
|
93
|
+
* On-demand current state for one store. Wire-form snapshots replace
|
|
94
|
+
* oversized / unserializable `currentState` with STATE_ON_DEVICE.
|
|
95
|
+
*/
|
|
96
|
+
getStoreState: params => {
|
|
97
|
+
const {
|
|
98
|
+
storeName,
|
|
99
|
+
path
|
|
100
|
+
} = readParams(params);
|
|
101
|
+
if (!storeName) return {
|
|
102
|
+
found: false,
|
|
103
|
+
reason: "missing storeName"
|
|
104
|
+
};
|
|
105
|
+
const store = zustandStateStore.getStore(storeName);
|
|
106
|
+
if (!store) return {
|
|
107
|
+
found: false,
|
|
108
|
+
reason: "unknown storeName"
|
|
109
|
+
};
|
|
110
|
+
let currentState;
|
|
111
|
+
try {
|
|
112
|
+
currentState = store.api.getState();
|
|
113
|
+
} catch {
|
|
114
|
+
currentState = undefined;
|
|
115
|
+
}
|
|
116
|
+
// One slice instead of the whole store. The reason to want it is the
|
|
117
|
+
// engine's 24,000-character result cap: a caller that never saw the field
|
|
118
|
+
// it means to edit is left inventing a shape, which is the failure this
|
|
119
|
+
// whole surface keeps producing.
|
|
120
|
+
if (path) {
|
|
121
|
+
const at = readPath(currentState, path);
|
|
122
|
+
if (!at.ok) return {
|
|
123
|
+
found: false,
|
|
124
|
+
reason: at.error
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
found: true,
|
|
128
|
+
storeName,
|
|
129
|
+
path,
|
|
130
|
+
shape: shapeSummary(at.value),
|
|
131
|
+
currentState: at.value
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
// The sketch goes BEFORE currentState, deliberately. The engine truncates
|
|
135
|
+
// a result by slicing the encoded string at 24,000 characters, so whatever
|
|
136
|
+
// is serialised first is what survives — and the reads most in need of a
|
|
137
|
+
// shape are exactly the long ones that get cut. It costs ~150 characters
|
|
138
|
+
// and does not grow with the data.
|
|
139
|
+
const shape = shapeSummary(currentState);
|
|
140
|
+
if (!isOverWireBudget(currentState, WIRE_DETAIL_LIMIT_BYTES)) {
|
|
141
|
+
return {
|
|
142
|
+
found: true,
|
|
143
|
+
storeName,
|
|
144
|
+
...(shape ? {
|
|
145
|
+
shape
|
|
146
|
+
} : {}),
|
|
147
|
+
currentState
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
found: true,
|
|
152
|
+
storeName,
|
|
153
|
+
...(shape ? {
|
|
154
|
+
shape
|
|
155
|
+
} : {}),
|
|
156
|
+
currentState: isJsonSerializable(currentState) ? truncatedNote(WIRE_DETAIL_LIMIT_BYTES) : STATE_ON_DEVICE
|
|
157
|
+
};
|
|
158
|
+
},
|
|
159
|
+
/**
|
|
160
|
+
* Compact current-state reader for a remote driver (MCP/LLM): the registered
|
|
161
|
+
* stores with light metadata; each store's full `currentState` object stays
|
|
162
|
+
* on the device unless `includeValues` is set (compact view returns just the
|
|
163
|
+
* top-level `keys` so the shape is visible cheaply).
|
|
164
|
+
*/
|
|
165
|
+
listStores: params => {
|
|
166
|
+
const {
|
|
167
|
+
includeValues = false,
|
|
168
|
+
limit
|
|
169
|
+
} = readParams(params);
|
|
170
|
+
const all = zustandStateStore.getStoreSnapshots();
|
|
171
|
+
const capped = typeof limit === "number" && limit > 0 ? all.slice(0, limit) : all;
|
|
172
|
+
const stores = capped.map(s => ({
|
|
173
|
+
name: s.name,
|
|
174
|
+
changes: s.stateChangeCount,
|
|
175
|
+
isPersisted: s.isPersisted,
|
|
176
|
+
persistName: s.persistName,
|
|
177
|
+
canRehydrate: s.canRehydrate,
|
|
178
|
+
...(includeValues ? {
|
|
179
|
+
currentState: s.currentState
|
|
180
|
+
} : {
|
|
181
|
+
keys: topLevelKeys(s.currentState)
|
|
182
|
+
}),
|
|
183
|
+
// Cheap enough to always include: this is the compact view a caller
|
|
184
|
+
// reaches for precisely because it does not want to pull the data, and
|
|
185
|
+
// the item shape of a list is the one thing it cannot infer without it.
|
|
186
|
+
...(shapeSummary(s.currentState) ? {
|
|
187
|
+
shape: shapeSummary(s.currentState)
|
|
188
|
+
} : {})
|
|
189
|
+
}));
|
|
190
|
+
return {
|
|
191
|
+
stores,
|
|
192
|
+
total: all.length,
|
|
193
|
+
returned: stores.length,
|
|
194
|
+
includedValues: includeValues
|
|
195
|
+
};
|
|
196
|
+
},
|
|
197
|
+
setState: params => {
|
|
198
|
+
const {
|
|
199
|
+
storeName,
|
|
200
|
+
state,
|
|
201
|
+
replace,
|
|
202
|
+
force,
|
|
203
|
+
path,
|
|
204
|
+
value
|
|
205
|
+
} = readParams(params);
|
|
206
|
+
let effective = state;
|
|
207
|
+
let keyedNotes = [];
|
|
208
|
+
let unchecked = [];
|
|
209
|
+
if (!storeName) return {
|
|
210
|
+
ok: false,
|
|
211
|
+
error: "Missing storeName."
|
|
212
|
+
};
|
|
213
|
+
const store = zustandStateStore.getStore(storeName);
|
|
214
|
+
if (!store) return {
|
|
215
|
+
ok: false,
|
|
216
|
+
error: `No store named "${storeName}".`
|
|
217
|
+
};
|
|
218
|
+
// `path` is sugar over a merge: it can only ever produce a patch, which
|
|
219
|
+
// then goes through the guard below like any other. Its value is that
|
|
220
|
+
// there is no nesting depth for the caller to get wrong.
|
|
221
|
+
// `state` is no longer schema-required, because `path`+`value` is a valid
|
|
222
|
+
// alternative — so the handler has to be the thing that rejects NEITHER.
|
|
223
|
+
// Without this, `state` arrives undefined and falls through to
|
|
224
|
+
// `setState(undefined, true)`, which is zustand's whole-state replace: the
|
|
225
|
+
// store's data AND its action functions, gone, from a call that looks like
|
|
226
|
+
// a typo. This is the most destructive thing in this file.
|
|
227
|
+
if (state === undefined && path === undefined) {
|
|
228
|
+
return {
|
|
229
|
+
ok: false,
|
|
230
|
+
error: `Refused: no change was described. Send \`state\` with the fields to merge, or \`path\` and \`value\` to set one value.`
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
let pathed = false;
|
|
234
|
+
if (path !== undefined) {
|
|
235
|
+
if (value === undefined) {
|
|
236
|
+
return {
|
|
237
|
+
ok: false,
|
|
238
|
+
error: `Refused: sent \`path\` without \`value\`. Say what to set "${path}" to; if you mean to clear it, send value:null and the field must already be nullable.`
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
let currentForPath;
|
|
242
|
+
try {
|
|
243
|
+
currentForPath = store.api.getState();
|
|
244
|
+
} catch {
|
|
245
|
+
currentForPath = undefined;
|
|
246
|
+
}
|
|
247
|
+
const built = patchFromPath(currentForPath, path, value);
|
|
248
|
+
if (!built.ok) return {
|
|
249
|
+
ok: false,
|
|
250
|
+
error: `Refused: ${built.error}`
|
|
251
|
+
};
|
|
252
|
+
effective = built.patch;
|
|
253
|
+
pathed = true;
|
|
254
|
+
}
|
|
255
|
+
// On a MERGE (replace:false), constrain it to a typed edit so a remote
|
|
256
|
+
// caller can't hand the store a field of the wrong type or a malformed
|
|
257
|
+
// new list item — the same protection the query cache has. A replace
|
|
258
|
+
// (whole-store reset) and an explicit `force` skip this.
|
|
259
|
+
if (!force && (replace === false || pathed)) {
|
|
260
|
+
let current;
|
|
261
|
+
try {
|
|
262
|
+
current = store.api.getState();
|
|
263
|
+
} catch {
|
|
264
|
+
current = undefined;
|
|
265
|
+
}
|
|
266
|
+
// Expand id-addressed list edits BEFORE validating, so the typed-edit
|
|
267
|
+
// guard below sees a real array and every existing protection still
|
|
268
|
+
// applies to the result.
|
|
269
|
+
if (current !== undefined) {
|
|
270
|
+
const expanded = expandKeyedArrays(current, effective);
|
|
271
|
+
// See keyedArrays.ts: an added item whose id disagrees with the key
|
|
272
|
+
// it was sent under is ambiguous, and only this layer can say so.
|
|
273
|
+
if (expanded.error) {
|
|
274
|
+
return {
|
|
275
|
+
ok: false,
|
|
276
|
+
error: `Refused: ${expanded.error}`
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
effective = expanded.patch;
|
|
280
|
+
keyedNotes = expanded.notes;
|
|
281
|
+
}
|
|
282
|
+
// The guard builds its template from `list[0]`, so a list that is EMPTY
|
|
283
|
+
// has no template and an added item is written with nothing to check it
|
|
284
|
+
// against. That is not a rare corner: it is every "add the first thing"
|
|
285
|
+
// flow, and it is where models invent shapes, because on an empty list
|
|
286
|
+
// the item shape genuinely exists nowhere in the running app. We cannot
|
|
287
|
+
// refuse it — refusing would break adding the first item to anything —
|
|
288
|
+
// so we say so instead of letting the guess through unremarked.
|
|
289
|
+
if (current !== undefined) {
|
|
290
|
+
unchecked = unshapedLists(current).filter(path => touchesList(effective, path));
|
|
291
|
+
}
|
|
292
|
+
if (current !== undefined) {
|
|
293
|
+
const violations = typedEditViolations(current, effective, {
|
|
294
|
+
noun: "store"
|
|
295
|
+
});
|
|
296
|
+
if (violations.length > 0) {
|
|
297
|
+
return {
|
|
298
|
+
ok: false,
|
|
299
|
+
error: refusalText(violations, "store", suggestedPatch(effective, violations)),
|
|
300
|
+
...(suggestedPatch(effective, violations) ? {
|
|
301
|
+
suggestedState: suggestedPatch(effective, violations)
|
|
302
|
+
} : {}),
|
|
303
|
+
violations
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// A pathed write is a merge by construction — it names one value, so it
|
|
309
|
+
// must never fall through to zustand's default whole-state replace.
|
|
310
|
+
store.api.setState(effective, pathed ? false : replace ?? true);
|
|
311
|
+
// Say what an addressed edit resolved to. A caller that meant to change one
|
|
312
|
+
// line and sees "17 item(s) remain" has caught its own mistake.
|
|
313
|
+
return {
|
|
314
|
+
ok: true,
|
|
315
|
+
...(path !== undefined ? {
|
|
316
|
+
path
|
|
317
|
+
} : {}),
|
|
318
|
+
...(keyedNotes.length ? {
|
|
319
|
+
keyed: keyedNotes
|
|
320
|
+
} : {}),
|
|
321
|
+
...(unchecked.length ? {
|
|
322
|
+
unchecked: unchecked.map(path => `\`${path}\` 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.`)
|
|
323
|
+
} : {})
|
|
324
|
+
};
|
|
325
|
+
},
|
|
326
|
+
/**
|
|
327
|
+
* Re-read a persisted store's saved value and merge it into the live store.
|
|
328
|
+
*
|
|
329
|
+
* This is what makes editing a store's storage key mean anything. The app
|
|
330
|
+
* reads that key once at startup and then holds the state in memory, so an
|
|
331
|
+
* outside write — the Storage tool, a scenario, an agent — changes the disk
|
|
332
|
+
* and nothing else, and the next time the store saves it writes its own
|
|
333
|
+
* copy straight back over the edit.
|
|
334
|
+
*
|
|
335
|
+
* `persist.rehydrate()` is plain zustand, not a devtools hook, so unlike
|
|
336
|
+
* reloading the app this also works in a release build. It merges the saved
|
|
337
|
+
* value OVER current state (zustand's default merge is
|
|
338
|
+
* `{...current, ...persisted}`), so the store's action functions survive,
|
|
339
|
+
* and it does not write back to storage unless a version migration ran —
|
|
340
|
+
* the edit stays exactly as it was typed.
|
|
341
|
+
*
|
|
342
|
+
* Two honest limits, both inherent to persist rather than to this action:
|
|
343
|
+
* a key the store's `partialize` excludes is not in the saved value and so
|
|
344
|
+
* cannot be applied, and because the merge is shallow, DELETING a top-level
|
|
345
|
+
* key from the saved JSON does not remove it from the live store.
|
|
346
|
+
*/
|
|
347
|
+
rehydrate: async params => {
|
|
348
|
+
const {
|
|
349
|
+
storeName
|
|
350
|
+
} = readParams(params);
|
|
351
|
+
if (!storeName) return {
|
|
352
|
+
ok: false,
|
|
353
|
+
error: "Missing storeName."
|
|
354
|
+
};
|
|
355
|
+
const store = zustandStateStore.getStore(storeName);
|
|
356
|
+
if (!store) return {
|
|
357
|
+
ok: false,
|
|
358
|
+
error: `No store named "${storeName}".`
|
|
359
|
+
};
|
|
360
|
+
if (!store.isPersisted) {
|
|
361
|
+
return {
|
|
362
|
+
ok: false,
|
|
363
|
+
error: `"${storeName}" is not a persisted store — it has no saved copy to re-read.`
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
if (!store.rehydrate) {
|
|
367
|
+
return {
|
|
368
|
+
ok: false,
|
|
369
|
+
error: `"${storeName}" is persisted but Buoy has no rehydrate handle for it. It was probably registered before the app's persist middleware attached.`
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
await store.rehydrate();
|
|
373
|
+
return {
|
|
374
|
+
ok: true,
|
|
375
|
+
storeName,
|
|
376
|
+
persistName: store.persistName
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
});
|
|
@@ -1 +1,278 @@
|
|
|
1
|
-
"use strict";
|
|
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
|
+
}
|