@wizardkit/state 0.0.0-stage → 1.13.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Georgiy Tsamaladze
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # @wizardkit/state
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Internal adapter package** — used by `@wizardkit/react` and `@wizardkit/vue`. Most applications should depend on the React/Vue packages only; import `WizardStateManager` from those packages when needed for advanced integrations.
4
+
5
+ A state management layer for multi-step wizards. Provides fine-grained subscription channels for efficient React component rendering when using `useSyncExternalStore`.
6
+
7
+ ## Overview
8
+
9
+ `WizardStateManager` wraps a `WizardMachine` instance and adds a subscription-based state notification system. This enables React hooks to subscribe to specific state channels (state, navigation, validation, loading) for selective re-renders, avoiding unnecessary updates.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pnpm add @wizardkit/state @wizardkit/core
15
+ ```
16
+
17
+ ## Basic Usage
18
+
19
+ ```typescript
20
+ import { WizardMachine } from "@wizardkit/core";
21
+ import { WizardStateManager } from "@wizardkit/state";
22
+
23
+ // Create a wizard machine
24
+ const machine = new WizardMachine(wizardDefinition, context, initialData);
25
+
26
+ // Wrap it with the state manager
27
+ const manager = new WizardStateManager(machine, "step-1");
28
+
29
+ // Subscribe to state changes
30
+ const unsubscribe = manager.subscribe(() => {
31
+ console.log("State changed");
32
+ });
33
+
34
+ // Subscribe to specific channel
35
+ const navUnsubscribe = manager.subscribe(
36
+ () => {
37
+ console.log("Navigation state changed");
38
+ },
39
+ "navigation"
40
+ );
41
+
42
+ // Handle machine state changes
43
+ manager.handleStateChange(newState, oldState);
44
+
45
+ // Clean up
46
+ unsubscribe();
47
+ navUnsubscribe();
48
+ ```
49
+
50
+ ## API
51
+
52
+ ### Constructor
53
+
54
+ ```typescript
55
+ new WizardStateManager<T extends WizardData>(
56
+ machine: WizardMachine<T>,
57
+ initialStepId: StepId
58
+ )
59
+ ```
60
+
61
+ Creates a state manager wrapping the provided machine.
62
+
63
+ ### Subscription Methods
64
+
65
+ #### `subscribe(listener, channel?)`
66
+
67
+ Subscribes to state changes on a specific channel or all channels.
68
+
69
+ ```typescript
70
+ // Subscribe to all channels (default)
71
+ const unsub = manager.subscribe(() => console.log("Any change"));
72
+
73
+ // Subscribe to specific channel
74
+ const navUnsub = manager.subscribe(
75
+ () => console.log("Navigation changed"),
76
+ "navigation"
77
+ );
78
+ ```
79
+
80
+ **Channels:**
81
+
82
+ - `"state"` - Data or current step changes
83
+ - `"navigation"` - Navigation capabilities (canGoNext, canGoPrevious)
84
+ - `"validation"` - Validation state or errors
85
+ - `"loading"` - Loading flags (isValidating, isSubmitting, isNavigating, isLoadingStep)
86
+ - `"all"` - All channels (default)
87
+
88
+ ### Snapshot Methods
89
+
90
+ #### `getStateSnapshot()`
91
+
92
+ Returns cached state snapshot for the current step and data.
93
+
94
+ ```typescript
95
+ const snapshot = manager.getStateSnapshot();
96
+ console.log(snapshot.currentStepId, snapshot.data);
97
+ ```
98
+
99
+ #### `getNavigationSnapshot()`
100
+
101
+ Returns cached navigation state (async-computed).
102
+
103
+ ```typescript
104
+ const navSnap = manager.getNavigationSnapshot();
105
+ console.log(navSnap.canGoNext, navSnap.canGoPrevious);
106
+ ```
107
+
108
+ #### `getValidationSnapshot()`
109
+
110
+ Returns cached validation state.
111
+
112
+ ```typescript
113
+ const validSnap = manager.getValidationSnapshot();
114
+ console.log(validSnap.isValid, validSnap.validationErrors);
115
+ ```
116
+
117
+ #### `getLoadingSnapshot()`
118
+
119
+ Returns cached loading state.
120
+
121
+ ```typescript
122
+ const loadingSnap = manager.getLoadingSnapshot();
123
+ console.log(loadingSnap.isValidating, loadingSnap.isSubmitting);
124
+ ```
125
+
126
+ ### State Management
127
+
128
+ #### `handleStateChange(newState, oldState)`
129
+
130
+ Called when the machine state changes. Automatically determines which channels to notify based on what actually changed.
131
+
132
+ ```typescript
133
+ machine.subscribe((newState, oldState) => {
134
+ manager.handleStateChange(newState, oldState);
135
+ });
136
+ ```
137
+
138
+ #### `setLoadingState(update)`
139
+
140
+ Updates loading state and notifies loading channel subscribers.
141
+
142
+ ```typescript
143
+ manager.setLoadingState({ isValidating: true });
144
+ ```
145
+
146
+ `isLoadingStep` (WIZ-013) is different from the other flags: it mirrors `machine.snapshot.isLoadingStep` and is seeded from the snapshot, so `trackLoading()` only accepts `TrackedLoadingFlag` (`"isValidating" | "isSubmitting" | "isNavigating"`) — `trackLoading("isLoadingStep")` is a type error. `setLoadingState()` likewise only accepts the tracked flags (`isLoadingStep` is a type error). When the machine replaces the current step's definition without any other state change (a background `preloadStep()` / `validateAll()` of the current step), the manager refreshes the `"state"` slice's `currentStep`. `createWizardActions` adds `preloadStep(stepId)`, which prefetches a lazy step without touching any loading flag and **never rejects** (failures are reported by the navigation that needs the step; `machine.preloadStep()` itself still rejects).
147
+
148
+ ### Notification
149
+
150
+ #### `notifySubscribers(channels)`
151
+
152
+ Manually notify subscribers of specific channels.
153
+
154
+ ```typescript
155
+ manager.notifySubscribers(["state", "navigation"]);
156
+ ```
157
+
158
+ ### Machine Access
159
+
160
+ #### `getMachine()`
161
+
162
+ Get direct access to the underlying machine.
163
+
164
+ ```typescript
165
+ const machine = manager.getMachine();
166
+ ```
167
+
168
+ #### `getCurrentStep()`
169
+
170
+ Get the current step definition.
171
+
172
+ ```typescript
173
+ const step = manager.getCurrentStep();
174
+ ```
175
+
176
+ #### `getVisitedSteps()`
177
+
178
+ Get list of visited step IDs.
179
+
180
+ ```typescript
181
+ const visited = manager.getVisitedSteps();
182
+ ```
183
+
184
+ #### `getStepHistory()`
185
+
186
+ Get ordered history of step navigation.
187
+
188
+ ```typescript
189
+ const history = manager.getStepHistory();
190
+ ```
191
+
192
+ ## Design Philosophy
193
+
194
+ - **Cached Snapshots** - All snapshot getters return the same reference until the underlying data actually changes, enabling `useSyncExternalStore` stability
195
+ - **Channel-Based Subscriptions** - Listeners only receive notifications for the specific channels they care about, reducing unnecessary React renders
196
+ - **Async Navigation** - Navigation capabilities are computed asynchronously in the background to avoid blocking renders. `canGoNext` / `isLastStep` are seeded synchronously from the machine's `progress.isLastStep` (on creation and on every step change), so the first render is already correct for synchronous graphs
197
+
198
+ ## See Also
199
+
200
+ - [@wizardkit/core](https://www.npmjs.com/package/@wizardkit/core) - Core state machine
201
+ - [@wizardkit/react](https://www.npmjs.com/package/@wizardkit/react) - React hooks using WizardStateManager
@@ -0,0 +1,47 @@
1
+ import { GoToOptions, StepId, ValidationSummary, WizardData, WizardSerializedState } from '@wizardkit/core';
2
+ import { WizardStateManager } from './manager';
3
+ /**
4
+ * The imperative action surface every binding exposes.
5
+ */
6
+ export interface WizardBindingActions<T extends WizardData> {
7
+ updateData: (updater: (data: T) => T) => void;
8
+ setData: (data: T) => void;
9
+ updateField: <K extends keyof T>(field: K, value: T[K]) => void;
10
+ validate: () => Promise<void>;
11
+ validateAll: (options?: {
12
+ updateStatuses?: boolean;
13
+ }) => Promise<ValidationSummary>;
14
+ canSubmit: () => Promise<boolean>;
15
+ submit: () => Promise<void>;
16
+ reset: (data?: T) => void;
17
+ cancel: () => Promise<void>;
18
+ serialize: () => WizardSerializedState<T>;
19
+ restore: (state: WizardSerializedState<T>) => void;
20
+ goNext: () => Promise<void>;
21
+ goPrevious: () => Promise<void>;
22
+ goBack: (steps?: number) => Promise<void>;
23
+ goTo: (stepId: StepId, options?: GoToOptions) => Promise<void>;
24
+ goToStep: (stepId: StepId) => Promise<void>;
25
+ /**
26
+ * WIZ-013: prefetch a lazy step's implementation (no loading flag).
27
+ * Never rejects (including an unknown step id): meant for fire-and-forget
28
+ * hover/focus handlers; failures are reported by the navigation that needs
29
+ * the step. `machine.preloadStep()` itself still rejects.
30
+ */
31
+ preloadStep: (stepId: StepId) => Promise<void>;
32
+ }
33
+ /**
34
+ * Builds the binding action callbacks on top of a manager.
35
+ *
36
+ * - Data mutators call the machine directly (updateField keeps its Object.is
37
+ * no-op guard).
38
+ * - validate/validateAll hold "isValidating", submit holds "isSubmitting", and
39
+ * navigation holds "isNavigating", all via the reference-counted
40
+ * `manager.trackLoading()`: a busy-rejected double click does not clear the
41
+ * flag of the navigation still in flight.
42
+ * - reset/restore are fire-and-forget; their failures (e.g. a malformed
43
+ * snapshot raising WizardRestoreError) go to `reportError` instead of
44
+ * becoming unhandled rejections. `reset(data)` passes `data` through
45
+ * unchanged, so `reset()` uses the machine's current reset baseline.
46
+ */
47
+ export declare function createWizardActions<T extends WizardData>(manager: WizardStateManager<T>, reportError: (error: unknown) => void): WizardBindingActions<T>;
@@ -0,0 +1,6 @@
1
+ export type { WizardBindingActions } from './actions';
2
+ export { createWizardActions } from './actions';
3
+ export { WizardStateManager } from './manager';
4
+ export type { LoadingState, NavigationState, StateSnapshot, SubscriptionChannel, SubscriptionListener, TrackedLoadingFlag, ValidationState, WizardStateManagerOptions, } from './types';
5
+ export type { CreateMachineAndManagerOptions, WizardCallbacks } from './wiring';
6
+ export { createMachineAndManager } from './wiring';
package/dist/index.js ADDED
@@ -0,0 +1,353 @@
1
+ import { WizardMachine as e } from "@wizardkit/core";
2
+ //#region src/actions.ts
3
+ function t(e, t) {
4
+ let n = e.getMachine(), r = (t) => e.trackLoading("isNavigating", t), i = (e, t) => r(() => n.goTo(e, t));
5
+ return {
6
+ updateData: (e) => n.updateData(e),
7
+ setData: (e) => n.setData(e),
8
+ updateField: (e, t) => n.updateField(e, t),
9
+ validate: () => e.trackLoading("isValidating", async () => {
10
+ await n.validate();
11
+ }),
12
+ validateAll: (t) => e.trackLoading("isValidating", () => n.validateAll(t)),
13
+ canSubmit: () => n.canSubmit(),
14
+ submit: () => e.trackLoading("isSubmitting", () => n.submit()),
15
+ reset: (n) => {
16
+ e.runReset(n).catch(t);
17
+ },
18
+ cancel: () => e.runCancel(),
19
+ serialize: () => n.serialize(),
20
+ restore: (n) => {
21
+ e.runRestore(n).catch(t);
22
+ },
23
+ goNext: () => r(() => n.goNext()),
24
+ goPrevious: () => r(() => n.goPrevious()),
25
+ goBack: (e) => r(() => n.goBack(e)),
26
+ goTo: i,
27
+ goToStep: (e) => i(e, { skipValidation: !0 }),
28
+ preloadStep: (e) => n.preloadStep(e).catch(() => {})
29
+ };
30
+ }
31
+ //#endregion
32
+ //#region src/manager.ts
33
+ var n = class {
34
+ machine;
35
+ subscribers;
36
+ stateCache;
37
+ navigationCache;
38
+ validationCache;
39
+ loadingCache;
40
+ loadingCounts = {
41
+ isValidating: 0,
42
+ isSubmitting: 0,
43
+ isNavigating: 0
44
+ };
45
+ loadingEpoch = 0;
46
+ snapshotCache;
47
+ navigationPromise = null;
48
+ navigationDirty = !1;
49
+ destroyed = !1;
50
+ navigationSeedStepId;
51
+ initialStepId;
52
+ options;
53
+ lastState;
54
+ constructor(e, t, n = {}) {
55
+ this.machine = e, this.initialStepId = t, this.options = n, this.subscribers = /* @__PURE__ */ new Map([
56
+ ["state", /* @__PURE__ */ new Set()],
57
+ ["navigation", /* @__PURE__ */ new Set()],
58
+ ["validation", /* @__PURE__ */ new Set()],
59
+ ["loading", /* @__PURE__ */ new Set()],
60
+ ["all", /* @__PURE__ */ new Set()]
61
+ ]);
62
+ let r = this.machine.snapshot;
63
+ this.loadingCache = {
64
+ isValidating: !1,
65
+ isSubmitting: !1,
66
+ isNavigating: !1,
67
+ isLoadingStep: r.isLoadingStep
68
+ }, this.snapshotCache = r, this.lastState = r, this.stateCache = {
69
+ currentStepId: r.currentStepId,
70
+ currentStep: this.machine.currentStep,
71
+ data: r.data,
72
+ isCompleted: r.isCompleted,
73
+ stepStatuses: r.stepStatuses,
74
+ progress: r.progress
75
+ }, this.validationCache = {
76
+ isValid: r.isValid,
77
+ validationErrors: r.validationErrors
78
+ }, this.navigationCache = {
79
+ canGoNext: !r.progress.isLastStep,
80
+ canGoPrevious: !1,
81
+ canGoBack: r.canGoBack,
82
+ availableSteps: [],
83
+ isFirstStep: r.currentStepId === this.initialStepId,
84
+ isLastStep: r.progress.isLastStep,
85
+ visitedSteps: [...this.machine.visited],
86
+ stepHistory: [...this.machine.history]
87
+ }, this.navigationSeedStepId = r.currentStepId, this.computeNavigationStateAsync();
88
+ }
89
+ subscribe(e, t = "all") {
90
+ let n = this.subscribers.get(t);
91
+ return n && n.add(e), () => {
92
+ let n = this.subscribers.get(t);
93
+ n && n.delete(e);
94
+ };
95
+ }
96
+ notifySubscribers(e) {
97
+ if (this.destroyed) return;
98
+ this.snapshotCache = this.machine.snapshot;
99
+ for (let t of e) t === "state" && this.updateStateCache(), t === "navigation" && (this.updateNavigationCacheSync(), this.computeNavigationStateAsync()), t === "validation" && this.updateValidationCache();
100
+ let t = /* @__PURE__ */ new Set();
101
+ for (let n of e) {
102
+ let e = this.subscribers.get(n);
103
+ if (e) for (let n of e) t.add(n);
104
+ }
105
+ let n = this.subscribers.get("all");
106
+ if (n) for (let e of n) t.add(e);
107
+ for (let e of t) e();
108
+ }
109
+ updateStateCache() {
110
+ let e = this.snapshotCache;
111
+ this.stateCache = {
112
+ currentStepId: e.currentStepId,
113
+ currentStep: this.machine.currentStep,
114
+ data: e.data,
115
+ isCompleted: e.isCompleted,
116
+ stepStatuses: e.stepStatuses,
117
+ progress: e.progress
118
+ };
119
+ }
120
+ updateValidationCache() {
121
+ let e = this.snapshotCache;
122
+ this.validationCache = {
123
+ isValid: e.isValid,
124
+ validationErrors: e.validationErrors
125
+ };
126
+ }
127
+ updateNavigationCacheSync() {
128
+ let e = this.snapshotCache, t = e.currentStepId !== this.navigationSeedStepId;
129
+ t && (this.navigationSeedStepId = e.currentStepId), this.navigationCache = {
130
+ ...this.navigationCache,
131
+ canGoNext: t ? !e.progress.isLastStep : this.navigationCache.canGoNext,
132
+ isLastStep: t ? e.progress.isLastStep : this.navigationCache.isLastStep,
133
+ canGoBack: e.canGoBack,
134
+ isFirstStep: e.currentStepId === this.initialStepId,
135
+ visitedSteps: [...this.machine.visited],
136
+ stepHistory: [...this.machine.history]
137
+ };
138
+ }
139
+ getSnapshot() {
140
+ return this.snapshotCache;
141
+ }
142
+ getStateSnapshot() {
143
+ return this.stateCache;
144
+ }
145
+ getCurrentStep() {
146
+ return this.machine.currentStep;
147
+ }
148
+ getNavigationSnapshot() {
149
+ return this.navigationCache;
150
+ }
151
+ computeNavigationStateAsync() {
152
+ if (this.navigationPromise) {
153
+ this.navigationDirty = !0;
154
+ return;
155
+ }
156
+ if (this.destroyed) return;
157
+ this.navigationDirty = !1;
158
+ let e = this.machine.snapshot.currentStepId;
159
+ this.navigationPromise = (async () => {
160
+ try {
161
+ let [t, n, r] = await Promise.all([
162
+ this.machine.getNextStepId(),
163
+ this.machine.getPreviousStepId(),
164
+ this.machine.getAvailableSteps()
165
+ ]);
166
+ if (this.destroyed) return;
167
+ let i = this.machine.snapshot;
168
+ if (i.currentStepId !== e) {
169
+ this.navigationDirty = !0;
170
+ return;
171
+ }
172
+ let a = {
173
+ canGoNext: !!t,
174
+ canGoPrevious: !!n,
175
+ canGoBack: i.canGoBack,
176
+ availableSteps: r,
177
+ isFirstStep: i.currentStepId === this.initialStepId,
178
+ isLastStep: !t,
179
+ visitedSteps: [...this.machine.visited],
180
+ stepHistory: [...this.machine.history]
181
+ };
182
+ this.navigationStateEqual(this.navigationCache, a) || (this.navigationCache = a, this.navigationSeedStepId = e, this.notifySubscribersForChannel("navigation"));
183
+ } catch (e) {
184
+ this.destroyed || this.reportError(e);
185
+ } finally {
186
+ this.navigationPromise = null, this.navigationDirty && !this.destroyed && (this.navigationDirty = !1, this.computeNavigationStateAsync());
187
+ }
188
+ })();
189
+ }
190
+ reportError(e) {
191
+ let t = e instanceof Error ? e : Error(String(e)), { onError: n } = this.options;
192
+ if (!n) {
193
+ console.error("[WizardStateManager] navigation computation failed:", t);
194
+ return;
195
+ }
196
+ try {
197
+ n(t);
198
+ } catch (e) {
199
+ console.error("[WizardStateManager] onError handler threw:", e), console.error("[WizardStateManager] navigation computation failed:", t);
200
+ }
201
+ }
202
+ navigationStateEqual(e, t) {
203
+ return e.canGoNext === t.canGoNext && e.canGoPrevious === t.canGoPrevious && e.canGoBack === t.canGoBack && e.isFirstStep === t.isFirstStep && e.isLastStep === t.isLastStep && this.stepIdsEqual(e.availableSteps, t.availableSteps) && this.stepIdsEqual(e.visitedSteps, t.visitedSteps) && this.stepIdsEqual(e.stepHistory, t.stepHistory);
204
+ }
205
+ stepIdsEqual(e, t) {
206
+ if (e.length !== t.length) return !1;
207
+ for (let n = 0; n < e.length; n++) if (e[n] !== t[n]) return !1;
208
+ return !0;
209
+ }
210
+ notifySubscribersForChannel(e) {
211
+ if (this.destroyed) return;
212
+ let t = this.subscribers.get(e);
213
+ if (t) for (let e of t) e();
214
+ let n = this.subscribers.get("all");
215
+ if (n) for (let e of n) e();
216
+ }
217
+ getValidationSnapshot() {
218
+ return this.validationCache;
219
+ }
220
+ getLoadingSnapshot() {
221
+ return this.loadingCache;
222
+ }
223
+ setLoadingState(e) {
224
+ this.destroyed || (this.loadingCache = {
225
+ ...this.loadingCache,
226
+ ...e
227
+ }, this.notifySubscribersForChannel("loading"));
228
+ }
229
+ async trackLoading(e, t) {
230
+ let n = this.loadingEpoch;
231
+ this.loadingCounts[e] += 1, this.setLoadingFlag(e, !0);
232
+ try {
233
+ return await t();
234
+ } finally {
235
+ n === this.loadingEpoch && (this.loadingCounts[e] = Math.max(0, this.loadingCounts[e] - 1), this.loadingCounts[e] === 0 && this.setLoadingFlag(e, !1));
236
+ }
237
+ }
238
+ setLoadingFlag(e, t) {
239
+ this.loadingCache[e] !== t && this.setLoadingState({ [e]: t });
240
+ }
241
+ discardLoadingRefs() {
242
+ this.loadingEpoch += 1, this.loadingCounts = {
243
+ isValidating: 0,
244
+ isSubmitting: 0,
245
+ isNavigating: 0
246
+ };
247
+ }
248
+ forceLoadingOff() {
249
+ this.discardLoadingRefs(), this.setLoadingState({
250
+ isValidating: !1,
251
+ isSubmitting: !1,
252
+ isNavigating: !1
253
+ });
254
+ }
255
+ getMachine() {
256
+ return this.machine;
257
+ }
258
+ async destroy() {
259
+ this.destroyed = !0, this.navigationPromise = null, this.navigationDirty = !1;
260
+ for (let e of this.subscribers.values()) e.clear();
261
+ await this.machine.destroy();
262
+ }
263
+ get isDestroyed() {
264
+ return this.destroyed || this.machine.isDestroyed;
265
+ }
266
+ async runReset(e) {
267
+ this.forceLoadingOff();
268
+ try {
269
+ this.machine.reset(e);
270
+ } finally {
271
+ this.forceLoadingOff();
272
+ }
273
+ }
274
+ async runCancel() {
275
+ this.discardLoadingRefs(), this.setLoadingState({ isNavigating: !0 });
276
+ try {
277
+ await this.machine.cancel();
278
+ } finally {
279
+ this.forceLoadingOff();
280
+ }
281
+ }
282
+ async runRestore(e) {
283
+ this.forceLoadingOff();
284
+ try {
285
+ this.machine.restore(e);
286
+ } finally {
287
+ this.forceLoadingOff();
288
+ }
289
+ }
290
+ getVisitedSteps() {
291
+ return this.machine.visited;
292
+ }
293
+ getStepHistory() {
294
+ return this.machine.history;
295
+ }
296
+ handleMachineStateChange(e) {
297
+ let t = this.lastState;
298
+ this.lastState = e, this.handleStateChange(e, t);
299
+ }
300
+ handleStateChange(e, t) {
301
+ if (this.lastState = e, this.destroyed) return;
302
+ let n = [];
303
+ if (e.data !== t.data && n.push("state", "navigation", "validation"), e.currentStepId !== t.currentStepId && n.push("state", "navigation"), e.isCompleted !== t.isCompleted && n.push("state"), (e.isValid !== t.isValid || e.validationErrors !== t.validationErrors) && n.push("validation"), e.stepStatuses !== t.stepStatuses && n.push("state", "navigation"), (e.canGoBack !== t.canGoBack || !this.stepIdsEqual(this.machine.history, this.navigationCache.stepHistory) || !this.stepIdsEqual(this.machine.visited, this.navigationCache.visitedSteps)) && n.push("navigation"), e.isLoadingStep !== t.isLoadingStep && (this.loadingCache = {
304
+ ...this.loadingCache,
305
+ isLoadingStep: e.isLoadingStep
306
+ }, n.push("loading")), this.machine.currentStep !== this.stateCache.currentStep && n.push("state"), n.length > 0) {
307
+ let e = [...new Set(n)];
308
+ this.notifySubscribers(e);
309
+ }
310
+ }
311
+ getInitialStepId() {
312
+ return this.initialStepId;
313
+ }
314
+ };
315
+ //#endregion
316
+ //#region src/wiring.ts
317
+ function r(t) {
318
+ let { definition: r, context: i, initialData: a, getCallbacks: o, plugins: s } = t, c = null, l = new e(r, i, a, {
319
+ onStateChange: (e) => {
320
+ c?.handleMachineStateChange(e), o().onStateChange?.(e);
321
+ },
322
+ onStepEnter: (e, t) => {
323
+ o().onStepEnter?.(e, t);
324
+ },
325
+ onStepLeave: (e, t) => {
326
+ o().onStepLeave?.(e, t);
327
+ },
328
+ onComplete: (e) => {
329
+ o().onComplete?.(e);
330
+ },
331
+ onCancel: async (e) => {
332
+ await o().onCancel?.(e);
333
+ },
334
+ onReset: () => {
335
+ o().onReset?.();
336
+ },
337
+ onError: (e) => {
338
+ o().onError?.(e);
339
+ },
340
+ onDataChange: (e, t, n) => {
341
+ o().onDataChange?.(e, t, n);
342
+ }
343
+ }, s), u = new n(l, r.initialStepId, { onError: (e) => {
344
+ let t = o().onError;
345
+ t ? t(e) : console.error(e);
346
+ } });
347
+ return c = u, {
348
+ machine: l,
349
+ manager: u
350
+ };
351
+ }
352
+ //#endregion
353
+ export { n as WizardStateManager, r as createMachineAndManager, t as createWizardActions };
@@ -0,0 +1,238 @@
1
+ import { StepId, WizardData, WizardMachine, WizardSerializedState, WizardState, WizardStepDefinition } from '@wizardkit/core';
2
+ import { LoadingState, NavigationState, StateSnapshot, SubscriptionChannel, SubscriptionListener, TrackedLoadingFlag, ValidationState, WizardStateManagerOptions } from './types';
3
+ /**
4
+ * Manages shared wizard state and subscriptions for granular hooks
5
+ * Supports channel-based subscriptions for fine-grained re-renders
6
+ * Works standalone or can be used with provider
7
+ *
8
+ * IMPORTANT: All snapshot getters return cached values for useSyncExternalStore stability.
9
+ * Caches are updated via handleStateChange() and setLoadingState().
10
+ */
11
+ export declare class WizardStateManager<T extends WizardData> {
12
+ private machine;
13
+ private subscribers;
14
+ private stateCache;
15
+ private navigationCache;
16
+ private validationCache;
17
+ private loadingCache;
18
+ private loadingCounts;
19
+ private loadingEpoch;
20
+ private snapshotCache;
21
+ private navigationPromise;
22
+ private navigationDirty;
23
+ private destroyed;
24
+ private navigationSeedStepId;
25
+ private initialStepId;
26
+ private options;
27
+ private lastState;
28
+ constructor(machine: WizardMachine<T>, initialStepId: StepId, options?: WizardStateManagerOptions);
29
+ /**
30
+ * Subscribe to state changes with optional channel filter
31
+ * @param listener Callback function to invoke on state change
32
+ * @param channel Optional channel to subscribe to (defaults to 'all')
33
+ * @returns Unsubscribe function
34
+ */
35
+ subscribe(listener: SubscriptionListener, channel?: SubscriptionChannel): () => void;
36
+ /**
37
+ * Notify subscribers of specific channels and update caches
38
+ * @param channels Array of channels that have changed
39
+ */
40
+ notifySubscribers(channels: SubscriptionChannel[]): void;
41
+ /**
42
+ * Update state cache from machine
43
+ */
44
+ private updateStateCache;
45
+ /**
46
+ * Update validation cache from machine
47
+ */
48
+ private updateValidationCache;
49
+ /**
50
+ * Update navigation cache with synchronous values only.
51
+ *
52
+ * When the current step differs from the step the cached values belong to,
53
+ * isLastStep/canGoNext are re-seeded from core's synchronous, conservative
54
+ * `progress.isLastStep` so they track the NEW step in the same notify
55
+ * (instead of carrying the previous step's values until the async
56
+ * recompute resolves). On the same step (data edits, validation, status
57
+ * changes) the previous values are kept and the async compute corrects
58
+ * them if needed — re-seeding there would flicker an async-proven
59
+ * `isLastStep: true` back to the conservative `false` on every edit.
60
+ * canGoPrevious/availableSteps always keep their last computed values.
61
+ */
62
+ private updateNavigationCacheSync;
63
+ /**
64
+ * Get current machine snapshot
65
+ */
66
+ getSnapshot(): WizardState<T>;
67
+ /**
68
+ * Get state snapshot for useWizardData hook
69
+ * Returns cached value for useSyncExternalStore stability
70
+ */
71
+ getStateSnapshot(): StateSnapshot<T>;
72
+ /**
73
+ * Get current step definition
74
+ */
75
+ getCurrentStep(): WizardStepDefinition<T>;
76
+ /**
77
+ * Get navigation snapshot for useSyncExternalStore
78
+ * Returns cached value - async computation updates cache in background
79
+ */
80
+ getNavigationSnapshot(): NavigationState;
81
+ /**
82
+ * Compute navigation state asynchronously and notify subscribers when ready
83
+ */
84
+ private computeNavigationStateAsync;
85
+ /**
86
+ * Route an error the manager caught itself to `options.onError`, falling
87
+ * back to console.error. Never throws: callers run inside a detached
88
+ * promise, where a throw would become an unhandled rejection.
89
+ */
90
+ private reportError;
91
+ /**
92
+ * Content equality for two navigation states. Arrays are compared by
93
+ * length + element (StepId is a string) — NOT by reference — because
94
+ * visitedSteps/stepHistory are freshly spread every compute, so a reference
95
+ * compare would always report "changed" and break useSyncExternalStore
96
+ * referential stability.
97
+ */
98
+ private navigationStateEqual;
99
+ /**
100
+ * Order-significant content equality for two StepId arrays.
101
+ */
102
+ private stepIdsEqual;
103
+ /**
104
+ * Notify only subscribers of a specific channel (without updating caches)
105
+ */
106
+ private notifySubscribersForChannel;
107
+ /**
108
+ * Get validation snapshot for useSyncExternalStore
109
+ * Returns cached value for stability
110
+ */
111
+ getValidationSnapshot(): ValidationState;
112
+ /**
113
+ * Get loading snapshot for useSyncExternalStore
114
+ * Returns cached value for stability
115
+ */
116
+ getLoadingSnapshot(): LoadingState;
117
+ /**
118
+ * Update the manager-owned loading flags and notify the loading channel.
119
+ * `isLoadingStep` is machine-owned (mirrored in handleStateChange) and is
120
+ * deliberately not accepted here.
121
+ */
122
+ setLoadingState(update: Partial<Pick<LoadingState, TrackedLoadingFlag>>): void;
123
+ /**
124
+ * Run `fn` while holding a reference on the `flag` loading flag.
125
+ *
126
+ * Reference-counted: the flag turns on when the first tracked call starts and
127
+ * off only when the last one settles (resolved OR rejected), so overlapping
128
+ * operations — or one that is rejected immediately, e.g. a double-clicked
129
+ * Next rejected as busy — never clear another operation's flag early. The
130
+ * "loading" channel is notified only when the boolean actually changes.
131
+ *
132
+ * The flag is set synchronously, before `fn` is invoked. `fn`'s result is
133
+ * returned and its rejection propagates unchanged.
134
+ *
135
+ * runReset()/runRestore()/runCancel() force every flag off and discard all
136
+ * outstanding references; operations in flight at that moment release
137
+ * nothing when they later settle. `isLoadingStep` is machine-owned and is
138
+ * not touched by these (the machine resets it itself).
139
+ */
140
+ trackLoading<R>(flag: TrackedLoadingFlag, fn: () => Promise<R>): Promise<R>;
141
+ /**
142
+ * Set a single loading flag, notifying "loading" only on an actual change.
143
+ */
144
+ private setLoadingFlag;
145
+ /**
146
+ * Drop every outstanding trackLoading() reference (zero the counters and
147
+ * start a new epoch). Does not touch the flags themselves.
148
+ */
149
+ private discardLoadingRefs;
150
+ /**
151
+ * Force every loading flag off (always notifies, as before) and discard all
152
+ * trackLoading() references so aborted in-flight operations cannot drive a
153
+ * counter negative or clear a newer operation's flag when they settle.
154
+ *
155
+ * `isLoadingStep` is machine-owned and is not touched here (the machine
156
+ * resets it itself).
157
+ */
158
+ private forceLoadingOff;
159
+ /**
160
+ * Get the underlying machine for direct access
161
+ */
162
+ getMachine(): WizardMachine<T>;
163
+ /**
164
+ * Tears down the wizard: delegates to the machine's destroy(), which runs
165
+ * every plugin's destroy() hook in reverse registration order. The machine
166
+ * isolates plugin-destroy rejections internally (routed to onError /
167
+ * console.error), so callers may fire-and-forget the returned promise.
168
+ */
169
+ destroy(): Promise<void>;
170
+ /**
171
+ * Whether the underlying machine has been destroyed (plugins torn down).
172
+ * Terminal. Used by React entry points to detect a manager killed by the
173
+ * StrictMode mount->unmount->remount probe so it can be recreated.
174
+ */
175
+ get isDestroyed(): boolean;
176
+ /**
177
+ * Reset the wizard to its initial state.
178
+ *
179
+ * Sets the loading flags + notifies "loading", calls the machine's
180
+ * synchronous reset(), then clears the loading flags + notifies "loading".
181
+ * (`isLoadingStep` is machine-owned and is not touched by this.)
182
+ *
183
+ * The state/navigation/validation channels are notified automatically via the
184
+ * machine's onStateChange auto-routing (handleStateChange), so this method
185
+ * must NOT notify them manually to avoid double-notify.
186
+ */
187
+ runReset(data?: T): Promise<void>;
188
+ /**
189
+ * Cancel the wizard.
190
+ *
191
+ * Sets isNavigating + notifies "loading", awaits the machine's cancel()
192
+ * (which always resets, then rejects if a cancel handler threw), then clears
193
+ * the loading flags + notifies "loading". Rejections from the machine
194
+ * propagate to the caller.
195
+ * (`isLoadingStep` is machine-owned and is not touched by this.)
196
+ *
197
+ * The state/navigation/validation channels are notified automatically via the
198
+ * machine's onStateChange auto-routing.
199
+ */
200
+ runCancel(): Promise<void>;
201
+ /**
202
+ * Restore the wizard from a serialized state.
203
+ *
204
+ * Sets the loading flags + notifies "loading", calls the machine's
205
+ * synchronous restore(), then clears the loading flags + notifies "loading".
206
+ * (`isLoadingStep` is machine-owned and is not touched by this.)
207
+ *
208
+ * The state/navigation/validation channels are notified automatically via the
209
+ * machine's onStateChange auto-routing (restore emits sync + async-validate
210
+ * onStateChange).
211
+ */
212
+ runRestore(serializedState: WizardSerializedState<T>): Promise<void>;
213
+ /**
214
+ * Get visited steps from machine
215
+ */
216
+ getVisitedSteps(): StepId[];
217
+ /**
218
+ * Get step history from machine
219
+ */
220
+ getStepHistory(): StepId[];
221
+ /**
222
+ * Entry point for the machine's `onStateChange` event: diffs `newState`
223
+ * against the last state this manager saw and routes the change to the
224
+ * affected channels. Bindings wire `events.onStateChange` straight to this
225
+ * (see createMachineAndManager) instead of tracking the previous state.
226
+ */
227
+ handleMachineStateChange(newState: WizardState<T>): void;
228
+ /**
229
+ * Handle state change from machine - determine affected channels
230
+ * @param newState New wizard state
231
+ * @param oldState Previous wizard state
232
+ */
233
+ handleStateChange(newState: WizardState<T>, oldState: WizardState<T>): void;
234
+ /**
235
+ * Get initial step ID
236
+ */
237
+ getInitialStepId(): StepId;
238
+ }
@@ -0,0 +1,68 @@
1
+ import { StepId, StepStatus, WizardData, WizardProgress, WizardStepDefinition } from '@wizardkit/core';
2
+ /**
3
+ * Subscription channels for fine-grained re-renders
4
+ */
5
+ export type SubscriptionChannel = "state" | "navigation" | "validation" | "loading" | "all";
6
+ /**
7
+ * Navigation state computed from wizard machine
8
+ */
9
+ export interface NavigationState {
10
+ canGoNext: boolean;
11
+ canGoPrevious: boolean;
12
+ canGoBack: boolean;
13
+ availableSteps: StepId[];
14
+ isFirstStep: boolean;
15
+ isLastStep: boolean;
16
+ visitedSteps: StepId[];
17
+ stepHistory: StepId[];
18
+ }
19
+ /**
20
+ * Validation state slice
21
+ */
22
+ export interface ValidationState {
23
+ isValid: boolean;
24
+ validationErrors?: Record<string, string>;
25
+ }
26
+ /**
27
+ * Loading flags. `isValidating` / `isSubmitting` / `isNavigating` are UI flags
28
+ * owned by the manager; `isLoadingStep` mirrors the machine.
29
+ */
30
+ export interface LoadingState {
31
+ isValidating: boolean;
32
+ isSubmitting: boolean;
33
+ isNavigating: boolean;
34
+ /**
35
+ * WIZ-013: a lazy step implementation is loading. Mirrors
36
+ * `machine.snapshot.isLoadingStep` (owned by the machine, not by
37
+ * `trackLoading()`).
38
+ */
39
+ isLoadingStep: boolean;
40
+ }
41
+ /** Loading flags owned by the manager's reference-counted `trackLoading()`. */
42
+ export type TrackedLoadingFlag = Exclude<keyof LoadingState, "isLoadingStep">;
43
+ /**
44
+ * State snapshot interface for wizard state
45
+ */
46
+ export interface StateSnapshot<T extends WizardData> {
47
+ currentStepId: StepId;
48
+ currentStep: WizardStepDefinition<T>;
49
+ data: T;
50
+ isCompleted: boolean;
51
+ stepStatuses: Record<StepId, StepStatus>;
52
+ progress: WizardProgress;
53
+ }
54
+ /**
55
+ * Listener type for subscription callbacks
56
+ */
57
+ export type SubscriptionListener = () => void;
58
+ /**
59
+ * Options for {@link WizardStateManager}.
60
+ */
61
+ export interface WizardStateManagerOptions {
62
+ /**
63
+ * Receives errors the manager catches itself — currently failures of the
64
+ * background navigation recompute (a throwing user guard / transition
65
+ * resolver). When omitted they are logged with `console.error`.
66
+ */
67
+ onError?: (error: Error) => void;
68
+ }
@@ -0,0 +1,40 @@
1
+ import { StepId, WizardContext, WizardData, WizardDefinition, WizardPlugin, WizardState, WizardMachine } from '@wizardkit/core';
2
+ import { WizardStateManager } from './manager';
3
+ /**
4
+ * The user-facing lifecycle callbacks a binding forwards to the machine.
5
+ */
6
+ export interface WizardCallbacks<T extends WizardData> {
7
+ onStateChange?: (state: WizardState<T>) => void;
8
+ onStepEnter?: (stepId: StepId, data: T) => void;
9
+ onStepLeave?: (stepId: StepId, data: T) => void;
10
+ onComplete?: (data: T) => void;
11
+ onCancel?: (data: T) => void | Promise<void>;
12
+ onReset?: () => void;
13
+ onError?: (error: Error) => void;
14
+ onDataChange?: (prevData: T, nextData: T, changedFields: (keyof T)[]) => void;
15
+ }
16
+ export interface CreateMachineAndManagerOptions<T extends WizardData> {
17
+ definition: WizardDefinition<T>;
18
+ context: WizardContext;
19
+ initialData: T;
20
+ /** Read at CALL time on every event, so React can pass a ref reader. */
21
+ getCallbacks: () => WizardCallbacks<T>;
22
+ plugins?: WizardPlugin<T>[];
23
+ }
24
+ /**
25
+ * Builds a WizardMachine + WizardStateManager pair with the machine's events
26
+ * wired into the manager's channel routing and forwarded to the user callbacks.
27
+ *
28
+ * - Every event reads `getCallbacks()` when it fires, so swapping the callbacks
29
+ * object (e.g. a React ref updated each render) takes effect immediately.
30
+ * - `onStateChange` first routes to `manager.handleMachineStateChange()`, then
31
+ * calls the user callback. Emissions fired synchronously from the machine
32
+ * constructor (before the manager exists) are not routed; the manager seeds
33
+ * its baseline from `machine.snapshot` itself.
34
+ * - Errors the manager catches (navigation recompute failures) go to
35
+ * `getCallbacks().onError`, or `console.error` when none is registered.
36
+ */
37
+ export declare function createMachineAndManager<T extends WizardData>(options: CreateMachineAndManagerOptions<T>): {
38
+ machine: WizardMachine<T>;
39
+ manager: WizardStateManager<T>;
40
+ };
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@wizardkit/state",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.13.1",
4
+ "description": "Framework-agnostic state manager for WizardKit, the headless multi-step form and wizard engine. Shared by the React, Vue, Svelte and Solid bindings; use it to build your own binding.",
5
+ "keywords": [
6
+ "wizard",
7
+ "multi-step-form",
8
+ "multistep",
9
+ "stepper",
10
+ "form-wizard",
11
+ "onboarding",
12
+ "state-machine",
13
+ "headless",
14
+ "typescript",
15
+ "state",
16
+ "state-management",
17
+ "framework-agnostic"
18
+ ],
19
+ "homepage": "https://wizardkit.dev",
20
+ "bugs": {
21
+ "url": "https://github.com/gooonzick/wizardkit/issues"
22
+ },
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md"
37
+ ],
38
+ "dependencies": {
39
+ "@wizardkit/core": "1.13.1"
40
+ },
41
+ "devDependencies": {
42
+ "@biomejs/biome": "^2.5.3",
43
+ "@types/node": "^26.1.1",
44
+ "@vitest/coverage-v8": "^4.1.10",
45
+ "typescript": "^6.0.3",
46
+ "vite": "^8.1.4",
47
+ "vite-plugin-dts": "^5.0.3",
48
+ "vitest": "^4.1.10"
49
+ },
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "https://github.com/gooonzick/wizardkit",
53
+ "directory": "packages/state"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "scripts": {
59
+ "build": "vite build",
60
+ "typecheck": "tsc --build --verbose",
61
+ "test": "vitest --run",
62
+ "test:watch": "vitest --watch",
63
+ "lint": "biome check .",
64
+ "lint:fix": "biome check . --write"
65
+ }
6
66
  }