@rxova/journey-core 0.6.4 → 1.0.0-rc.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/README.md +240 -93
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/journey-builder/index.d.cts +5 -0
- package/dist/journey-builder/index.d.ts +5 -0
- package/dist/journey-builder/types.d.cts +69 -0
- package/dist/journey-builder/types.d.ts +69 -0
- package/dist/journey-machine/async-state.d.cts +12 -0
- package/dist/journey-machine/async-state.d.ts +12 -0
- package/dist/journey-machine/computed.d.cts +2 -0
- package/dist/journey-machine/computed.d.ts +2 -0
- package/dist/journey-machine/controls.d.cts +17 -0
- package/dist/journey-machine/controls.d.ts +17 -0
- package/dist/journey-machine/helpers.d.cts +44 -0
- package/dist/journey-machine/helpers.d.ts +44 -0
- package/dist/journey-machine/index.d.cts +3 -0
- package/dist/journey-machine/index.d.ts +3 -0
- package/dist/journey-machine/navigation.d.cts +31 -0
- package/dist/journey-machine/navigation.d.ts +31 -0
- package/dist/journey-machine/plugin-controller.d.cts +15 -0
- package/dist/journey-machine/plugin-controller.d.ts +15 -0
- package/dist/journey-machine/resolve-journey-definition.d.cts +2 -0
- package/dist/journey-machine/resolve-journey-definition.d.ts +2 -0
- package/dist/journey-machine/runtime.d.cts +33 -0
- package/dist/journey-machine/runtime.d.ts +33 -0
- package/dist/journey-machine/send.d.cts +9 -0
- package/dist/journey-machine/send.d.ts +9 -0
- package/dist/plugins/analytics/index.cjs +2 -0
- package/dist/plugins/analytics/index.cjs.map +7 -0
- package/dist/plugins/analytics/index.d.cts +25 -0
- package/dist/plugins/analytics/index.d.ts +25 -0
- package/dist/plugins/analytics/index.js +2 -0
- package/dist/plugins/analytics/index.js.map +7 -0
- package/dist/plugins/autosave/index.cjs +2 -0
- package/dist/plugins/autosave/index.cjs.map +7 -0
- package/dist/plugins/autosave/index.d.cts +17 -0
- package/dist/plugins/autosave/index.d.ts +17 -0
- package/dist/plugins/autosave/index.js +2 -0
- package/dist/plugins/autosave/index.js.map +7 -0
- package/dist/plugins/diagnostics/diagnostics.d.cts +3 -0
- package/dist/plugins/diagnostics/diagnostics.d.ts +3 -0
- package/dist/plugins/diagnostics/index.cjs +2 -0
- package/dist/plugins/diagnostics/index.cjs.map +7 -0
- package/dist/plugins/diagnostics/index.d.cts +15 -0
- package/dist/plugins/diagnostics/index.d.ts +15 -0
- package/dist/plugins/diagnostics/index.js +2 -0
- package/dist/plugins/diagnostics/index.js.map +7 -0
- package/dist/plugins/execution-paths/execution-paths.d.cts +6 -0
- package/dist/plugins/execution-paths/execution-paths.d.ts +6 -0
- package/dist/plugins/execution-paths/index.cjs +2 -0
- package/dist/plugins/execution-paths/index.cjs.map +7 -0
- package/dist/plugins/execution-paths/index.d.cts +18 -0
- package/dist/plugins/execution-paths/index.d.ts +18 -0
- package/dist/plugins/execution-paths/index.js +2 -0
- package/dist/plugins/execution-paths/index.js.map +7 -0
- package/dist/plugins/persistence/controller.d.cts +17 -0
- package/dist/plugins/persistence/controller.d.ts +17 -0
- package/dist/plugins/persistence/index.cjs +2 -0
- package/dist/plugins/persistence/index.cjs.map +7 -0
- package/dist/plugins/persistence/index.d.cts +12 -0
- package/dist/plugins/persistence/index.d.ts +12 -0
- package/dist/plugins/persistence/index.js +2 -0
- package/dist/plugins/persistence/index.js.map +7 -0
- package/dist/plugins/replay/index.cjs +2 -0
- package/dist/plugins/replay/index.cjs.map +7 -0
- package/dist/plugins/replay/index.d.cts +27 -0
- package/dist/plugins/replay/index.d.ts +27 -0
- package/dist/plugins/replay/index.js +2 -0
- package/dist/plugins/replay/index.js.map +7 -0
- package/dist/types/analytics.types.d.cts +32 -0
- package/dist/types/analytics.types.d.ts +32 -0
- package/dist/types/autosave.types.d.cts +23 -0
- package/dist/types/autosave.types.d.ts +23 -0
- package/dist/types/diagnostics.types.d.cts +38 -0
- package/dist/types/diagnostics.types.d.ts +38 -0
- package/dist/types/index.d.cts +9 -0
- package/dist/types/index.d.ts +9 -4
- package/dist/types/journey.types.d.cts +190 -0
- package/dist/types/journey.types.d.ts +143 -150
- package/dist/types/machine.types.d.cts +102 -0
- package/dist/types/machine.types.d.ts +102 -0
- package/dist/types/observation.types.d.cts +75 -0
- package/dist/types/observation.types.d.ts +75 -0
- package/dist/types/persistence.types.d.cts +34 -0
- package/dist/types/persistence.types.d.ts +13 -20
- package/dist/types/replay.types.d.cts +35 -0
- package/dist/types/replay.types.d.ts +35 -0
- package/dist/types/transitions.types.d.cts +117 -0
- package/dist/types/transitions.types.d.ts +103 -47
- package/package.json +70 -4
- package/dist/machine-helpers.d.ts +0 -20
- package/dist/machine.d.ts +0 -13
- package/dist/persistence.d.ts +0 -17
- package/dist/transitions.d.ts +0 -27
- package/dist/types.d.ts +0 -1
package/README.md
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
# @rxova/journey-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed state machine for multi-step UI flows.
|
|
4
|
+
|
|
5
|
+
<p>
|
|
6
|
+
<a href="https://www.npmjs.com/package/@rxova/journey-core">
|
|
7
|
+
<img src="https://img.shields.io/npm/v/@rxova/journey-core?color=0f8f6a" alt="npm" />
|
|
8
|
+
</a>
|
|
9
|
+
<img src="https://img.shields.io/badge/5.4%20kB-brotli-0f8f6a" alt="size" />
|
|
10
|
+
<img src="https://img.shields.io/badge/zero%20dependencies-black" alt="zero deps" />
|
|
11
|
+
<img src="https://img.shields.io/badge/TypeScript-strict-3178C6?logo=typescript&logoColor=white" alt="TypeScript" />
|
|
12
|
+
</p>
|
|
13
|
+
|
|
14
|
+
`@rxova/journey-core` is approaching a `1.0.0-rc` contract freeze. The current public model is:
|
|
15
|
+
|
|
16
|
+
- JSON-only runtime `context`
|
|
17
|
+
- static step `meta`
|
|
18
|
+
- transition-side state updates through `updateContext(...)`
|
|
19
|
+
- documented lifecycle callbacks and events as the supported extension surface
|
|
4
20
|
|
|
5
21
|
## Install
|
|
6
22
|
|
|
@@ -8,128 +24,259 @@ Headless runtime for non-linear journeys.
|
|
|
8
24
|
npm i @rxova/journey-core
|
|
9
25
|
```
|
|
10
26
|
|
|
11
|
-
## What You Get
|
|
12
|
-
|
|
13
|
-
- Deterministic transition matching (first match wins).
|
|
14
|
-
- Timeline + pointer navigation model (`history.timeline` + `history.index`).
|
|
15
|
-
- Built-in navigation and terminal events:
|
|
16
|
-
`goToNextStep()`, `goToPreviousStep()`, `goToLastVisitedStep()`, `completeJourney()`, `terminateJourney()`.
|
|
17
|
-
- Async guard/effect lifecycle state in `snapshot.async`.
|
|
18
|
-
- Typed observability stream via `subscribeEvent`.
|
|
19
|
-
- Step metadata updates via `updateStepMetadata`.
|
|
20
|
-
- Optional persistence with schema versioning and migration hooks.
|
|
21
|
-
|
|
22
27
|
## Quickstart
|
|
23
28
|
|
|
24
29
|
```ts
|
|
25
30
|
import { createJourneyMachine } from "@rxova/journey-core";
|
|
26
31
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
32
|
+
const machine = createJourneyMachine({
|
|
33
|
+
initial: "account",
|
|
34
|
+
context: { name: "" },
|
|
35
|
+
steps: { account: {}, details: {}, review: {} },
|
|
36
|
+
transitions: ["account", "details", "review"]
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
machine.start();
|
|
40
|
+
|
|
41
|
+
await machine.send({ type: "goToNextStep" }); // account → details
|
|
42
|
+
await machine.send({ type: "goToNextStep" }); // details → review
|
|
43
|
+
await machine.goToPreviousStep(); // review → details
|
|
44
|
+
|
|
45
|
+
const snap = machine.getSnapshot();
|
|
46
|
+
console.log(snap.currentStepId); // "details"
|
|
47
|
+
console.log(snap.history.timeline); // ["account", "details"]
|
|
48
|
+
console.log(snap.status); // "running"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Three Transition Modes
|
|
52
|
+
|
|
53
|
+
Reserved step ids: `*`, `global`, `COMPLETE`, and `TERMINATED`. They are used by the runtime and cannot be used as real step names.
|
|
54
|
+
|
|
55
|
+
### Linear
|
|
56
|
+
|
|
57
|
+
Array shorthand for sequential flows. Steps can carry synchronous `updateContext` transitions and timeouts.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
transitions: [
|
|
61
|
+
"account",
|
|
62
|
+
{
|
|
63
|
+
step: "details",
|
|
64
|
+
updateContext: ({ context }) => ({ ...context, step: 2 }),
|
|
65
|
+
timeoutMs: 5000
|
|
66
|
+
},
|
|
67
|
+
"payment",
|
|
68
|
+
"review"
|
|
69
|
+
];
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Graph
|
|
73
|
+
|
|
74
|
+
Step-keyed transitions with guards, `updateContext`, and branching.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
transitions: {
|
|
78
|
+
login: {
|
|
79
|
+
goToNextStep: [
|
|
80
|
+
{ to: "admin", when: ({ context }) => context.role === "admin" },
|
|
81
|
+
{ to: "dashboard" }
|
|
82
|
+
]
|
|
83
|
+
},
|
|
84
|
+
admin: { completeJourney: true },
|
|
85
|
+
dashboard: { completeJourney: true },
|
|
86
|
+
global: { terminateJourney: true }
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
#### Graph Builder
|
|
91
|
+
|
|
92
|
+
For larger flows, `createJourneyBuilder` lets each step declare its own transitions co-located with its component. It compiles to the same `JourneyDefinition` — no new runtime concepts.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
// builder.ts — typed singleton
|
|
96
|
+
const { createStep, to, build } = createJourneyBuilder<Context, StepId, EventMap>();
|
|
97
|
+
|
|
98
|
+
// steps/login.step.ts — co-located with Login.tsx
|
|
99
|
+
export const loginStep = createStep("login", {
|
|
100
|
+
on: {
|
|
101
|
+
submit: [to("admin").when(({ context }) => context.role === "admin"), to("dashboard")]
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// journey.ts — one-screen assembly
|
|
106
|
+
const definition = build({
|
|
107
|
+
initial: "login",
|
|
108
|
+
context: { role: "user" },
|
|
109
|
+
steps: [loginStep, adminStep, dashboardStep],
|
|
110
|
+
global: { completeJourney: true, terminateJourney: true }
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Use the **factory form** when you need `event.payload` narrowed to the specific event type:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
submit: ({ to }) => [to("admin").when(({ context, event }) => event.payload?.username !== "")];
|
|
118
|
+
```
|
|
30
119
|
|
|
31
|
-
|
|
120
|
+
### Headless
|
|
121
|
+
|
|
122
|
+
Omit `transitions` entirely. The machine holds state, history, and context, but the caller decides where to go. Useful for custom renderers, server-driven flows, or when the navigation logic lives outside the definition.
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
const machine = createJourneyMachine({
|
|
32
126
|
initial: "start",
|
|
33
|
-
context: {
|
|
127
|
+
context: {},
|
|
128
|
+
steps: { start: {}, configure: {}, confirm: {} }
|
|
129
|
+
// no transitions — the caller drives the flow
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
machine.start();
|
|
133
|
+
await machine.goToStepById("configure");
|
|
134
|
+
await machine.goToStepById("confirm");
|
|
135
|
+
await machine.goToPreviousStep(); // back to configure
|
|
136
|
+
await machine.completeJourney();
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
In headless mode, `goToStepById(...)` is the navigation primitive. `goToNextStep()` and custom events are explicit no-ops until you define transitions and move into linear or graph mode.
|
|
140
|
+
|
|
141
|
+
After `dispose()`, send-style APIs resolve with `transitioned: false` and `error: JourneyDisposedError`. Control APIs such as `start()` and `updateContext()` stay no-op and emit a development warning.
|
|
142
|
+
|
|
143
|
+
`updateContext()` is the ordered context-write API. It runs through the same queue as `send()`, so it applies against the latest committed snapshot when it executes.
|
|
144
|
+
|
|
145
|
+
## Step Lifecycle
|
|
146
|
+
|
|
147
|
+
Run side effects when a step is entered or left by attaching `onEnter` / `onLeave` directly to the step definition. Both callbacks receive the current `context` and are observational. They do not change transition selection or mutate context. Use transition `updateContext` for synchronous state commits that belong to the transition itself.
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
const machine = createJourneyMachine({
|
|
151
|
+
context: { username: "" },
|
|
34
152
|
steps: {
|
|
35
|
-
|
|
36
|
-
|
|
153
|
+
login: {
|
|
154
|
+
onLeave: ({ context }) => analytics.track("login_left", { user: context.username })
|
|
155
|
+
},
|
|
156
|
+
dashboard: {
|
|
157
|
+
onEnter: ({ context }) => analytics.track("dashboard_entered"),
|
|
158
|
+
onLeave: ({ context }) => console.log("leaving dashboard")
|
|
159
|
+
}
|
|
37
160
|
},
|
|
38
|
-
transitions: [
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
]
|
|
42
|
-
};
|
|
161
|
+
transitions: ["login", "dashboard"]
|
|
162
|
+
});
|
|
163
|
+
```
|
|
43
164
|
|
|
44
|
-
|
|
45
|
-
await machine.goToNextStep();
|
|
46
|
-
await machine.goToPreviousStep();
|
|
47
|
-
await machine.completeJourney();
|
|
165
|
+
With the graph builder, callbacks sit alongside transitions on the step:
|
|
48
166
|
|
|
49
|
-
|
|
50
|
-
|
|
167
|
+
```ts
|
|
168
|
+
const dashboardStep = createStep("dashboard", {
|
|
169
|
+
onEnter: ({ context }) => analytics.track("dashboard_entered"),
|
|
170
|
+
onLeave: ({ context }) => console.log("leaving dashboard"),
|
|
171
|
+
on: { submit: [to("review")] }
|
|
172
|
+
});
|
|
51
173
|
```
|
|
52
174
|
|
|
53
|
-
|
|
175
|
+
In React, use `useJourneyStepLifecycle` when the callback needs access to component state or React context:
|
|
54
176
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
- Once status is `complete` or `terminated`, pointer navigation and transitions no-op until `resetMachine()`.
|
|
58
|
-
- Forward navigation after moving back truncates timeline tail before appending the next step.
|
|
59
|
-
- Snapshot shape is stable: `currentStepId === history.timeline[history.index]`.
|
|
177
|
+
```tsx
|
|
178
|
+
const { useJourneyStepLifecycle } = createJourney(definition);
|
|
60
179
|
|
|
61
|
-
|
|
180
|
+
function Dashboard() {
|
|
181
|
+
useJourneyStepLifecycle("dashboard", {
|
|
182
|
+
onEnter: ({ context }) => analytics.track("dashboard_entered"),
|
|
183
|
+
onLeave: ({ context }) => console.log("leaving dashboard")
|
|
184
|
+
});
|
|
185
|
+
// ...
|
|
186
|
+
}
|
|
187
|
+
```
|
|
62
188
|
|
|
63
|
-
|
|
189
|
+
The hook always calls the latest version of your callbacks without re-subscribing.
|
|
64
190
|
|
|
65
|
-
|
|
66
|
-
- `running-effect`: async effect in progress
|
|
67
|
-
- `error`: guard/effect rejected
|
|
68
|
-
- `idle`: no active async work
|
|
191
|
+
## Features
|
|
69
192
|
|
|
70
|
-
`
|
|
193
|
+
- **Async guards** — `when` can be async, with per-transition `timeoutMs` and `AbortSignal`-based cancellation. Step async state is tracked in `snapshot.async.byStep[stepId]` (`idle`, `evaluating-when`, `error`)
|
|
194
|
+
- **Timeline history** — `goToPreviousStep()`, `goToLastVisitedStep()`, deterministic back/forward. Snapshot exposes `history.timeline` and `history.index` so you always know where the user has been
|
|
195
|
+
- **Computed state** — `getComputed()` returns derived flags: `isFirstStep`, `isLastStep`, `isLoading`, `isComplete`, `isTerminated`, `activeStepIndex`, `stepCount`, `mode` (`linear` | `graph` | `headless`)
|
|
196
|
+
- **Observability** — `subscribeEvent()` streams typed lifecycle events: `journey.start`, `transition.start`, `transition.success`, `step.enter`, `step.exit`, `journey.completed`, `journey.terminated`, and more
|
|
197
|
+
- **Step metadata** — attach typed metadata per step and read it with `getStepMeta(stepId)`. Metadata is definition data, not mutable runtime state
|
|
198
|
+
- **Terminal events** — `completeJourney()` and `terminateJourney()` with typed payloads. Once terminal, all navigation no-ops until `resetJourney()`
|
|
199
|
+
- **Snapshot** — one object holds everything that changes at runtime: `currentStepId`, `context`, `history`, `visited`, `status` (`idled`, `running`, `completed`, `terminated`), and `async`
|
|
200
|
+
- **Global transitions** — cross-cutting handlers via the `global` key, useful for close-confirmation or abort flows
|
|
71
201
|
|
|
72
202
|
## Persistence
|
|
73
203
|
|
|
74
|
-
|
|
204
|
+
```ts
|
|
205
|
+
import { createPersistencePlugin } from "@rxova/journey-core/persistence";
|
|
206
|
+
|
|
207
|
+
const machine = createJourneyMachine(definition, {
|
|
208
|
+
plugins: [
|
|
209
|
+
createPersistencePlugin({
|
|
210
|
+
key: "checkout",
|
|
211
|
+
version: 2,
|
|
212
|
+
blockList: ["payment.cardNumber"]
|
|
213
|
+
})
|
|
214
|
+
]
|
|
215
|
+
});
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
Versioned snapshot storage with migrations, context allow/block lists, and configurable reset behavior. Defaults to `localStorage` when available.
|
|
219
|
+
|
|
220
|
+
If `migrate(...)` returns data that no longer matches a valid snapshot, Journey reports the error through `onError` (or a development warning when `onError` is omitted) and falls back to the initial snapshot.
|
|
221
|
+
|
|
222
|
+
## Autosave
|
|
75
223
|
|
|
76
224
|
```ts
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
context: { name: "" },
|
|
88
|
-
status: "running",
|
|
89
|
-
visited: { start: true, review: false },
|
|
90
|
-
stepMeta: { start: undefined, review: undefined }
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
return legacySnapshot as never;
|
|
94
|
-
},
|
|
95
|
-
onError: (error) => {
|
|
96
|
-
console.error("Persistence error", error);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
225
|
+
import { createAutosavePlugin } from "@rxova/journey-core/autosave";
|
|
226
|
+
|
|
227
|
+
const machine = createJourneyMachine(definition, {
|
|
228
|
+
plugins: [
|
|
229
|
+
createAutosavePlugin({
|
|
230
|
+
key: "checkout-draft",
|
|
231
|
+
debounceMs: 300,
|
|
232
|
+
allowList: ["profile", "shipping"]
|
|
233
|
+
})
|
|
234
|
+
]
|
|
99
235
|
});
|
|
236
|
+
|
|
237
|
+
await machine.flushAutosave();
|
|
100
238
|
```
|
|
101
239
|
|
|
102
|
-
|
|
240
|
+
Autosave adds debounced draft persistence, hydration, `getAutosaveState()`, `flushAutosave()`, and `clearAutosave()` without requiring the persistence plugin as a separate public dependency.
|
|
103
241
|
|
|
104
|
-
##
|
|
242
|
+
## Analytics
|
|
105
243
|
|
|
106
|
-
|
|
244
|
+
```ts
|
|
245
|
+
import { createAnalyticsPlugin } from "@rxova/journey-core/analytics";
|
|
246
|
+
|
|
247
|
+
const machine = createJourneyMachine(definition, {
|
|
248
|
+
plugins: [
|
|
249
|
+
createAnalyticsPlugin({
|
|
250
|
+
machineId: "checkout",
|
|
251
|
+
track: (event) => analytics.track(event.name, event.payload)
|
|
252
|
+
})
|
|
253
|
+
]
|
|
254
|
+
});
|
|
255
|
+
```
|
|
107
256
|
|
|
108
|
-
|
|
109
|
-
- `transition.success`
|
|
110
|
-
- `transition.error`
|
|
111
|
-
- `step.exit`
|
|
112
|
-
- `step.enter`
|
|
113
|
-
- `navigation.previous`
|
|
114
|
-
- `navigation.lastVisited`
|
|
115
|
-
- `journey.complete`
|
|
116
|
-
- `journey.close`
|
|
117
|
-
- `metadata.updated`
|
|
257
|
+
Analytics normalizes Journey lifecycle events into a stable event envelope and adds `trackAnalyticsEvent(...)` for custom markers.
|
|
118
258
|
|
|
119
|
-
##
|
|
259
|
+
## DevTools
|
|
120
260
|
|
|
121
261
|
```ts
|
|
122
|
-
import {
|
|
123
|
-
|
|
124
|
-
const
|
|
125
|
-
tx.from("start").on("goToNextStep").to("review"),
|
|
126
|
-
tx
|
|
127
|
-
.from("review")
|
|
128
|
-
.on("goToNextStep")
|
|
129
|
-
.choose(
|
|
130
|
-
tx.when(({ context }) => context.canSubmit).to("done", { id: "review-submit" }),
|
|
131
|
-
tx.otherwise().to("review", { id: "review-stay" })
|
|
132
|
-
),
|
|
133
|
-
tx.from("review").toComplete()
|
|
134
|
-
);
|
|
262
|
+
import { attachJourneyDevtools } from "@rxova/journey-devtools-bridge";
|
|
263
|
+
|
|
264
|
+
const detach = attachJourneyDevtools(machine, { label: "Checkout" });
|
|
135
265
|
```
|
|
266
|
+
|
|
267
|
+
## Documentation
|
|
268
|
+
|
|
269
|
+
- [Pre-1.0 Migration](https://rxova.org/docs/core/pre-1-0-migration)
|
|
270
|
+
- [Stability Contract](https://rxova.org/docs/core/stability)
|
|
271
|
+
- [Quickstart](https://rxova.org/docs/core/getting-started)
|
|
272
|
+
- [Usage Modes](https://rxova.org/docs/core/usage)
|
|
273
|
+
- [Async Lifecycle](https://rxova.org/docs/core/async)
|
|
274
|
+
- [Persistence](https://rxova.org/docs/core/persistence)
|
|
275
|
+
- [Autosave](https://rxova.org/docs/core/autosave)
|
|
276
|
+
- [Analytics Plugin](https://rxova.org/docs/core/plugins/analytics-plugin)
|
|
277
|
+
- [Plugins](https://rxova.org/docs/core/plugins/overview)
|
|
278
|
+
- [API Reference](https://rxova.org/docs/core/api/overview)
|
|
279
|
+
|
|
280
|
+
## License
|
|
281
|
+
|
|
282
|
+
MIT
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var z=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var Te=Object.prototype.hasOwnProperty;var ye=(e,n)=>{for(var a in n)z(e,a,{get:n[a],enumerable:!0})},de=(e,n,a,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ie(n))!Te.call(e,o)&&o!==a&&z(e,o,{get:()=>n[o],enumerable:!(i=se(n,o))||i.enumerable});return e};var ue=e=>de(z({},"__esModule",{value:!0}),e);var xe={};ye(xe,{JOURNEY_ASYNC_PHASE:()=>h,JOURNEY_EVENT:()=>w,JOURNEY_STATUS:()=>I,JOURNEY_WILDCARD:()=>N,createJourneyMachine:()=>oe,createPersistenceController:()=>V,createTransitions:()=>pe,tx:()=>ae});module.exports=ue(xe);var I={RUNNING:"running",COMPLETE:"complete",TERMINATED:"terminated"},N="*",w={GO_TO_STEP_BY_ID:"goToStepById"},h={IDLE:"idle",EVALUATING_WHEN:"evaluating-when",RUNNING_EFFECT:"running-effect",ERROR:"error"};var B=(e,n,a)=>{if(!(n in e))throw new Error(a)},K=e=>typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.trunc(e)),l=()=>Date.now(),Se=e=>[...new Set(e)],ce=(e,n)=>Object.fromEntries(n.map(a=>[a,e[a]===!0])),L=(e,n)=>{let a=n??Se(e),i=Object.fromEntries(a.map(o=>[o,!1]));for(let o of e)i[o]=!0;return i},le=(e,n)=>({...e,[n]:!0}),j=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function",F=()=>({phase:h.IDLE,eventType:null,transitionId:null,error:null}),G=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(a=>[a,F()]))}),X=e=>e.type===w.GO_TO_STEP_BY_ID&&"stepId"in e,q=e=>e==="COMPLETE"||e==="TERMINATED",Z=(e,n)=>{let a=n;for(let[i,o]of e.entries()){if(!o||typeof o!="object")throw new Error(`Journey transition at index ${i} must be an object.`);if(typeof o.from!="string"||typeof o.event!="string")throw new Error(`Journey transition at index ${i} must define string "from" and "event".`);if(o.from!==N&&!(o.from in a))throw new Error(`Journey transition at index ${i} references unknown from step "${o.from}".`);if(o.event==="completeJourney"||o.event==="terminateJourney"){if("to"in o&&o.to!==void 0)throw new Error(`Journey transition at index ${i} with event "${o.event}" cannot define "to".`);continue}if(typeof o.to!="string")throw new Error(`Journey transition at index ${i} with event "${o.event}" must define string "to".`);if(!q(o.to)&&!(o.to in a))throw new Error(`Journey transition at index ${i} points to unknown step "${o.to}".`)}},M=(e,n,a)=>a?{transitioned:n,transitionId:a,snapshot:e}:{transitioned:n,snapshot:e},_=(e,n,a,i,o,S,u)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let t=Math.max(0,Math.min(Math.trunc(n),e.length-1)),J=e[t],x=Object.keys(S);return{status:i,currentStepId:J,history:{timeline:[...e],index:t},context:a,visited:u?ce(u,x):L(e,x),stepMeta:{...S},async:o}},ee=async(e,n,a,i)=>{for(let o of e){let S=o.from===N||o.from===n.currentStepId,u=o.event===a.type;if(!S||!u)continue;if(!o.when)return o;let t=o.when({context:n.context,from:n.currentStepId,timeline:n.history.timeline,index:n.history.index,event:a}),J=j(t);J&&i?.onAsyncGuardStart?.(o);let x;try{x=await t}catch(f){throw J&&i?.onAsyncGuardError?.(o,f),f}if(J&&i?.onAsyncGuardSuccess?.(o),x)return o}return null},Q=(e,n,a)=>{let i=e.history.timeline.slice(0,e.history.index+1),o=i;n!==e.currentStepId&&(o=[...i,n]);let S=o.length-1,u=le(e.visited,n);return _(o,S,a,e.status,e.async,e.stepMeta,u)};var Y=e=>typeof e=="object"&&e!==null,te=e=>e===I.RUNNING||e===I.COMPLETE||e===I.TERMINATED,Ee=()=>{let e=globalThis.localStorage;return!e||typeof e.getItem!="function"||typeof e.setItem!="function"||typeof e.removeItem!="function"?null:e},Je=e=>{if(!e)return null;let n=e.storage??Ee();return n?{key:e.key,storage:n,version:e.version??1,clearOnReset:e.clearOnReset??!0,serialize:e.serialize??JSON.stringify,deserialize:e.deserialize??JSON.parse,...e.migrate?{migrate:e.migrate}:{},...e.onError?{onError:e.onError}:{}}:null},ne=(e,n,a,i)=>{if(!Y(e))return null;let o=!1,S=Y(e.history)?e.history:null;S||(o=!0);let u=S?.timeline??e.timeline,t=Array.isArray(u)?u.filter(E=>typeof E=="string"&&E in n):[],J=typeof e.currentStepId=="string"&&e.currentStepId in n?e.currentStepId:typeof e.current=="string"&&e.current in n?e.current:null;if(t.length===0){if(!J)return null;t.push(J),o=!0}let x=t.length-1,f=S?.index??e.index;if(typeof f=="number"&&Number.isFinite(f))x=Math.max(0,Math.min(Math.trunc(f),t.length-1)),x!==f&&(o=!0);else if(J){let E=t.lastIndexOf(J);E>=0&&(x=E,o=!0)}let d=te(e.status)?e.status:I.RUNNING;te(e.status)||(o=!0);let s=Object.keys(n),m=e.visited,D=Y(m)?Object.fromEntries(s.map(E=>[E,m[E]===!0])):null,v=Array.isArray(m)?L(m.filter(E=>typeof E=="string"&&E in n),s):null,C=L(t,s);if(D){let E=m;C=D,s.some(g=>typeof E[g]!="boolean")&&(o=!0)}else v&&(C=v),o=!0;let P=Y(e.stepMeta)?e.stepMeta:null;P||(o=!0);let R=Object.fromEntries(Object.keys(n).map(E=>{let k=E,g=P?P[E]:void 0;return g===void 0?[k,i[k]]:[k,g]}));return{snapshot:{currentStepId:t[x],history:{timeline:t,index:x},context:"context"in e?e.context:a,status:d,visited:C,stepMeta:R},needsRewrite:o}},V=e=>{let{initial:n,context:a,stepMeta:i,steps:o,options:S}=e,u=Je(S?.persistence),t=d=>{u?.onError?.(d)},J=d=>{if(u)try{let s={version:u.version,snapshot:{currentStepId:d.currentStepId,history:{timeline:[...d.history.timeline],index:d.history.index},context:d.context,status:d.status,visited:{...d.visited},stepMeta:{...d.stepMeta}}};u.storage.setItem(u.key,u.serialize(s))}catch(s){t(s)}},x=()=>{if(u)try{u.storage.removeItem(u.key)}catch(d){t(d)}},f=()=>{let d=_([n],0,a,I.RUNNING,G(o),i);if(!u)return d;try{let s=u.storage.getItem(u.key);if(!s)return d;let m=u.deserialize(s);if(!Y(m))return d;let D=m.version;if(typeof D!="number")return d;let v=null,C=!1;if(D===u.version){let R=ne(m.snapshot,o,a,i);v=R?.snapshot??null,C=!!R?.needsRewrite}else if(u.migrate){let R=u.migrate(m.snapshot,D);v=ne(R,o,a,i)?.snapshot??null,C=v!==null}if(!v)return d;let P=_(v.history.timeline,v.history.index,v.context,v.status,G(o),v.stepMeta,v.visited);return C&&J(P),P}catch(s){return t(s),d}};return{clearOnReset:u?.clearOnReset??!0,hydrateSnapshot:f,persistSnapshot:J,removePersistedSnapshot:x}};function oe(e,n){if(!e.steps||typeof e.steps!="object")throw new Error("Journey steps must be a record object.");if(!Array.isArray(e.transitions))throw new Error("Journey transitions must be an array.");B(e.steps,e.initial,`Journey initial step "${e.initial}" does not exist in steps registry.`),Z(e.transitions,e.steps);let a=()=>{let r={};for(let p of Object.keys(e.steps))r[p]=e.steps[p].meta;return r},{clearOnReset:i,hydrateSnapshot:o,persistSnapshot:S,removePersistedSnapshot:u}=V({initial:e.initial,context:e.context,stepMeta:a(),steps:e.steps,...n?{options:n}:{}}),t=o();t={...t,async:G(e.steps)};let J=new Set,x=new Set,f=Promise.resolve(),d=()=>{for(let r of J)r()},s=r=>{for(let p of x)p(r)},m=r=>{let p=f.then(r,r);return f=p.then(()=>{},()=>{}),p},D=r=>r===h.EVALUATING_WHEN||r===h.RUNNING_EFFECT,v=(r,p)=>{let T=t.async.byStep[r]??F(),y=p(T);if(T.phase===y.phase&&T.eventType===y.eventType&&T.transitionId===y.transitionId&&T.error===y.error)return;let A={...t.async.byStep,[r]:y},b=Object.values(A).some(U=>D(U.phase));t={...t,async:{isLoading:b,byStep:A}},d()},C=(r,p,T,y)=>{v(r,()=>({phase:p,eventType:T,transitionId:y??null,error:null}))},P=r=>{v(r,()=>F())},R=(r,p,T,y)=>{v(r,()=>({phase:h.ERROR,eventType:p,transitionId:y??null,error:T}))},E=(r,p)=>{if(t.status!==I.RUNNING)return M(t,!1);let T=K(r);if(t.history.index===0)return M(t,!1);let y=t.currentStepId,A=Math.max(0,t.history.index-T),b=t.history.index-A;return b<=0?M(t,!1):(s({type:"step.exit",stepId:y,timestamp:l()}),t=_(t.history.timeline,A,t.context,t.status,t.async,t.stepMeta,t.visited),S(t),d(),s({type:"navigation.previous",from:y,to:t.currentStepId,requestedSteps:T,appliedSteps:b,timestamp:l()}),s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,p))},k=r=>{if(t.status!==I.RUNNING)return M(t,!1);let p=t.history.timeline.length-1;if(t.history.index>=p)return M(t,!1);let T=t.currentStepId;return s({type:"step.exit",stepId:T,timestamp:l()}),t=_(t.history.timeline,p,t.context,t.status,t.async,t.stepMeta,t.visited),S(t),d(),s({type:"navigation.lastVisited",from:T,to:t.currentStepId,timestamp:l()}),s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,r)},g={getSnapshot:()=>t,subscribe:r=>(J.add(r),()=>{J.delete(r)}),subscribeEvent:r=>(x.add(r),()=>{x.delete(r)}),resetMachine:()=>(t=_([e.initial],0,e.context,I.RUNNING,G(e.steps),a()),i?u():S(t),d(),t),updateContext:r=>(t={...t,context:r(t.context)},S(t),d(),t),updateStepMetadata:(r,p)=>{if(!(r in e.steps))return t;let T=t.stepMeta[r],y=p(T);return Object.is(T,y)||(t={...t,stepMeta:{...t.stepMeta,[r]:y}},S(t),d(),s({type:"metadata.updated",stepId:r,previous:T,next:y,timestamp:l()})),t},clearStepError:r=>{let p=r??t.currentStepId;return p in e.steps&&P(p),t},goToPreviousStep:r=>m(async()=>E(r,"goToPreviousStep")),goToLastVisitedStep:()=>m(async()=>k("goToLastVisitedStep")),goToNextStep:()=>g.send({type:"goToNextStep"}),terminateJourney:r=>r===void 0?g.send({type:"terminateJourney"}):g.send({type:"terminateJourney",payload:r}),completeJourney:r=>r===void 0?g.send({type:"completeJourney"}):g.send({type:"completeJourney",payload:r}),send:r=>m(async()=>{if(t.status!==I.RUNNING)return M(t,!1);let p=t.currentStepId;if(X(r)){B(e.steps,r.stepId,`Cannot goToStepById unknown step "${r.stepId}".`),s({type:"transition.start",from:p,event:r,timestamp:l()}),P(p);let c=t.currentStepId,O=Q(t,r.stepId,t.context);return O.currentStepId!==c&&s({type:"step.exit",stepId:c,timestamp:l()}),t=O,S(t),d(),s({type:"transition.success",from:p,to:t.currentStepId,eventType:w.GO_TO_STEP_BY_ID,transitionId:w.GO_TO_STEP_BY_ID,timestamp:l()}),O.currentStepId!==c&&s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,w.GO_TO_STEP_BY_ID)}let T=r;s({type:"transition.start",from:p,event:r,timestamp:l()});let y;try{y=await ee(e.transitions,t,T,{onAsyncGuardStart:c=>{C(p,h.EVALUATING_WHEN,T.type,c.id)},onAsyncGuardSuccess:()=>{P(p)},onAsyncGuardError:(c,O)=>{R(p,T.type,O,c.id)}})}catch(c){throw R(p,T.type,c),s({type:"transition.error",from:p,eventType:T.type,transitionId:null,error:c,timestamp:l()}),c}if(!y){if(r.type==="goToPreviousStep"||r.type==="back"){let c=E(1,r.type);return c.transitioned&&s({type:"transition.success",from:p,to:c.snapshot.currentStepId,eventType:r.type,transitionId:null,timestamp:l()}),c}return M(t,!1)}let A=t.context;if(y.effect){let c=y.effect({context:t.context,from:t.currentStepId,timeline:t.history.timeline,index:t.history.index,event:T});j(c)&&C(p,h.RUNNING_EFFECT,T.type,y.id);let O;try{O=await c}catch(W){throw R(p,T.type,W,y.id),s({type:"transition.error",from:p,eventType:T.type,transitionId:y.id??null,error:W,timestamp:l()}),W}O!==void 0&&(A=O)}P(p);let b=y.event==="completeJourney"?"COMPLETE":y.event==="terminateJourney"?"TERMINATED":y.to;if(q(b)){let c=t.history.timeline.slice(0,t.history.index+1);return t={...t,history:{timeline:c,index:c.length-1},context:A,status:b==="COMPLETE"?I.COMPLETE:I.TERMINATED},S(t),d(),s({type:"transition.success",from:p,to:b,eventType:T.type,transitionId:y.id??null,timestamp:l()}),s({type:b==="COMPLETE"?"journey.complete":"journey.close",stepId:t.currentStepId,timestamp:l()}),M(t,!0,y.id)}let U=b;B(e.steps,U,`Transition points to unknown step "${U}".`);let H=t.currentStepId;return H!==U&&s({type:"step.exit",stepId:H,timestamp:l()}),t=Q(t,U,A),S(t),d(),s({type:"transition.success",from:p,to:t.currentStepId,eventType:T.type,transitionId:y.id??null,timestamp:l()}),H!==t.currentStepId&&s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,y.id)})};return g}var re=(e,n)=>n==="completeJourney"?{complete:(a={})=>({...a,from:e,event:n})}:n==="terminateJourney"?{terminate:(a={})=>({...a,from:e,event:n})}:{to:(a,i={})=>({...i,from:e,event:n,to:a}),choose:(...a)=>a.map(i=>({...i,from:e,event:n}))},$=(e,n,a={})=>({...a,from:e,event:n}),ae={from:e=>({on:n=>re(e,n),toComplete:(n={})=>$(e,"completeJourney",n),toTerminate:(n={})=>$(e,"terminateJourney",n)}),any:()=>({on:e=>re(N,e),toComplete:(e={})=>$(N,"completeJourney",e),toTerminate:(e={})=>$(N,"terminateJourney",e)}),when:e=>({to:(n,a={})=>({...a,to:n,when:e})}),otherwise:()=>({to:(e,n={})=>({...n,to:e})})},pe=(...e)=>e.flatMap(n=>Array.isArray(n)?[...n]:[n]);0&&(module.exports={JOURNEY_ASYNC_PHASE,JOURNEY_EVENT,JOURNEY_STATUS,JOURNEY_WILDCARD,createJourneyMachine,createPersistenceController,createTransitions,tx});
|
|
1
|
+
"use strict";var te=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var Le=(e,t)=>{for(var o in t)te(e,o,{get:t[o],enumerable:!0})},Pe=(e,t,o,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ae(t))!Oe.call(e,i)&&i!==o&&te(e,i,{get:()=>t[i],enumerable:!(u=ke(t,i))||u.enumerable});return e};var He=e=>Pe(te({},"__esModule",{value:!0}),e);var Ve={};Le(Ve,{JourneyDisposedError:()=>G,createJourneyBuilder:()=>we,createJourneyMachine:()=>Ce});module.exports=He(Ve);var V=(e,t,o)=>{if(!(t in e))throw new Error(o)},U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),z=e=>Array.isArray(e)?e.map(t=>z(t)):U(e)?Object.fromEntries(Object.entries(e).map(([t,o])=>[t,z(o)])):e,de=e=>{if(e===null)return"null";if(Array.isArray(e))return"array";if(typeof e=="object"){let t=e.constructor?.name;return t&&t!=="Object"?t:"object"}return typeof e};function ne(e,t,o,u=[]){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return;let i=u.length===0?t:`${t}.${u.join(".")}`;if(e===void 0)throw new Error(`${i} must be JSON-serializable. Received undefined.`);if(typeof e=="bigint"||typeof e=="symbol"||typeof e=="function")throw new Error(`${i} must be JSON-serializable. Received ${typeof e}.`);if(typeof e!="object")throw new Error(`${i} must be JSON-serializable. Received ${de(e)}.`);if(o.seen.has(e))throw new Error(`${i} must be JSON-serializable. Circular references are not supported.`);if(o.seen.add(e),Array.isArray(e)){for(let[n,s]of e.entries())ne(s,t,o,[...u,String(n)]);return}if(!U(e))throw new Error(`${i} must be JSON-serializable. Received non-plain ${de(e)}.`);for(let[n,s]of Object.entries(e))ne(s,t,o,[...u,n])}function D(e,t="Journey context"){return ne(e,t,{seen:new WeakSet}),e}var $=e=>z(D(e)),B=e=>Array.isArray(e)?e.map(t=>B(t)):e instanceof Date?new Date(e.getTime()):e instanceof Map?new Map([...e.entries()].map(([t,o])=>[B(t),B(o)])):e instanceof Set?new Set([...e].map(t=>B(t))):U(e)?Object.fromEntries(Object.entries(e).map(([t,o])=>[t,B(o)])):e,se=e=>{if(typeof e!="object"&&typeof e!="function"||e===null)return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{return B(e)}else return B(e)},oe=e=>{if(!(typeof e!="object"||e===null||Object.isFrozen(e))){if(Array.isArray(e)){for(let t of e)oe(t);Object.freeze(e);return}if(U(e)){for(let t of Object.values(e))oe(t);Object.freeze(e)}}},pe=e=>typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.trunc(e)),I=()=>Date.now(),ue=e=>[...new Set(e)],je=(e,t)=>Object.fromEntries(t.map(o=>[o,e[o]===!0])),De=(e,t)=>{let o=t??ue(e),u=Object.fromEntries(o.map(i=>[i,!1]));for(let i of e)u[i]=!0;return u},$e=(e,t)=>({...e,[t]:!0}),ie=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function",ye=e=>typeof e=="number"&&Number.isFinite(e),q=(e,t)=>{if(e!==void 0&&!ye(e))throw new Error(`${t} must define a finite numeric "timeoutMs" when provided.`)},re=class extends Error{constructor(o){super(o);this.name="JourneyTimeoutError"}},G=class extends Error{constructor(o){super(`Journey machine has been disposed; "${o}" can no longer be used.`);this.name="JourneyDisposedError";this.operation=o}},le=()=>{let e=globalThis;if(typeof e.__DEV__=="boolean")return e.__DEV__;let t=e.process?.env?.NODE_ENV;return t===void 0||t==="development"},Q=(e,t)=>{if(!(!le()||typeof console>"u")){if(t===void 0){console.warn(e);return}console.warn(e,t)}},ce=(e,t)=>{if(!(!le()||typeof console>"u")){if(t===void 0){console.error(e);return}console.error(e,t)}},_e=async(e,t,o)=>!ye(t)||t<=0?await e:await new Promise((u,i)=>{let n=setTimeout(()=>{i(o())},t);e.then(s=>{clearTimeout(n),u(s)},s=>{clearTimeout(n),i(s)})}),Be=async(e,t)=>{if(t.aborted)throw t.reason;return await new Promise((o,u)=>{let i=()=>{t.removeEventListener("abort",i),u(t.reason)};t.addEventListener("abort",i,{once:!0}),e.then(n=>{t.removeEventListener("abort",i),o(n)},n=>{t.removeEventListener("abort",i),u(n)})})},X=()=>({phase:"idle",eventType:null,transitionId:null,error:null}),Y=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(o=>[o,X()]))}),Z=e=>e.type==="goToStepById"&&"stepId"in e,W=e=>e==="COMPLETE"||e==="TERMINATED",Te=e=>e.event==="completeJourney"?"COMPLETE":e.event==="terminateJourney"?"TERMINATED":e.to,Se=(e,t)=>{let o=t,u=new Set(["from","event","to","when","updateContext","onEnter","onLeave","id","timeoutMs"]);for(let[i,n]of e.entries()){if(!n||typeof n!="object")throw new Error(`Journey transition at index ${i} must be an object.`);for(let s of Object.keys(n))if(!u.has(s))throw new Error(`Journey transition at index ${i} contains unsupported field "${s}".`);if(typeof n.from!="string"||typeof n.event!="string")throw new Error(`Journey transition at index ${i} must define string "from" and "event".`);if(n.from!=="*"&&!(n.from in o))throw new Error(`Journey transition at index ${i} references unknown from step "${n.from}".`);if(q(n.timeoutMs,`Journey transition at index ${i}`),n.when!==void 0&&typeof n.when!="function")throw new Error(`Journey transition at index ${i} must define "when" as a function when provided.`);if(n.updateContext!==void 0&&typeof n.updateContext!="function")throw new Error(`Journey transition at index ${i} must define "updateContext" as a function when provided.`);if(n.onEnter!==void 0&&typeof n.onEnter!="function")throw new Error(`Journey transition at index ${i} must define "onEnter" as a function when provided.`);if(n.onLeave!==void 0&&typeof n.onLeave!="function")throw new Error(`Journey transition at index ${i} must define "onLeave" as a function when provided.`);if(n.id!==void 0&&typeof n.id!="string")throw new Error(`Journey transition at index ${i} must define "id" as a string when provided.`);if(n.event==="completeJourney"||n.event==="terminateJourney"){if("to"in n&&n.to!==void 0)throw new Error(`Journey transition at index ${i} with event "${n.event}" cannot define "to".`);continue}if(typeof n.to!="string")throw new Error(`Journey transition at index ${i} with event "${n.event}" must define string "to".`);if(!W(n.to)&&!(n.to in o))throw new Error(`Journey transition at index ${i} points to unknown step "${n.to}".`)}},M=(e,t,o={})=>({transitioned:t,...o.transitionId!==void 0?{transitionId:o.transitionId}:{},..."error"in o?{error:o.error}:{},snapshot:e}),_=(e,t,o,u,i,n)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let s=Math.max(0,Math.min(Math.trunc(t),e.length-1)),r=e[s],d=ue(n?[...Object.keys(n),...e]:e);return{status:u,currentStepId:r,history:{timeline:[...e],index:s},context:$(o),visited:n?je(n,d):De(e,d),async:z(i)}},P=e=>{let t={...e,history:{timeline:[...e.history.timeline],index:e.history.index},context:$(e.context),visited:{...e.visited},async:z(e.async)};return oe(t),t},fe=async(e,t,o,u,i,n,s)=>{for(let r of e){let d=r.from==="*"||r.from===t.currentStepId,y=r.event===o.type;if(!d||!y)continue;if(!r.when)return r;let l;if(u.aborted)throw u.reason;l=r.when({snapshot:t,context:t.context,from:t.currentStepId,timeline:t.history.timeline,index:t.history.index,event:o,signal:u,handlers:i});let a=ie(l),p=a?l:null,b;try{a?(n?.onAsyncGuardStart?.(r),b=await _e(Be(p,u),r.timeoutMs??s,()=>new re(`Transition guard timed out after ${r.timeoutMs??s}ms (event: ${o.type}, transition: ${r.id??"<anonymous>"}).`))):b=l}catch(C){throw a&&n?.onAsyncGuardError?.(r,C),C}if(a&&n?.onAsyncGuardSuccess?.(r),b)return r}return null},xe=(e,t,o)=>{let u=e.history.timeline.slice(0,e.history.index+1),i=u;t!==e.currentStepId&&(i=[...u,t]);let n=i.length-1,s=$e(e.visited,t);return _(i,n,o,e.status,e.async,s)};var Je=({runtime:e})=>{let t=s=>s==="evaluating-when",o=s=>Object.values(s.byStep).reduce((r,d)=>r+(t(d.phase)?1:0),0),u=o(e.peekSnapshot().async),i=s=>{u=o(s)},n=(s,r,d)=>{if(d!==void 0&&!e.isRunActive(d))return;let y=e.peekSnapshot(),l=y.async.byStep[s]??X(),a=r(l);if(l.phase===a.phase&&l.eventType===a.eventType&&l.transitionId===a.transitionId&&l.error===a.error)return;let p={...y.async.byStep,[s]:a},b=t(l.phase),C=t(a.phase),H=b===C?u:u+(C?1:-1);e.setSnapshot({...y,async:{isLoading:H>0,byStep:p}},{notify:!0,reason:"async"}),u=H};return{syncState:i,updateStepAsync:n,setStepLoading:(s,r,d,y,l)=>{n(s,()=>({phase:r,eventType:d,transitionId:y??null,error:null}),l)},setStepIdle:(s,r)=>{n(s,()=>X(),r)},setStepError:(s,r,d,y,l)=>{n(s,()=>({phase:"error",eventType:r,transitionId:y??null,error:d}),l)}}};var Ne=e=>e.map(t=>typeof t=="string"?t:t.step),Fe=e=>{let t=0;for(let o in e)e[o]&&(t+=1);return t},he=(e,t,o)=>{let u=e.transitions===void 0?"headless":Array.isArray(e.transitions)?"linear":"graph",i=u==="linear"?Ne(e.transitions):null;return()=>{let n=o(),s=n.history.index,r={activeStepId:n.currentStepId,activeStepIndex:s,visitedStepCount:Fe(n.visited),isLoading:n.async.isLoading,isIdle:n.status==="idled",isRunning:n.status==="running",isComplete:n.status==="completed",isTerminated:n.status==="terminated",isInitialStep:n.currentStepId===t.initial};if(u==="linear"&&i!==null){let d=i.length,y=i.indexOf(n.currentStepId);return{...r,activeStepIndex:y===-1?s:y,mode:"linear",stepCount:d,journeyLength:d,isFirstStep:y===0,isLastStep:y===d-1,stepOrder:i}}return u==="graph"?{...r,mode:"graph"}:{...r,mode:"headless"}}};var me=({runtime:e,asyncState:t,initial:o,initialContext:u,steps:i})=>{let n=r=>{Q(`Journey machine has been disposed; "${r}" is a no-op.`)},s=()=>_([o],0,$(u),"idled",Y(i));return{start:()=>e.isDisposed()?(n("start"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let r=e.peekSnapshot();if(r.status!=="idled")return e.getSnapshot();let d=e.setSnapshot({...r,status:"running"},{notify:!0,reason:"start"});return e.emit({type:"journey.start",stepId:d.currentStepId,timestamp:I()}),e.getSnapshot()},()=>e.getSnapshot()),resetJourney:()=>e.isDisposed()?(n("resetJourney"),Promise.resolve(e.getSnapshot())):(e.cancelInFlight(),e.queue(async()=>{let r=e.setSnapshot(s(),{notify:!0,reason:"reset"});return t.syncState(r.async),e.getSnapshot()},()=>e.getSnapshot())),updateContext:r=>e.isDisposed()?(n("updateContext"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let d=e.peekSnapshot(),y=D(r($(d.context)));return e.setSnapshot({...d,context:y},{notify:!0,reason:"context"})},()=>e.getSnapshot()),clearStepError:r=>e.isDisposed()?(n("clearStepError"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let d=e.peekSnapshot(),y=r??d.currentStepId;return y in i&&t.setStepIdle(y),e.getSnapshot()},()=>e.getSnapshot()),dispose:()=>{e.dispose()}}};var Ee=({runtime:e,steps:t,transitions:o,scheduleLifecycle:u})=>({applyPreviousNavigation:(i,n,s=0)=>{let r=e.peekSnapshot();if(r.status!=="running")return M(e.getSnapshot(),!1);let d=pe(i);if(r.history.index===0)return M(e.getSnapshot(),!1);let y=r.currentStepId,l=Math.max(0,r.history.index-d),a=r.history.index-l;if(a<=0)return M(e.getSnapshot(),!1);e.emit({type:"step.exit",stepId:y,timestamp:I()});let p=e.setSnapshot(_(r.history.timeline,l,r.context,r.status,r.async,r.visited),{notify:!0,reason:"navigation"});return e.emit({type:"navigation.previous",from:y,to:p.currentStepId,requestedSteps:d,appliedSteps:a,timestamp:I()}),e.emit({type:"step.enter",stepId:p.currentStepId,timestamp:I()}),u({previousSnapshot:r,snapshot:p,from:y,to:p.currentStepId,event:{type:"goToPreviousStep"},transitionId:n??null,runVersion:s}),M(p,!0,{...n!==void 0?{transitionId:n}:{}})},applyLastVisitedNavigation:(i,n=0)=>{let s=e.peekSnapshot();if(s.status!=="running")return M(e.getSnapshot(),!1);let r=s.history.timeline.length-1;if(s.history.index>=r)return M(e.getSnapshot(),!1);let d=s.currentStepId;e.emit({type:"step.exit",stepId:d,timestamp:I()});let y=e.setSnapshot(_(s.history.timeline,r,s.context,s.status,s.async,s.visited),{notify:!0,reason:"navigation"});return e.emit({type:"navigation.lastVisited",from:d,to:y.currentStepId,timestamp:I()}),e.emit({type:"step.enter",stepId:y.currentStepId,timestamp:I()}),u({previousSnapshot:s,snapshot:y,from:d,to:y.currentStepId,event:{type:"goToLastVisitedStep"},transitionId:i??null,runVersion:n}),M(y,!0,{...i!==void 0?{transitionId:i}:{}})},hasDeclaredTransitionForEvent:(i,n)=>o.some(s=>(s.from==="*"||s.from===i)&&s.event===n),commitTerminalTransition:(i,n,s,r,d,y=0)=>{let l=e.peekSnapshot(),a=l.history.timeline.slice(0,l.history.index+1),p=e.setSnapshot({...l,history:{timeline:a,index:a.length-1},context:d,status:n==="COMPLETE"?"completed":"terminated"},{notify:!0,reason:"transition"});return e.emit({type:"transition.success",from:i,to:n,eventType:s.type,transitionId:r,timestamp:I()}),e.emit({type:n==="COMPLETE"?"journey.completed":"journey.terminated",stepId:p.currentStepId,timestamp:I()}),u({previousSnapshot:l,snapshot:p,from:i,to:n,event:s,transitionId:r,runVersion:y}),M(p,!0,{...r!==null?{transitionId:r}:{}})},commitStepTransition:(i,n,s,r,d,y=0)=>{V(t,n,`Transition points to unknown step "${n}".`);let l=e.peekSnapshot(),a=l.currentStepId;a!==n&&e.emit({type:"step.exit",stepId:a,timestamp:I()});let p=e.setSnapshot(xe(l,n,d),{notify:!0,reason:"transition"});return e.emit({type:"transition.success",from:i,to:p.currentStepId,eventType:s.type,transitionId:r.id??null,timestamp:I()}),a!==p.currentStepId&&e.emit({type:"step.enter",stepId:p.currentStepId,timestamp:I()}),u({previousSnapshot:l,snapshot:p,from:i,to:p.currentStepId,event:s,transitionId:r.id??null,runVersion:y,transition:r}),M(p,!0,{...r.id!==void 0?{transitionId:r.id}:{}})}});var ve=({plugins:e,setupContext:t})=>{let o=[];for(let u of e)try{o.push({name:u.name,hooks:u.setup(t)})}catch(i){for(let r of[...o].reverse())try{r.hooks.dispose?.()}catch{}let n=i instanceof Error?i.message:String(i),s=new Error(`Journey plugin "${u.name}" setup failed: ${n}`);throw Object.assign(s,{cause:i}),s}return{hydrateSnapshot:u=>o.reduce((i,n)=>n.hooks.hydrateSnapshot?.(i)??i,u),onSnapshotChange:({previousSnapshot:u,snapshot:i,reason:n})=>{let s;for(let r of o)try{let d=r.hooks.onSnapshotChange?.({previousSnapshot:u,snapshot:i,reason:n});ie(d)&&Q(`Journey plugin "${r.name}" returned a Promise from onSnapshotChange. This hook must be synchronous; returning a Promise blocks the machine and the await is dropped.`)}catch(d){s??(s=d)}if(s!==void 0)throw s},extendMachine:u=>{let i=u,n=u,s=new Map;for(let r of o){let d=r.hooks.augmentMachine?.({machine:u,journey:t.journey,resolvedJourney:t.resolvedJourney});if(d)for(let[y,l]of Object.entries(d)){let a=s.get(y);if(a)throw new Error(`Journey plugin "${r.name}" cannot add "${y}" \u2014 already provided by plugin "${a}".`);if(y in i)throw new Error(`Journey plugin "${r.name}" cannot override machine property "${y}".`);s.set(y,r.name),n[y]=l}}return i},dispose:()=>{let u;for(let i of o)try{i.hooks.dispose?.()}catch(n){u??(u=n)}if(u!==void 0)throw u}}};var Ie=({snapshot:e,onSnapshotChange:t,onDispose:o,onListenerError:u})=>{let i=P(e),n=P(i),s=new Set,r=new Set,d=Promise.resolve(),y=0,l=!1,a=null,p=new Set,b=u??((f,E)=>{ce(`Journey ${E} listener threw an error.`,f)}),C=()=>{for(let f of s)try{f()}catch(E){b(E,"snapshot")}},H=f=>{for(let E of r)try{E(f)}catch(w){b(w,"event")}},T=(f,E={})=>{let w=n,L=P(f),R=P(L);return t?.({previousSnapshot:P(w),snapshot:P(R),reason:E.reason??"transition"}),i=L,n=R,E.notify&&C(),R},S=f=>!l&&f===y,x=()=>{y+=1,a&&!a.signal.aborted&&a.abort(),a=null;for(let f of p)f.signal.aborted||f.abort();p.clear(),d=Promise.resolve()},J=f=>{if(!S(f))return null;let E=new AbortController;return S(f)?(p.add(E),E):(E.abort(),null)},h=f=>{p.delete(f)},c=(f,E)=>{let w=y,L=async()=>{if(!S(w))return E();let k=new AbortController;a=k;try{return S(w)?await f(w,k.signal):(k.abort(),E())}finally{a===k&&(a=null)}},R=d.then(L,L);return d=R.then(()=>{},()=>{}),R},m=f=>l?()=>{}:(s.add(f),()=>{s.delete(f)});return{getSnapshot:()=>n,peekSnapshot:()=>i,setSnapshot:T,isDisposed:()=>l,isRunActive:S,cancelInFlight:x,openLifecycle:J,closeLifecycle:h,queue:c,notify:C,emit:H,subscribe:m,subscribeSelector:(f,E,w)=>{if(l)return()=>{};let L=w??Object.is,R=f(n);return m(()=>{let k=f(n);if(L(R,k))return;let F=R;R=k,E(k,F)})},subscribeEvent:f=>l?()=>{}:(r.add(f),()=>{r.delete(f)}),dispose:()=>{l||(l=!0,x(),s.clear(),r.clear(),o?.())}}};var ge=(e,t,o,u,i,n,s,r,d)=>{let y=(T="send")=>M(e.getSnapshot(),!1,{...e.isDisposed()?{error:new G(T)}:{}}),l=(T,S)=>M(e.getSnapshot(),!1,{...S!==void 0?{transitionId:S}:{},error:T}),a=(T,S,x,J,h,c=!1)=>(c||t.setStepError(T,S,x,J??void 0,h),e.emit({type:"transition.error",from:T,eventType:S,transitionId:J,error:x,timestamp:I()}),l(x,J??void 0)),p=(T,S)=>Z(T)?(V(i,T.stepId,`Cannot goToStepById unknown step "${T.stepId}".`),{transitionsToEvaluate:n.filter(x=>(x.from==="*"||x.from===S)&&x.event==="goToStepById"&&"to"in x&&x.to===T.stepId),earlyResult:null}):{transitionsToEvaluate:n,earlyResult:null},b=async(T,S,x,J,h)=>{let c,m=null,g=!1;try{c=await fe(T,P(e.peekSnapshot()),S,h,s,{onAsyncGuardStart:v=>{t.setStepLoading(x,"evaluating-when",S.type,v.id,J)},onAsyncGuardSuccess:()=>{t.setStepIdle(x,J)},onAsyncGuardError:(v,A)=>{m=v.id??null,g=!0,t.setStepError(x,S.type,A,v.id,J)}},d)}catch(v){return e.isRunActive(J)?{transition:null,earlyResult:a(x,S.type,v,m,J,g)}:{transition:null,earlyResult:y(S.type)}}return{transition:c,earlyResult:null}},C=(T,S,x)=>{if(Z(T))return y(T.type);if(T.type==="goToPreviousStep"){let J=o.applyPreviousNavigation(1,T.type,x);return J.transitioned&&e.emit({type:"transition.success",from:S,to:J.snapshot.currentStepId,eventType:T.type,transitionId:null,timestamp:I()}),J}return T.type==="goToNextStep"&&!r&&!o.hasDeclaredTransitionForEvent(S,"goToNextStep")||T.type==="completeJourney"&&!o.hasDeclaredTransitionForEvent(S,"completeJourney")?o.commitTerminalTransition(S,"COMPLETE",T,null,e.peekSnapshot().context,x):T.type==="terminateJourney"&&!o.hasDeclaredTransitionForEvent(S,"terminateJourney")?o.commitTerminalTransition(S,"TERMINATED",T,null,e.peekSnapshot().context,x):y(T.type)},H=(T,S,x,J)=>{let h=e.peekSnapshot();if(!T.updateContext)return{nextContext:h.context,earlyResult:null};try{let c=T.updateContext({snapshot:P(h),context:h.context,from:h.currentStepId,timeline:h.history.timeline,index:h.history.index,event:S});return{nextContext:D(c),earlyResult:null}}catch(c){return e.isRunActive(J)?{nextContext:null,earlyResult:a(x,S.type,c,T.id??null,J)}:{nextContext:null,earlyResult:y(S.type)}}};return{buildCanceledSendResult:y,executeSend:async(T,S,x)=>{if(e.peekSnapshot().status!=="running")return y(T.type);let J=e.peekSnapshot().currentStepId,h=T;if(e.emit({type:"transition.start",from:J,event:T,timestamp:I()}),u){if(Z(T))return o.commitStepTransition(J,T.stepId,h,{from:J,event:"goToStepById",to:T.stepId},e.peekSnapshot().context,S);if(T.type!=="completeJourney"&&T.type!=="terminateJourney"&&T.type!=="goToPreviousStep")return y(T.type)}let c=p(T,J);if(c.earlyResult)return c.earlyResult;let m=await b(c.transitionsToEvaluate,h,J,S,x);if(m.earlyResult)return m.earlyResult;if(!e.isRunActive(S))return y(T.type);let{transition:g}=m;if(!g)return C(T,J,S);t.setStepIdle(J,S);let v=H(g,h,J,S);if(v.earlyResult)return v.earlyResult;let A=Te(g);return W(A)?o.commitTerminalTransition(J,A,h,g.id??null,v.nextContext,S):o.commitStepTransition(J,A,h,g,v.nextContext,S)}}};var be=e=>{let t=[],{transitions:o}=e;if(o===void 0)return{...e,transitions:t};if(Array.isArray(o)){if(o.length===0)throw new Error("Journey linear transitions must include the initial step as the first item.");let[n,...s]=o;if(typeof n!="string")throw new Error("Journey linear transitions at index 0 must be a step id string.");if(!(n in e.steps))throw new Error(`Journey linear transitions reference unknown step "${n}".`);let r=e.initial??n;if(e.initial!==void 0&&!o.map(a=>typeof a=="string"?a:a.step).includes(e.initial))throw new Error(`Journey initial step "${e.initial}" does not exist in linear transitions.`);let d=n,y=new Set([n]);for(let[l,a]of s.entries()){let p=l+1;if(typeof a=="string"){if(!(a in e.steps))throw new Error(`Journey linear transitions reference unknown step "${a}".`);if(y.has(a))throw new Error(`Journey linear transitions contain duplicate step "${a}" at index ${p}.`);y.add(a),t.push({from:d,event:"goToNextStep",to:a}),d=a;continue}if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`Journey linear transitions at index ${p} must be a step id string or step config object.`);let b=new Set(["step","id","updateContext","onEnter","onLeave","timeoutMs"]);for(let C of Object.keys(a))if(!b.has(C))throw new Error(`Journey linear transition object at index ${p} contains unsupported field "${C}". Allowed fields are "step", "id", "updateContext", "onEnter", "onLeave", and "timeoutMs".`);if(typeof a.step!="string")throw new Error(`Journey linear transition object at index ${p} must define string "step".`);if(!(a.step in e.steps))throw new Error(`Journey linear transitions reference unknown step "${a.step}".`);if(y.has(a.step))throw new Error(`Journey linear transitions contain duplicate step "${a.step}" at index ${p}.`);if(y.add(a.step),a.updateContext!==void 0&&typeof a.updateContext!="function")throw new Error(`Journey linear transition object at index ${p} must define "updateContext" as a function when provided.`);if(a.onEnter!==void 0&&typeof a.onEnter!="function")throw new Error(`Journey linear transition object at index ${p} must define "onEnter" as a function when provided.`);if(a.onLeave!==void 0&&typeof a.onLeave!="function")throw new Error(`Journey linear transition object at index ${p} must define "onLeave" as a function when provided.`);q(a.timeoutMs,`Journey linear transition object at index ${p}`),t.push({...a.id!==void 0?{id:a.id}:{},...a.timeoutMs!==void 0?{timeoutMs:a.timeoutMs}:{},...a.updateContext!==void 0?{updateContext:a.updateContext}:{},...a.onEnter!==void 0?{onEnter:a.onEnter}:{},...a.onLeave!==void 0?{onLeave:a.onLeave}:{},from:d,event:"goToNextStep",to:a.step}),d=a.step}return{...e,initial:r,transitions:t}}if(!o||typeof o!="object")throw new Error("Journey transitions must be an array or an object map when provided.");let u=o,i=[...u.global?[["global",u.global]]:[],...Object.entries(u).filter(([n])=>n!=="global")];for(let[n,s]of i){if(n!=="global"&&!(n in e.steps))throw new Error(`Journey transitions reference unknown step "${n}".`);if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`Journey transitions for "${n}" must be an event map object.`);for(let[r,d]of Object.entries(s)){let l=(r==="completeJourney"||r==="terminateJourney")&&(d===!0||Array.isArray(d)&&d.length===0)?[{}]:d;if(!Array.isArray(l))throw new Error(`Journey transitions for "${n}.${r}" must be an array.`);for(let[a,p]of l.entries()){if(!p||typeof p!="object")throw new Error(`Journey transition at "${n}.${r}[${a}]" must be an object.`);t.push({...p,from:n==="global"?"*":n,event:r})}}}return{...e,transitions:t}};function Ce(e,t){if(!e.steps||typeof e.steps!="object")throw new Error("Journey steps must be a record object.");if(e.transitions!==void 0&&(e.transitions===null||typeof e.transitions!="object"&&!Array.isArray(e.transitions)))throw new Error("Journey transitions must be an array or an object map when provided.");for(let c of Object.keys(e.steps))if(c==="*"||c==="global"||c==="COMPLETE"||c==="TERMINATED")throw new Error(`Step id "${c}" is reserved and cannot be used as a step name.`);if(e.initial===void 0&&!Array.isArray(e.transitions))throw new Error('Journey "initial" is required for graph and headless definitions. For linear transitions, initial defaults to the first array element.');D(e.context);let o=be(e);V(o.steps,o.initial,`Journey initial step "${o.initial}" does not exist in steps registry.`),Se(o.transitions,o.steps);let u=t?.requireExplicitCompletion??!1;q(t?.defaultTimeoutMs,"Journey machine options");let i=t?.defaultTimeoutMs,n=$(o.context),s=Object.fromEntries(Object.keys(o.steps).map(c=>[c,se(o.steps[c].meta)])),r=()=>_([o.initial],0,$(n),"idled",Y(o.steps)),d=ve({plugins:t?.plugins??[],setupContext:{journey:e,resolvedJourney:o,options:{requireExplicitCompletion:u,defaultTimeoutMs:i},buildInitialSnapshot:r}}),y=d.hydrateSnapshot(r());D(y.context,"Journey hydrated context");let l=t?.onListenerError,a=t?.onLifecycleError,p=Ie({snapshot:y,onSnapshotChange:d.onSnapshotChange,onDispose:d.dispose,...l!==void 0?{onListenerError:l}:{}}),b=Je({runtime:p}),C=()=>Promise.resolve(M(p.getSnapshot(),!1)),H=({previousSnapshot:c,snapshot:m,from:g,to:v,event:A,transitionId:f,runVersion:E,transition:w})=>{let L=o.steps[g],R=W(v)?null:o.steps[v],k=o.handlers??{},F=O=>!p.isRunActive(E)||p.isDisposed()?Promise.resolve(M(p.getSnapshot(),!1)):C(O),ee=p.openLifecycle(E);if(!ee)return;let{signal:j}=ee,K=(O,Re)=>{let ae={phase:Re,from:g,to:v,eventType:A.type,transitionId:f};p.emit({type:"lifecycle.error",...ae,error:O,timestamp:I()}),a?.(O,ae)};(async()=>{try{if(L?.onLeave)try{await L.onLeave({snapshot:c,context:c.context,from:g,to:v,event:A,transitionId:f,handlers:k,signal:j,dispatch:F})}catch(O){if(j.aborted||!p.isRunActive(E))return;K(O,"step.onLeave");return}if(!p.isRunActive(E))return;if(w?.onLeave)try{await w.onLeave({snapshot:c,context:c.context,from:g,to:v,event:A,transitionId:f,handlers:k,signal:j,dispatch:F})}catch(O){if(j.aborted||!p.isRunActive(E))return;K(O,"transition.onLeave");return}if(!p.isRunActive(E))return;if(R?.onEnter)try{await R.onEnter({snapshot:m,context:m.context,from:g,to:v,event:A,transitionId:f,handlers:k,signal:j,dispatch:F})}catch(O){if(j.aborted||!p.isRunActive(E))return;K(O,"step.onEnter");return}if(!p.isRunActive(E))return;if(w?.onEnter)try{await w.onEnter({snapshot:m,context:m.context,from:g,to:v,event:A,transitionId:f,handlers:k,signal:j,dispatch:F})}catch(O){if(j.aborted||!p.isRunActive(E))return;K(O,"transition.onEnter");return}}finally{p.closeLifecycle(ee)}})()},T=Ee({runtime:p,steps:o.steps,transitions:o.transitions,scheduleLifecycle:H}),S=ge(p,b,T,e.transitions===void 0,o.steps,o.transitions,o.handlers??{},u,i),x=me({runtime:p,asyncState:b,initial:o.initial,initialContext:n,steps:o.steps}),J=he(e,o,p.getSnapshot),h={getSnapshot:p.getSnapshot,getStepMeta:c=>se(s[c]),getComputed:J,start:x.start,subscribe:p.subscribe,subscribeSelector:p.subscribeSelector,subscribeEvent:p.subscribeEvent,subscribeStart:c=>p.subscribeEvent(m=>{m.type==="journey.start"&&c(m)}),subscribeComplete:c=>p.subscribeEvent(m=>{m.type==="journey.completed"&&c(m)}),subscribeTerminate:c=>p.subscribeEvent(m=>{m.type==="journey.terminated"&&c(m)}),resetJourney:x.resetJourney,updateContext:x.updateContext,clearStepError:x.clearStepError,dispose:x.dispose,goToPreviousStep:c=>p.queue(async m=>T.applyPreviousNavigation(c,"goToPreviousStep",m),()=>S.buildCanceledSendResult("goToPreviousStep")),goToLastVisitedStep:()=>p.queue(async c=>T.applyLastVisitedNavigation("goToLastVisitedStep",c),()=>S.buildCanceledSendResult("goToLastVisitedStep")),goToNextStep:()=>h.send({type:"goToNextStep"}),goToStepById:c=>h.send({type:"goToStepById",stepId:c}),terminateJourney:c=>c===void 0?h.send({type:"terminateJourney"}):h.send({type:"terminateJourney",payload:c}),completeJourney:c=>c===void 0?h.send({type:"completeJourney"}):h.send({type:"completeJourney",payload:c}),send:c=>p.queue((m,g)=>S.executeSend(c,m,g),()=>S.buildCanceledSendResult(c.type))};return C=h.send,d.extendMachine(h)}function N(e){return{_candidate:e,when(t){return N({...e,_when:t})},updateContext(t){return N({...e,_updateContext:t})},onEnter(t){return N({...e,_onEnter:t})},onLeave(t){return N({...e,_onLeave:t})},id(t){return N({...e,_id:t})},timeoutMs(t){return N({...e,_timeoutMs:t})}}}function Me(e){let t={to:e._to};return e._when!==void 0&&(t.when=e._when),e._updateContext!==void 0&&(t.updateContext=e._updateContext),e._onEnter!==void 0&&(t.onEnter=e._onEnter),e._onLeave!==void 0&&(t.onLeave=e._onLeave),e._id!==void 0&&(t.id=e._id),e._timeoutMs!==void 0&&(t.timeoutMs=e._timeoutMs),t}function Ge(e){let t={};return e.when!==void 0&&(t.when=e.when),e.updateContext!==void 0&&(t.updateContext=e.updateContext),e.onEnter!==void 0&&(t.onEnter=e.onEnter),e.onLeave!==void 0&&(t.onLeave=e.onLeave),e.id!==void 0&&(t.id=e.id),e.timeoutMs!==void 0&&(t.timeoutMs=e.timeoutMs),t}function we(){function e(n){return N({_to:n,_when:void 0,_updateContext:void 0,_onEnter:void 0,_onLeave:void 0,_id:void 0,_timeoutMs:void 0})}function t(n){return typeof n=="function"?n({to:e}):n}function o(n){return n===!0||n.length===0?n:n.map(s=>Ge(s))}function u(n,s){return{_id:n,_meta:s?.meta,_onEnter:s?.onEnter,_onLeave:s?.onLeave,_on:s?.on}}function i(n){let s={},r={};for(let d of n.steps)if(s[d._id]={...d._meta!==void 0?{meta:d._meta}:{},...d._onEnter!==void 0?{onEnter:d._onEnter}:{},...d._onLeave!==void 0?{onLeave:d._onLeave}:{}},d._on){let y={};for(let[l,a]of Object.entries(d._on)){if(!a)continue;if(l==="completeJourney"||l==="terminateJourney"){y[l]=o(a);continue}let p=t(a);y[l]=p.map(b=>Me(b._candidate))}r[d._id]=y}if(n.global){let d={};for(let[y,l]of Object.entries(n.global))l!==void 0&&(y==="completeJourney"||y==="terminateJourney"?d[y]=o(l):Array.isArray(l)&&(d[y]=l.map(a=>Me(a._candidate))));r.global=d}return{initial:n.initial,context:n.context,...n.handlers!==void 0?{handlers:n.handlers}:{},steps:s,transitions:r}}return{createStep:u,to:e,build:i}}0&&(module.exports={JourneyDisposedError,createJourneyBuilder,createJourneyMachine});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|