@rxova/journey-core 0.7.0 → 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.
Files changed (99) hide show
  1. package/README.md +235 -105
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.cjs.map +4 -4
  4. package/dist/index.d.cts +5 -4
  5. package/dist/index.d.ts +5 -4
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +4 -4
  8. package/dist/journey-builder/index.d.cts +5 -0
  9. package/dist/journey-builder/index.d.ts +5 -0
  10. package/dist/journey-builder/types.d.cts +69 -0
  11. package/dist/journey-builder/types.d.ts +69 -0
  12. package/dist/journey-machine/async-state.d.cts +12 -0
  13. package/dist/journey-machine/async-state.d.ts +12 -0
  14. package/dist/journey-machine/computed.d.cts +2 -0
  15. package/dist/journey-machine/computed.d.ts +2 -0
  16. package/dist/journey-machine/controls.d.cts +17 -0
  17. package/dist/journey-machine/controls.d.ts +17 -0
  18. package/dist/journey-machine/helpers.d.cts +44 -0
  19. package/dist/journey-machine/helpers.d.ts +44 -0
  20. package/dist/journey-machine/index.d.cts +3 -0
  21. package/dist/journey-machine/index.d.ts +3 -0
  22. package/dist/journey-machine/navigation.d.cts +31 -0
  23. package/dist/journey-machine/navigation.d.ts +31 -0
  24. package/dist/journey-machine/plugin-controller.d.cts +15 -0
  25. package/dist/journey-machine/plugin-controller.d.ts +15 -0
  26. package/dist/journey-machine/resolve-journey-definition.d.cts +2 -0
  27. package/dist/journey-machine/resolve-journey-definition.d.ts +2 -0
  28. package/dist/journey-machine/runtime.d.cts +33 -0
  29. package/dist/journey-machine/runtime.d.ts +33 -0
  30. package/dist/journey-machine/send.d.cts +9 -0
  31. package/dist/journey-machine/send.d.ts +9 -0
  32. package/dist/plugins/analytics/index.cjs +2 -0
  33. package/dist/plugins/analytics/index.cjs.map +7 -0
  34. package/dist/plugins/analytics/index.d.cts +25 -0
  35. package/dist/plugins/analytics/index.d.ts +25 -0
  36. package/dist/plugins/analytics/index.js +2 -0
  37. package/dist/plugins/analytics/index.js.map +7 -0
  38. package/dist/plugins/autosave/index.cjs +2 -0
  39. package/dist/plugins/autosave/index.cjs.map +7 -0
  40. package/dist/plugins/autosave/index.d.cts +17 -0
  41. package/dist/plugins/autosave/index.d.ts +17 -0
  42. package/dist/plugins/autosave/index.js +2 -0
  43. package/dist/plugins/autosave/index.js.map +7 -0
  44. package/dist/plugins/diagnostics/diagnostics.d.cts +3 -0
  45. package/dist/plugins/diagnostics/diagnostics.d.ts +3 -0
  46. package/dist/plugins/diagnostics/index.cjs +2 -0
  47. package/dist/plugins/diagnostics/index.cjs.map +7 -0
  48. package/dist/plugins/diagnostics/index.d.cts +15 -0
  49. package/dist/plugins/diagnostics/index.d.ts +15 -0
  50. package/dist/plugins/diagnostics/index.js +2 -0
  51. package/dist/plugins/diagnostics/index.js.map +7 -0
  52. package/dist/plugins/execution-paths/execution-paths.d.cts +6 -0
  53. package/dist/plugins/execution-paths/execution-paths.d.ts +6 -0
  54. package/dist/plugins/execution-paths/index.cjs +2 -0
  55. package/dist/plugins/execution-paths/index.cjs.map +7 -0
  56. package/dist/plugins/execution-paths/index.d.cts +18 -0
  57. package/dist/plugins/execution-paths/index.d.ts +18 -0
  58. package/dist/plugins/execution-paths/index.js +2 -0
  59. package/dist/plugins/execution-paths/index.js.map +7 -0
  60. package/dist/plugins/persistence/controller.d.cts +17 -0
  61. package/dist/plugins/persistence/controller.d.ts +17 -0
  62. package/dist/plugins/persistence/index.cjs +2 -0
  63. package/dist/plugins/persistence/index.cjs.map +7 -0
  64. package/dist/plugins/persistence/index.d.cts +12 -0
  65. package/dist/plugins/persistence/index.d.ts +12 -0
  66. package/dist/plugins/persistence/index.js +2 -0
  67. package/dist/plugins/persistence/index.js.map +7 -0
  68. package/dist/plugins/replay/index.cjs +2 -0
  69. package/dist/plugins/replay/index.cjs.map +7 -0
  70. package/dist/plugins/replay/index.d.cts +27 -0
  71. package/dist/plugins/replay/index.d.ts +27 -0
  72. package/dist/plugins/replay/index.js +2 -0
  73. package/dist/plugins/replay/index.js.map +7 -0
  74. package/dist/types/analytics.types.d.cts +32 -0
  75. package/dist/types/analytics.types.d.ts +32 -0
  76. package/dist/types/autosave.types.d.cts +23 -0
  77. package/dist/types/autosave.types.d.ts +23 -0
  78. package/dist/types/diagnostics.types.d.cts +38 -0
  79. package/dist/types/diagnostics.types.d.ts +38 -0
  80. package/dist/types/index.d.cts +9 -0
  81. package/dist/types/index.d.ts +9 -4
  82. package/dist/types/journey.types.d.cts +190 -0
  83. package/dist/types/journey.types.d.ts +139 -167
  84. package/dist/types/machine.types.d.cts +102 -0
  85. package/dist/types/machine.types.d.ts +102 -0
  86. package/dist/types/observation.types.d.cts +75 -0
  87. package/dist/types/observation.types.d.ts +75 -0
  88. package/dist/types/persistence.types.d.cts +34 -0
  89. package/dist/types/persistence.types.d.ts +13 -20
  90. package/dist/types/replay.types.d.cts +35 -0
  91. package/dist/types/replay.types.d.ts +35 -0
  92. package/dist/types/transitions.types.d.cts +117 -0
  93. package/dist/types/transitions.types.d.ts +94 -56
  94. package/package.json +68 -2
  95. package/dist/machine-helpers.d.ts +0 -23
  96. package/dist/machine.d.ts +0 -11
  97. package/dist/persistence.d.ts +0 -17
  98. package/dist/transitions.d.ts +0 -62
  99. package/dist/types.d.ts +0 -1
package/README.md CHANGED
@@ -1,152 +1,282 @@
1
1
  # @rxova/journey-core
2
2
 
3
- Headless runtime for non-linear journeys.
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
 
7
23
  ```bash
8
- pnpm add @rxova/journey-core
9
- yarn add @rxova/journey-core
10
24
  npm i @rxova/journey-core
11
- bun add @rxova/journey-core
12
25
  ```
13
26
 
14
- Runs in Bun-based SPAs and other standard ESM runtimes.
27
+ ## Quickstart
28
+
29
+ ```ts
30
+ import { createJourneyMachine } from "@rxova/journey-core";
15
31
 
16
- ## What You Get
32
+ const machine = createJourneyMachine({
33
+ initial: "account",
34
+ context: { name: "" },
35
+ steps: { account: {}, details: {}, review: {} },
36
+ transitions: ["account", "details", "review"]
37
+ });
17
38
 
18
- - Deterministic transition matching (first match wins).
19
- - Timeline + pointer navigation model (`history.timeline` + `history.index`).
20
- - Built-in navigation and terminal events:
21
- `goToNextStep()`, `goToPreviousStep()`, `goToLastVisitedStep()`, `completeJourney()`, `terminateJourney()`.
22
- - Async guard/effect lifecycle state in `snapshot.async`.
23
- - Typed observability stream via `subscribeEvent`.
24
- - Step metadata updates via `updateStepMetadata`.
25
- - Optional persistence with schema versioning and migration hooks.
39
+ machine.start();
26
40
 
27
- ## Quickstart
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.
28
58
 
29
59
  ```ts
30
- import { createJourneyMachine } from "@rxova/journey-core";
60
+ transitions: [
61
+ "account",
62
+ {
63
+ step: "details",
64
+ updateContext: ({ context }) => ({ ...context, step: 2 }),
65
+ timeoutMs: 5000
66
+ },
67
+ "payment",
68
+ "review"
69
+ ];
70
+ ```
31
71
 
32
- type StepId = "start" | "review";
33
- type Event = "goToNextStep" | "completeJourney" | "back";
34
- type Ctx = { name: string };
72
+ ### Graph
35
73
 
36
- const journey = {
37
- initial: "start",
38
- context: { name: "" },
39
- steps: {
40
- start: { meta: { label: "Start" } },
41
- review: { meta: { label: "Review" } }
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
+ ]
42
83
  },
43
- transitions: [
44
- { from: "start", event: "goToNextStep", to: "review" },
45
- { from: "review", event: "completeJourney" }
46
- ]
47
- };
84
+ admin: { completeJourney: true },
85
+ dashboard: { completeJourney: true },
86
+ global: { terminateJourney: true }
87
+ }
88
+ ```
48
89
 
49
- const machine = createJourneyMachine<Ctx, StepId, Event>(journey);
50
- await machine.goToNextStep();
51
- await machine.goToPreviousStep();
52
- await machine.completeJourney();
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>();
53
97
 
54
- const snapshot = machine.getSnapshot();
55
- console.log(snapshot.history.timeline, snapshot.history.index, snapshot.currentStepId);
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
+ });
56
112
  ```
57
113
 
58
- By default, `goToNextStep()` completes the machine when the current step declares no `goToNextStep` transition. Set `completeOnNoNextStep: false` in `createJourneyMachine(...)` options to opt out.
114
+ Use the **factory form** when you need `event.payload` narrowed to the specific event type:
59
115
 
60
- ## Behavioral Guarantees
116
+ ```ts
117
+ submit: ({ to }) => [to("admin").when(({ context, event }) => event.payload?.username !== "")];
118
+ ```
61
119
 
62
- - Transition selection is ordered: the first matching transition wins.
63
- - Same-step transitions are non-reentrant: when a transition resolves to the current step id, Journey emits `transition.start`/`transition.success` but skips `step.exit` and `step.enter`.
64
- - `send({ type: "back" })` falls back to previous-step navigation when no explicit `back` transition exists.
65
- - Once status is `complete` or `terminated`, pointer navigation and transitions no-op until `resetMachine()`.
66
- - Forward navigation after moving back truncates timeline tail before appending the next step.
67
- - Snapshot shape is stable: `currentStepId === history.timeline[history.index]`.
120
+ ### Headless
68
121
 
69
- ## Async Lifecycle
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.
70
123
 
71
- When guards/effects are async, step async state is tracked in `snapshot.async.byStep[stepId]`:
124
+ ```ts
125
+ const machine = createJourneyMachine({
126
+ initial: "start",
127
+ context: {},
128
+ steps: { start: {}, configure: {}, confirm: {} }
129
+ // no transitions — the caller drives the flow
130
+ });
72
131
 
73
- - `evaluating-when`: async guard in progress
74
- - `running-effect`: async effect in progress
75
- - `error`: guard/effect failed
76
- - `idle`: no active async work
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
+ ```
77
138
 
78
- `clearStepError(stepId?)` resets a step from `error` to `idle`.
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.
79
140
 
80
- `updateContext()` updates the current snapshot immediately, but it does not rebase an async transition that is already running. Async guards and effects keep the context they started with, and a running effect can later commit over a newer `updateContext()` call. If a context change must affect a transition, apply it before `send(...)` or wait for the transition promise to settle.
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.
81
142
 
82
- `send(...)` and convenience helpers resolve with `transitioned: false` and `error` when a guard or effect fails. They still emit `transition.error` and leave the source step in async `error` phase.
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.
83
144
 
84
- ## Persistence
145
+ ## Step Lifecycle
85
146
 
86
- Persistence is optional and disabled automatically if storage is unavailable.
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.
87
148
 
88
149
  ```ts
89
- const machine = createJourneyMachine(journey, {
90
- persistence: {
91
- key: "checkout:journey",
92
- version: 2,
93
- clearOnReset: false,
94
- migrate: (legacySnapshot, persistedVersion) => {
95
- if (persistedVersion < 2) {
96
- return {
97
- currentStepId: "start",
98
- history: { timeline: ["start"], index: 0 },
99
- context: { name: "" },
100
- status: "running",
101
- visited: { start: true, review: false },
102
- stepMeta: { start: undefined, review: undefined }
103
- };
104
- }
105
- return legacySnapshot as never;
150
+ const machine = createJourneyMachine({
151
+ context: { username: "" },
152
+ steps: {
153
+ login: {
154
+ onLeave: ({ context }) => analytics.track("login_left", { user: context.username })
106
155
  },
107
- onError: (error) => {
108
- console.error("Persistence error", error);
156
+ dashboard: {
157
+ onEnter: ({ context }) => analytics.track("dashboard_entered"),
158
+ onLeave: ({ context }) => console.log("leaving dashboard")
109
159
  }
110
- }
160
+ },
161
+ transitions: ["login", "dashboard"]
162
+ });
163
+ ```
164
+
165
+ With the graph builder, callbacks sit alongside transitions on the step:
166
+
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
+ });
173
+ ```
174
+
175
+ In React, use `useJourneyStepLifecycle` when the callback needs access to component state or React context:
176
+
177
+ ```tsx
178
+ const { useJourneyStepLifecycle } = createJourney(definition);
179
+
180
+ function Dashboard() {
181
+ useJourneyStepLifecycle("dashboard", {
182
+ onEnter: ({ context }) => analytics.track("dashboard_entered"),
183
+ onLeave: ({ context }) => console.log("leaving dashboard")
184
+ });
185
+ // ...
186
+ }
187
+ ```
188
+
189
+ The hook always calls the latest version of your callbacks without re-subscribing.
190
+
191
+ ## Features
192
+
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
201
+
202
+ ## Persistence
203
+
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
+ ]
111
215
  });
112
216
  ```
113
217
 
114
- Hydration coercion is defensive: malformed timeline/index/visited/status values fall back to safe defaults.
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
223
+
224
+ ```ts
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
+ ]
235
+ });
115
236
 
116
- ## Observability
237
+ await machine.flushAutosave();
238
+ ```
117
239
 
118
- Use `subscribeEvent` to inspect transition and navigation lifecycle events:
240
+ Autosave adds debounced draft persistence, hydration, `getAutosaveState()`, `flushAutosave()`, and `clearAutosave()` without requiring the persistence plugin as a separate public dependency.
119
241
 
120
- - `journey.start`
121
- - `transition.start`
122
- - `transition.success`
123
- - `transition.error`
124
- - `step.exit`
125
- - `step.enter`
126
- - `navigation.previous`
127
- - `navigation.lastVisited`
128
- - `journey.complete`
129
- - `journey.close`
130
- - `metadata.updated`
242
+ ## Analytics
131
243
 
132
- Use `subscribeStart(...)`, `subscribeComplete(...)`, and `subscribeTerminate(...)` when you only care about a specific lifecycle event.
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
+ ```
133
256
 
134
- `journey.start` is delivered immediately to each `subscribeEvent(...)` listener with the machine's startup step and startup timestamp.
257
+ Analytics normalizes Journey lifecycle events into a stable event envelope and adds `trackAnalyticsEvent(...)` for custom markers.
135
258
 
136
- ## Transition Ergonomics
259
+ ## DevTools
137
260
 
138
261
  ```ts
139
- import { createTransitions, tx } from "@rxova/journey-core";
140
-
141
- const transitions = createTransitions(
142
- tx.from("start").on("goToNextStep").to("review"),
143
- tx
144
- .from("review")
145
- .on("goToNextStep")
146
- .choose(
147
- tx.when(({ context }) => context.canSubmit).to("done", { id: "review-submit" }),
148
- tx.otherwise().to("review", { id: "review-stay" })
149
- ),
150
- tx.from("review").toComplete()
151
- );
262
+ import { attachJourneyDevtools } from "@rxova/journey-devtools-bridge";
263
+
264
+ const detach = attachJourneyDevtools(machine, { label: "Checkout" });
152
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 W=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var he=(e,r)=>{for(var s in r)W(e,s,{get:r[s],enumerable:!0})},be=(e,r,s,d)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of ge(r))!Re.call(e,a)&&a!==s&&W(e,a,{get:()=>r[a],enumerable:!(d=Ce(r,a))||d.enumerable});return e};var Ne=e=>be(W({},"__esModule",{value:!0}),e);var Ue={};he(Ue,{JOURNEY_ASYNC_PHASE:()=>R,JOURNEY_EVENT:()=>O,JOURNEY_STATUS:()=>m,JOURNEY_WILDCARD:()=>w,createJourneyMachine:()=>ie,createPersistenceController:()=>V,createTransitions:()=>ue,tx:()=>de});module.exports=Ne(Ue);var m={RUNNING:"running",COMPLETE:"complete",TERMINATED:"terminated"},w="*",O={GO_TO_STEP_BY_ID:"goToStepById"},R={IDLE:"idle",EVALUATING_WHEN:"evaluating-when",RUNNING_EFFECT:"running-effect",ERROR:"error"};var Y=(e,r,s)=>{if(!(r in e))throw new Error(s)},oe=e=>typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.trunc(e)),J=()=>Date.now(),we=e=>[...new Set(e)],Oe=(e,r)=>Object.fromEntries(r.map(s=>[s,e[s]===!0])),F=(e,r)=>{let s=r??we(e),d=Object.fromEntries(s.map(a=>[a,!1]));for(let a of e)d[a]=!0;return d},Ae=(e,r)=>({...e,[r]:!0}),z=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function",L=()=>({phase:R.IDLE,eventType:null,transitionId:null,error:null}),U=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(s=>[s,L()]))}),Q=e=>e.type===O.GO_TO_STEP_BY_ID&&"stepId"in e,K=e=>e==="COMPLETE"||e==="TERMINATED",re=(e,r)=>{let s=r;for(let[d,a]of e.entries()){if(!a||typeof a!="object")throw new Error(`Journey transition at index ${d} must be an object.`);if(typeof a.from!="string"||typeof a.event!="string")throw new Error(`Journey transition at index ${d} must define string "from" and "event".`);if(a.from!==w&&!(a.from in s))throw new Error(`Journey transition at index ${d} references unknown from step "${a.from}".`);if(a.event==="completeJourney"||a.event==="terminateJourney"){if("to"in a&&a.to!==void 0)throw new Error(`Journey transition at index ${d} with event "${a.event}" cannot define "to".`);continue}if(typeof a.to!="string")throw new Error(`Journey transition at index ${d} with event "${a.event}" must define string "to".`);if(!K(a.to)&&!(a.to in s))throw new Error(`Journey transition at index ${d} points to unknown step "${a.to}".`)}},P=(e,r,s={})=>({transitioned:r,...s.transitionId!==void 0?{transitionId:s.transitionId}:{},..."error"in s?{error:s.error}:{},snapshot:e}),_=(e,r,s,d,a,c,y)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let t=Math.max(0,Math.min(Math.trunc(r),e.length-1)),M=e[t],f=Object.keys(c);return{status:d,currentStepId:M,history:{timeline:[...e],index:t},context:s,visited:y?Oe(y,f):F(e,f),stepMeta:{...c},async:a}},ae=async(e,r,s,d)=>{for(let a of e){let c=a.from===w||a.from===r.currentStepId,y=a.event===s.type;if(!c||!y)continue;if(!a.when)return a;let t=a.when({context:r.context,from:r.currentStepId,timeline:r.history.timeline,index:r.history.index,event:s}),M=z(t);M&&d?.onAsyncGuardStart?.(a);let f;try{f=await t}catch(C){throw M&&d?.onAsyncGuardError?.(a,C),C}if(M&&d?.onAsyncGuardSuccess?.(a),f)return a}return null},X=(e,r,s)=>{let d=e.history.timeline.slice(0,e.history.index+1),a=d;r!==e.currentStepId&&(a=[...d,r]);let c=a.length-1,y=Ae(e.visited,r);return _(a,c,s,e.status,e.async,e.stepMeta,y)};var G=e=>typeof e=="object"&&e!==null,se=e=>e===m.RUNNING||e===m.COMPLETE||e===m.TERMINATED,De=()=>{let e=globalThis.localStorage;return!e||typeof e.getItem!="function"||typeof e.setItem!="function"||typeof e.removeItem!="function"?null:e},_e=e=>{if(!e)return null;let r=e.storage;if(r==null)try{r=De()}catch(s){return e.onError?.(s),null}return r?{key:e.key,storage:r,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},ke=(e,r,s)=>{let d=F(r,s);if(G(e)){let a=!1,c={...d};for(let y of s){let t=e[y];if(t===!0){c[y]=!0;continue}if(t===!1){d[y]&&(a=!0);continue}a=!0}return{visited:c,needsRewrite:a}}if(Array.isArray(e)){let a=F(e.filter(y=>typeof y=="string"&&s.includes(y)),s);return{visited:Object.fromEntries(s.map(y=>[y,d[y]||a[y]])),needsRewrite:!0}}return{visited:d,needsRewrite:!0}},pe=(e,r,s,d)=>{if(!G(e))return null;let a=!1,c=G(e.history)?e.history:null;c||(a=!0);let y=c?.timeline??e.timeline,t=Array.isArray(y)?y.filter(x=>typeof x=="string"&&x in r):[],M=typeof e.currentStepId=="string"&&e.currentStepId in r?e.currentStepId:typeof e.current=="string"&&e.current in r?e.current:null;if(t.length===0){if(!M)return null;t.push(M),a=!0}let f=t.length-1,C=c?.index??e.index;if(typeof C=="number"&&Number.isFinite(C))f=Math.max(0,Math.min(Math.trunc(C),t.length-1)),f!==C&&(a=!0);else if(M){let x=t.lastIndexOf(M);x>=0&&(f=x,a=!0)}let S=se(e.status)?e.status:m.RUNNING;se(e.status)||(a=!0);let g=Object.keys(r),{visited:h,needsRewrite:I}=ke(e.visited,t,g);I&&(a=!0);let E=G(e.stepMeta)?e.stepMeta:null;E||(a=!0);let D=Object.fromEntries(Object.keys(r).map(x=>{let l=x,k=E?E[x]:void 0;return k===void 0?[l,d[l]]:[l,k]}));return{snapshot:{currentStepId:t[f],history:{timeline:t,index:f},context:"context"in e?e.context:s,status:S,visited:h,stepMeta:D},needsRewrite:a}},V=e=>{let{initial:r,context:s,stepMeta:d,steps:a,options:c}=e,y=_e(c?.persistence),t=S=>{y?.onError?.(S)},M=S=>{if(y)try{let g={version:y.version,snapshot:{currentStepId:S.currentStepId,history:{timeline:[...S.history.timeline],index:S.history.index},context:S.context,status:S.status,visited:{...S.visited},stepMeta:{...S.stepMeta}}};y.storage.setItem(y.key,y.serialize(g))}catch(g){t(g)}},f=()=>{if(y)try{y.storage.removeItem(y.key)}catch(S){t(S)}},C=()=>{let S=_([r],0,s,m.RUNNING,U(a),d);if(!y)return S;try{let g=y.storage.getItem(y.key);if(!g)return S;let h=y.deserialize(g);if(!G(h))return S;let I=h.version;if(typeof I!="number")return S;let E=null,D=!1;if(I===y.version){let l=pe(h.snapshot,a,s,d);E=l?.snapshot??null,D=!!l?.needsRewrite}else if(y.migrate){let l=y.migrate(h.snapshot,I);E=pe(l,a,s,d)?.snapshot??null,D=E!==null}if(!E)return S;let x=_(E.history.timeline,E.history.index,E.context,E.status,U(a),E.stepMeta,E.visited);return D&&M(x),x}catch(g){return t(g),S}};return{clearOnReset:y?.clearOnReset??!0,hydrateSnapshot:C,persistSnapshot:M,removePersistedSnapshot:f}};function ie(e,r){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.");for(let n of Object.keys(e.steps))if(n==="*")throw new Error('Step id "*" is reserved as a wildcard and cannot be used as a step name.');Y(e.steps,e.initial,`Journey initial step "${e.initial}" does not exist in steps registry.`),re(e.transitions,e.steps);let s=()=>{let n={};for(let o of Object.keys(e.steps))n[o]=e.steps[o].meta;return n},{clearOnReset:d,hydrateSnapshot:a,persistSnapshot:c,removePersistedSnapshot:y}=V({initial:e.initial,context:e.context,stepMeta:s(),steps:e.steps,...r?{options:r}:{}}),t=a();t={...t,async:U(e.steps)};let M=r?.completeOnNoNextStep??!0,f={type:"journey.start",stepId:t.currentStepId,timestamp:J()},C=new Set,S=new Set,g=Promise.resolve(),h=0,I=!1,E=n=>!I&&n===h,D=()=>{h+=1,g=Promise.resolve()},x=()=>{for(let n of C)n()},l=n=>{for(let o of S)o(n)},k=(n,o)=>{let p=h,i=async()=>E(p)?n(p):o(),T=v=>{g=v.then(()=>{},()=>{})},u=g.then(i,i);return T(u),u},le=n=>n===R.EVALUATING_WHEN||n===R.RUNNING_EFFECT,$=(n,o,p)=>{if(p!==void 0&&!E(p))return;let i=t.async.byStep[n]??L(),T=o(i);if(i.phase===T.phase&&i.eventType===T.eventType&&i.transitionId===T.transitionId&&i.error===T.error)return;let u={...t.async.byStep,[n]:T},v=Object.values(u).some(N=>le(N.phase));t={...t,async:{isLoading:v,byStep:u}},x()},Z=(n,o,p,i,T)=>{$(n,()=>({phase:o,eventType:p,transitionId:i??null,error:null}),T)},B=(n,o)=>{$(n,()=>L(),o)},ee=(n,o,p,i,T)=>{$(n,()=>({phase:R.ERROR,eventType:o,transitionId:i??null,error:p}),T)},te=(n,o)=>{if(t.status!==m.RUNNING)return P(t,!1);let p=oe(n);if(t.history.index===0)return P(t,!1);let i=t.currentStepId,T=Math.max(0,t.history.index-p),u=t.history.index-T;return u<=0?P(t,!1):(l({type:"step.exit",stepId:i,timestamp:J()}),t=_(t.history.timeline,T,t.context,t.status,t.async,t.stepMeta,t.visited),c(t),x(),l({type:"navigation.previous",from:i,to:t.currentStepId,requestedSteps:p,appliedSteps:u,timestamp:J()}),l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...o!==void 0?{transitionId:o}:{}}))},Se=n=>{if(t.status!==m.RUNNING)return P(t,!1);let o=t.history.timeline.length-1;if(t.history.index>=o)return P(t,!1);let p=t.currentStepId;return l({type:"step.exit",stepId:p,timestamp:J()}),t=_(t.history.timeline,o,t.context,t.status,t.async,t.stepMeta,t.visited),c(t),x(),l({type:"navigation.lastVisited",from:p,to:t.currentStepId,timestamp:J()}),l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...n!==void 0?{transitionId:n}:{}})},A=()=>P(t,!1),ce=(n,o)=>P(t,!1,{...o!==void 0?{transitionId:o}:{},error:n}),q=(n,o,p,i,T)=>(ee(n,o,p,i??void 0,T),l({type:"transition.error",from:n,eventType:o,transitionId:i,error:p,timestamp:J()}),ce(p,i??void 0)),Ee=(n,o,p)=>{B(o,p);let i=t.currentStepId,T=X(t,n,t.context);return T.currentStepId!==i&&l({type:"step.exit",stepId:i,timestamp:J()}),t=T,c(t),x(),l({type:"transition.success",from:o,to:t.currentStepId,eventType:O.GO_TO_STEP_BY_ID,transitionId:O.GO_TO_STEP_BY_ID,timestamp:J()}),T.currentStepId!==i&&l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{transitionId:O.GO_TO_STEP_BY_ID})},xe=(n,o,p)=>{if(!Q(n))return{transitionsToEvaluate:e.transitions,earlyResult:null};Y(e.steps,n.stepId,`Cannot goToStepById unknown step "${n.stepId}".`);let i=e.transitions.filter(T=>(T.from==="*"||T.from===o)&&T.event===O.GO_TO_STEP_BY_ID&&"to"in T&&T.to===n.stepId);return i.length===0?{transitionsToEvaluate:e.transitions,earlyResult:Ee(n.stepId,o,p)}:{transitionsToEvaluate:i,earlyResult:null}},Je=async(n,o,p,i)=>{let T;try{T=await ae(n,t,o,{onAsyncGuardStart:u=>{Z(p,R.EVALUATING_WHEN,o.type,u.id,i)},onAsyncGuardSuccess:()=>{B(p,i)},onAsyncGuardError:(u,v)=>{ee(p,o.type,v,u.id,i)}})}catch(u){return E(i)?{transition:null,earlyResult:q(p,o.type,u,null,i)}:{transition:null,earlyResult:A()}}return{transition:T,earlyResult:null}},ve=(n,o)=>{if(Q(n))return A();if(n.type==="goToPreviousStep"||n.type==="back"){let p=te(1,n.type);return p.transitioned&&l({type:"transition.success",from:o,to:p.snapshot.currentStepId,eventType:n.type,transitionId:null,timestamp:J()}),p}return n.type==="goToNextStep"&&M&&!Me(o,"goToNextStep")?ne(o,"COMPLETE",n,null,t.context):A()},Ie=async(n,o,p,i)=>{let T=t.context;if(!n.effect)return{nextContext:T,earlyResult:null};let u;try{u=n.effect({context:t.context,from:t.currentStepId,timeline:t.history.timeline,index:t.history.index,event:o})}catch(N){return E(i)?{nextContext:null,earlyResult:q(p,o.type,N,n.id??null,i)}:{nextContext:null,earlyResult:A()}}z(u)&&Z(p,R.RUNNING_EFFECT,o.type,n.id,i);let v;try{v=await u}catch(N){return E(i)?{nextContext:null,earlyResult:q(p,o.type,N,n.id??null,i)}:{nextContext:null,earlyResult:A()}}return E(i)?(v!==void 0&&(T=v),{nextContext:T,earlyResult:null}):{nextContext:null,earlyResult:A()}},me=n=>n.event==="completeJourney"?"COMPLETE":n.event==="terminateJourney"?"TERMINATED":n.to,Me=(n,o)=>e.transitions.some(p=>(p.from==="*"||p.from===n)&&p.event===o),ne=(n,o,p,i,T)=>{let u=t.history.timeline.slice(0,t.history.index+1);return t={...t,history:{timeline:u,index:u.length-1},context:T,status:o==="COMPLETE"?m.COMPLETE:m.TERMINATED},c(t),x(),l({type:"transition.success",from:n,to:o,eventType:p.type,transitionId:i,timestamp:J()}),l({type:o==="COMPLETE"?"journey.complete":"journey.close",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...i!==null?{transitionId:i}:{}})},fe=(n,o,p,i,T)=>{Y(e.steps,o,`Transition points to unknown step "${o}".`);let u=t.currentStepId;return u!==o&&l({type:"step.exit",stepId:u,timestamp:J()}),t=X(t,o,T),c(t),x(),l({type:"transition.success",from:n,to:t.currentStepId,eventType:p.type,transitionId:i.id??null,timestamp:J()}),u!==t.currentStepId&&l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...i.id!==void 0?{transitionId:i.id}:{}})},Pe=async(n,o)=>{if(t.status!==m.RUNNING)return A();let p=t.currentStepId,i=n;l({type:"transition.start",from:p,event:n,timestamp:J()});let T=xe(n,p,o);if(T.earlyResult)return T.earlyResult;let u=await Je(T.transitionsToEvaluate,i,p,o);if(u.earlyResult)return u.earlyResult;if(!E(o))return A();let{transition:v}=u;if(!v)return ve(n,p);let N=await Ie(v,i,p,o);if(N.earlyResult)return N.earlyResult;B(p,o);let H=me(v);return K(H)?ne(p,H,i,v.id??null,N.nextContext):fe(p,H,i,v,N.nextContext)},b={getSnapshot:()=>t,subscribe:n=>I?()=>{}:(C.add(n),()=>{C.delete(n)}),subscribeSelector:(n,o,p)=>{if(I)return()=>{};let i=p??Object.is,T=n(t);return b.subscribe(()=>{let u=n(t);if(i(T,u))return;let v=T;T=u,o(u,v)})},subscribeEvent:n=>{if(I)return()=>{};S.add(n);try{n(f)}catch(o){throw S.delete(n),o}return()=>{S.delete(n)}},subscribeStart:n=>b.subscribeEvent(o=>{o.type==="journey.start"&&n(o)}),subscribeComplete:n=>b.subscribeEvent(o=>{o.type==="journey.complete"&&n(o)}),subscribeTerminate:n=>b.subscribeEvent(o=>{o.type==="journey.close"&&n(o)}),resetMachine:()=>(I||(D(),t=_([e.initial],0,e.context,m.RUNNING,U(e.steps),s()),d?y():c(t),x()),t),updateContext:n=>(I||(t={...t,context:n(t.context)},c(t),x()),t),updateStepMetadata:(n,o)=>{if(I||!(n in e.steps))return t;let p=t.stepMeta[n],i=o(p);return Object.is(p,i)||(t={...t,stepMeta:{...t.stepMeta,[n]:i}},c(t),x(),l({type:"metadata.updated",stepId:n,previous:p,next:i,timestamp:J()})),t},clearStepError:n=>{if(I)return t;let o=n??t.currentStepId;return o in e.steps&&B(o),t},dispose:()=>{I||(I=!0,D(),C.clear(),S.clear())},goToPreviousStep:n=>k(async()=>te(n,"goToPreviousStep"),()=>P(t,!1)),goToLastVisitedStep:()=>k(async()=>Se("goToLastVisitedStep"),()=>P(t,!1)),goToNextStep:()=>b.send({type:"goToNextStep"}),terminateJourney:n=>n===void 0?b.send({type:"terminateJourney"}):b.send({type:"terminateJourney",payload:n}),completeJourney:n=>n===void 0?b.send({type:"completeJourney"}):b.send({type:"completeJourney",payload:n}),send:n=>k(async o=>Pe(n,o),A)};return b}var Te=e=>({to:(r,s={})=>({...s,to:r,...e?{when:e}:{}})}),ye=(e,r)=>r==="completeJourney"?{complete:(s={})=>({...s,from:e,event:r})}:r==="terminateJourney"?{terminate:(s={})=>({...s,from:e,event:r})}:{to:(s,d={})=>({...d,from:e,event:r,to:s}),choose:(...s)=>s.map(d=>({...d,from:e,event:r})),when:s=>Te(s),otherwise:()=>Te()},j=(e,r,s={})=>({...s,from:e,event:r}),de={from:e=>({on:r=>ye(e,r),toComplete:(r={})=>j(e,"completeJourney",r),toTerminate:(r={})=>j(e,"terminateJourney",r)}),any:()=>({on:e=>ye(w,e),toComplete:(e={})=>j(w,"completeJourney",e),toTerminate:(e={})=>j(w,"terminateJourney",e)}),when:e=>({to:(r,s={})=>({...s,to:r,when:e})}),otherwise:()=>({to:(e,r={})=>({...r,to:e})})},ue=(...e)=>e.flatMap(r=>Array.isArray(r)?[...r]:[r]);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