@rxova/journey-core 1.0.0-rc.2 → 1.0.0

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 (158) hide show
  1. package/README.md +182 -186
  2. package/dist/connectors/immer/immer.cjs +2 -0
  3. package/dist/connectors/immer/immer.cjs.map +7 -0
  4. package/dist/connectors/immer/immer.d.cts +11 -0
  5. package/dist/connectors/immer/immer.d.ts +11 -0
  6. package/dist/connectors/immer/immer.js +2 -0
  7. package/dist/connectors/immer/immer.js.map +7 -0
  8. package/dist/connectors/immer/immer.types.d.cts +9 -0
  9. package/dist/connectors/immer/immer.types.d.ts +9 -0
  10. package/dist/core/errors.d.cts +57 -0
  11. package/dist/core/errors.d.ts +57 -0
  12. package/dist/core/helpers.d.cts +46 -0
  13. package/dist/core/helpers.d.ts +46 -0
  14. package/dist/core/machine.d.cts +9 -0
  15. package/dist/core/machine.d.ts +9 -0
  16. package/dist/core/runtime.d.cts +115 -0
  17. package/dist/core/runtime.d.ts +115 -0
  18. package/dist/core/runtime.types.d.cts +112 -0
  19. package/dist/core/runtime.types.d.ts +112 -0
  20. package/dist/core/store.d.cts +31 -0
  21. package/dist/core/store.d.ts +31 -0
  22. package/dist/core/types.d.cts +481 -0
  23. package/dist/core/types.d.ts +481 -0
  24. package/dist/diagnostics/diagnostics.helpers.d.cts +17 -0
  25. package/dist/diagnostics/diagnostics.helpers.d.ts +17 -0
  26. package/dist/diagnostics/diagnostics.types.d.cts +22 -0
  27. package/dist/diagnostics/diagnostics.types.d.ts +22 -0
  28. package/dist/graph/bag.types.d.cts +91 -0
  29. package/dist/graph/bag.types.d.ts +91 -0
  30. package/dist/graph/graph.d.cts +63 -0
  31. package/dist/graph/graph.d.ts +63 -0
  32. package/dist/graph/graph.types.d.cts +212 -0
  33. package/dist/graph/graph.types.d.ts +212 -0
  34. package/dist/graph/work.d.cts +81 -0
  35. package/dist/graph/work.d.ts +81 -0
  36. package/dist/index.cjs +1 -1
  37. package/dist/index.cjs.map +4 -4
  38. package/dist/index.d.cts +13 -5
  39. package/dist/index.d.ts +13 -5
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +4 -4
  42. package/dist/linear/linear.d.cts +33 -0
  43. package/dist/linear/linear.d.ts +33 -0
  44. package/dist/linear/linear.types.d.cts +28 -0
  45. package/dist/linear/linear.types.d.ts +28 -0
  46. package/dist/plugins/analytics/analytics.d.cts +8 -0
  47. package/dist/plugins/analytics/analytics.d.ts +8 -0
  48. package/dist/plugins/analytics/analytics.helpers.d.cts +2 -0
  49. package/dist/plugins/analytics/analytics.helpers.d.ts +2 -0
  50. package/dist/plugins/analytics/analytics.types.d.cts +27 -0
  51. package/dist/plugins/analytics/analytics.types.d.ts +27 -0
  52. package/dist/plugins/execution-paths/execution-paths.d.cts +7 -4
  53. package/dist/plugins/execution-paths/execution-paths.d.ts +7 -4
  54. package/dist/plugins/execution-paths/execution-paths.types.d.cts +21 -0
  55. package/dist/plugins/execution-paths/execution-paths.types.d.ts +21 -0
  56. package/dist/plugins/index.cjs +2 -0
  57. package/dist/plugins/index.cjs.map +7 -0
  58. package/dist/plugins/index.d.cts +19 -0
  59. package/dist/plugins/index.d.ts +19 -0
  60. package/dist/plugins/index.js +2 -0
  61. package/dist/plugins/index.js.map +7 -0
  62. package/dist/plugins/persistence/persistence.d.cts +16 -0
  63. package/dist/plugins/persistence/persistence.d.ts +16 -0
  64. package/dist/plugins/persistence/persistence.helpers.d.cts +34 -0
  65. package/dist/plugins/persistence/persistence.helpers.d.ts +34 -0
  66. package/dist/plugins/persistence/persistence.types.d.cts +63 -0
  67. package/dist/plugins/persistence/persistence.types.d.ts +63 -0
  68. package/dist/plugins/replay/replay.d.cts +7 -0
  69. package/dist/plugins/replay/replay.d.ts +7 -0
  70. package/dist/plugins/replay/replay.helpers.d.cts +22 -0
  71. package/dist/plugins/replay/replay.helpers.d.ts +22 -0
  72. package/dist/plugins/replay/replay.types.d.cts +28 -0
  73. package/dist/plugins/replay/replay.types.d.ts +28 -0
  74. package/package.json +78 -79
  75. package/dist/journey-builder/index.d.cts +0 -5
  76. package/dist/journey-builder/index.d.ts +0 -5
  77. package/dist/journey-builder/types.d.cts +0 -126
  78. package/dist/journey-builder/types.d.ts +0 -126
  79. package/dist/journey-machine/async-state.d.cts +0 -12
  80. package/dist/journey-machine/async-state.d.ts +0 -12
  81. package/dist/journey-machine/computed.d.cts +0 -2
  82. package/dist/journey-machine/computed.d.ts +0 -2
  83. package/dist/journey-machine/controls.d.cts +0 -17
  84. package/dist/journey-machine/controls.d.ts +0 -17
  85. package/dist/journey-machine/helpers.d.cts +0 -52
  86. package/dist/journey-machine/helpers.d.ts +0 -52
  87. package/dist/journey-machine/index.d.cts +0 -3
  88. package/dist/journey-machine/index.d.ts +0 -3
  89. package/dist/journey-machine/navigation.d.cts +0 -32
  90. package/dist/journey-machine/navigation.d.ts +0 -32
  91. package/dist/journey-machine/plugin-controller.d.cts +0 -15
  92. package/dist/journey-machine/plugin-controller.d.ts +0 -15
  93. package/dist/journey-machine/resolve-journey-definition.d.cts +0 -2
  94. package/dist/journey-machine/resolve-journey-definition.d.ts +0 -2
  95. package/dist/journey-machine/runtime.d.cts +0 -33
  96. package/dist/journey-machine/runtime.d.ts +0 -33
  97. package/dist/journey-machine/send.d.cts +0 -9
  98. package/dist/journey-machine/send.d.ts +0 -9
  99. package/dist/plugins/analytics/index.cjs +0 -2
  100. package/dist/plugins/analytics/index.cjs.map +0 -7
  101. package/dist/plugins/analytics/index.d.cts +0 -25
  102. package/dist/plugins/analytics/index.d.ts +0 -25
  103. package/dist/plugins/analytics/index.js +0 -2
  104. package/dist/plugins/analytics/index.js.map +0 -7
  105. package/dist/plugins/autosave/index.cjs +0 -2
  106. package/dist/plugins/autosave/index.cjs.map +0 -7
  107. package/dist/plugins/autosave/index.d.cts +0 -17
  108. package/dist/plugins/autosave/index.d.ts +0 -17
  109. package/dist/plugins/autosave/index.js +0 -2
  110. package/dist/plugins/autosave/index.js.map +0 -7
  111. package/dist/plugins/diagnostics/diagnostics.d.cts +0 -3
  112. package/dist/plugins/diagnostics/diagnostics.d.ts +0 -3
  113. package/dist/plugins/diagnostics/index.cjs +0 -2
  114. package/dist/plugins/diagnostics/index.cjs.map +0 -7
  115. package/dist/plugins/diagnostics/index.d.cts +0 -15
  116. package/dist/plugins/diagnostics/index.d.ts +0 -15
  117. package/dist/plugins/diagnostics/index.js +0 -2
  118. package/dist/plugins/diagnostics/index.js.map +0 -7
  119. package/dist/plugins/execution-paths/index.cjs +0 -2
  120. package/dist/plugins/execution-paths/index.cjs.map +0 -7
  121. package/dist/plugins/execution-paths/index.d.cts +0 -18
  122. package/dist/plugins/execution-paths/index.d.ts +0 -18
  123. package/dist/plugins/execution-paths/index.js +0 -2
  124. package/dist/plugins/execution-paths/index.js.map +0 -7
  125. package/dist/plugins/persistence/controller.d.cts +0 -17
  126. package/dist/plugins/persistence/controller.d.ts +0 -17
  127. package/dist/plugins/persistence/index.cjs +0 -2
  128. package/dist/plugins/persistence/index.cjs.map +0 -7
  129. package/dist/plugins/persistence/index.d.cts +0 -12
  130. package/dist/plugins/persistence/index.d.ts +0 -12
  131. package/dist/plugins/persistence/index.js +0 -2
  132. package/dist/plugins/persistence/index.js.map +0 -7
  133. package/dist/plugins/replay/index.cjs +0 -2
  134. package/dist/plugins/replay/index.cjs.map +0 -7
  135. package/dist/plugins/replay/index.d.cts +0 -27
  136. package/dist/plugins/replay/index.d.ts +0 -27
  137. package/dist/plugins/replay/index.js +0 -2
  138. package/dist/plugins/replay/index.js.map +0 -7
  139. package/dist/types/analytics.types.d.cts +0 -33
  140. package/dist/types/analytics.types.d.ts +0 -33
  141. package/dist/types/autosave.types.d.cts +0 -23
  142. package/dist/types/autosave.types.d.ts +0 -23
  143. package/dist/types/diagnostics.types.d.cts +0 -38
  144. package/dist/types/diagnostics.types.d.ts +0 -38
  145. package/dist/types/index.d.cts +0 -9
  146. package/dist/types/index.d.ts +0 -9
  147. package/dist/types/journey.types.d.cts +0 -191
  148. package/dist/types/journey.types.d.ts +0 -191
  149. package/dist/types/machine.types.d.cts +0 -104
  150. package/dist/types/machine.types.d.ts +0 -104
  151. package/dist/types/observation.types.d.cts +0 -83
  152. package/dist/types/observation.types.d.ts +0 -83
  153. package/dist/types/persistence.types.d.cts +0 -34
  154. package/dist/types/persistence.types.d.ts +0 -34
  155. package/dist/types/replay.types.d.cts +0 -35
  156. package/dist/types/replay.types.d.ts +0 -35
  157. package/dist/types/transitions.types.d.cts +0 -122
  158. package/dist/types/transitions.types.d.ts +0 -122
@@ -0,0 +1,81 @@
1
+ import type { Bag, HandlersOf, MetaOf, ResultOf } from "./bag.types.js";
2
+ import type { GraphOnEntry, GraphTransition, SendWorkArgs } from "./graph.types.js";
3
+ import type { ContextUpdater, GraphSnapshot } from "../core/types.js";
4
+ /** The event an entry is declared under, narrowed out of the bag's union. */
5
+ type TriggerOf<TBag extends Bag, TType extends TBag["events"]["type"]> = Extract<TBag["events"], {
6
+ type: TType;
7
+ }>;
8
+ type WorkArgs<TBag extends Bag, TType extends TBag["events"]["type"]> = SendWorkArgs<TBag["stepId"], TriggerOf<TBag, TType>, GraphSnapshot<TBag["context"], TBag["stepId"], MetaOf<TBag>, TBag["events"]>, HandlersOf<TBag>>;
9
+ /**
10
+ * The config {@link defineWork} checks.
11
+ *
12
+ * The same shape as the object arm of {@link GraphOnEntry}, with two
13
+ * differences that only a function call can provide: `TResult` is a free type
14
+ * parameter here rather than a fixed argument, and `event` is narrowed to the
15
+ * key the entry is declared under.
16
+ */
17
+ export type WorkConfig<TBag extends Bag, TType extends TBag["events"]["type"], TResult> = {
18
+ readonly run: (args: WorkArgs<TBag, TType>) => TResult | Promise<TResult>;
19
+ readonly commit?: (args: WorkArgs<TBag, TType> & {
20
+ readonly result: TResult;
21
+ readonly updateContext: (updater: ContextUpdater<TBag["context"]>) => void;
22
+ }) => void;
23
+ /** Names this work in timeout and error messages. */
24
+ readonly label?: string;
25
+ /** Budget for `run`, overriding `defaultTimeoutMs`. */
26
+ readonly timeoutMs?: number;
27
+ /**
28
+ * Guards here stay total functions of context, as everywhere else: the run
29
+ * result reaches them only through the context `commit` stages. Routing
30
+ * directly on the result was removed in v2 because the same guards run during
31
+ * snapshot derivation, where no send is in flight — `availableEvents` would
32
+ * then disagree with what a send actually does.
33
+ */
34
+ readonly candidates: readonly GraphTransition<TBag["context"], TBag["stepId"], TBag["events"], HandlersOf<TBag>, MetaOf<TBag>, TriggerOf<TBag, TType>>[];
35
+ };
36
+ /**
37
+ * Declares an event's async so that `run`'s return type flows into `commit` and
38
+ * into the candidates' guards.
39
+ *
40
+ * Written straight into a definition, `run` sits at a property position, which
41
+ * is not an inference site — so `result` is `unknown` unless the type is
42
+ * restated in the bag's `results`. Pinning it there works, but it is a second
43
+ * place to keep in sync, and it is one result type per event name rather than
44
+ * per (step, event) pair. Passing the same config through a generic function
45
+ * call puts `TResult` back at an inference site, so it is read off `run` and
46
+ * nothing needs restating:
47
+ *
48
+ * ```ts
49
+ * on: {
50
+ * SUBMIT: defineWork<AuthBag, "SUBMIT">()({
51
+ * run: ({ handlers }) => handlers.login(), // TResult inferred here
52
+ * commit: ({ result, updateContext }) => // ...and typed here
53
+ * updateContext((c) => ({ ...c, token: result.token, needsTwoFactor: result.twoFactor })),
54
+ * timeoutMs: 10_000,
55
+ * candidates: [
56
+ * { to: "twofa", label: "needs-2fa", when: ({ context }) => context.needsTwoFactor },
57
+ * { to: "home", label: "logged-in" }
58
+ * ]
59
+ * })
60
+ * }
61
+ * ```
62
+ *
63
+ * The call is curried because TypeScript infers all of a call's type arguments
64
+ * or none: naming the bag and the event inline would opt `TResult` out of
65
+ * inference too, which is the problem being solved. The empty second call is
66
+ * the price of pinning the first two and inferring the third.
67
+ *
68
+ * Pairs with a bag, so reach for it through `withGraphTypes<TBag>()` rather
69
+ * than plain `createGraphJourney`: the bag is where `stepId`, `events` and
70
+ * `handlers` come from, and a definition that infers those itself will not line
71
+ * up with them.
72
+ *
73
+ * At runtime this returns its argument unchanged. The cast is what erases the
74
+ * narrowed `event` and the inferred `TResult` back down to the slot's wider
75
+ * shape — `commit`'s `result` sits at a contravariant position, so a pinned
76
+ * config cannot be assigned into an `unknown` slot directly. That is the same
77
+ * erasure the v1 builder did, and it is sound because the config has already
78
+ * been checked, against sharper types, at this call site.
79
+ */
80
+ export declare const defineWork: <TBag extends Bag, TType extends TBag["events"]["type"] = TBag["events"]["type"]>() => <TResult>(config: WorkConfig<TBag, TType, TResult>) => GraphOnEntry<TBag["context"], TBag["stepId"], TBag["events"], HandlersOf<TBag>, MetaOf<TBag>, ResultOf<TBag, TType>, TriggerOf<TBag, TType>>;
81
+ export {};
@@ -0,0 +1,81 @@
1
+ import type { Bag, HandlersOf, MetaOf, ResultOf } from "./bag.types.js";
2
+ import type { GraphOnEntry, GraphTransition, SendWorkArgs } from "./graph.types.js";
3
+ import type { ContextUpdater, GraphSnapshot } from "../core/types.js";
4
+ /** The event an entry is declared under, narrowed out of the bag's union. */
5
+ type TriggerOf<TBag extends Bag, TType extends TBag["events"]["type"]> = Extract<TBag["events"], {
6
+ type: TType;
7
+ }>;
8
+ type WorkArgs<TBag extends Bag, TType extends TBag["events"]["type"]> = SendWorkArgs<TBag["stepId"], TriggerOf<TBag, TType>, GraphSnapshot<TBag["context"], TBag["stepId"], MetaOf<TBag>, TBag["events"]>, HandlersOf<TBag>>;
9
+ /**
10
+ * The config {@link defineWork} checks.
11
+ *
12
+ * The same shape as the object arm of {@link GraphOnEntry}, with two
13
+ * differences that only a function call can provide: `TResult` is a free type
14
+ * parameter here rather than a fixed argument, and `event` is narrowed to the
15
+ * key the entry is declared under.
16
+ */
17
+ export type WorkConfig<TBag extends Bag, TType extends TBag["events"]["type"], TResult> = {
18
+ readonly run: (args: WorkArgs<TBag, TType>) => TResult | Promise<TResult>;
19
+ readonly commit?: (args: WorkArgs<TBag, TType> & {
20
+ readonly result: TResult;
21
+ readonly updateContext: (updater: ContextUpdater<TBag["context"]>) => void;
22
+ }) => void;
23
+ /** Names this work in timeout and error messages. */
24
+ readonly label?: string;
25
+ /** Budget for `run`, overriding `defaultTimeoutMs`. */
26
+ readonly timeoutMs?: number;
27
+ /**
28
+ * Guards here stay total functions of context, as everywhere else: the run
29
+ * result reaches them only through the context `commit` stages. Routing
30
+ * directly on the result was removed in v2 because the same guards run during
31
+ * snapshot derivation, where no send is in flight — `availableEvents` would
32
+ * then disagree with what a send actually does.
33
+ */
34
+ readonly candidates: readonly GraphTransition<TBag["context"], TBag["stepId"], TBag["events"], HandlersOf<TBag>, MetaOf<TBag>, TriggerOf<TBag, TType>>[];
35
+ };
36
+ /**
37
+ * Declares an event's async so that `run`'s return type flows into `commit` and
38
+ * into the candidates' guards.
39
+ *
40
+ * Written straight into a definition, `run` sits at a property position, which
41
+ * is not an inference site — so `result` is `unknown` unless the type is
42
+ * restated in the bag's `results`. Pinning it there works, but it is a second
43
+ * place to keep in sync, and it is one result type per event name rather than
44
+ * per (step, event) pair. Passing the same config through a generic function
45
+ * call puts `TResult` back at an inference site, so it is read off `run` and
46
+ * nothing needs restating:
47
+ *
48
+ * ```ts
49
+ * on: {
50
+ * SUBMIT: defineWork<AuthBag, "SUBMIT">()({
51
+ * run: ({ handlers }) => handlers.login(), // TResult inferred here
52
+ * commit: ({ result, updateContext }) => // ...and typed here
53
+ * updateContext((c) => ({ ...c, token: result.token, needsTwoFactor: result.twoFactor })),
54
+ * timeoutMs: 10_000,
55
+ * candidates: [
56
+ * { to: "twofa", label: "needs-2fa", when: ({ context }) => context.needsTwoFactor },
57
+ * { to: "home", label: "logged-in" }
58
+ * ]
59
+ * })
60
+ * }
61
+ * ```
62
+ *
63
+ * The call is curried because TypeScript infers all of a call's type arguments
64
+ * or none: naming the bag and the event inline would opt `TResult` out of
65
+ * inference too, which is the problem being solved. The empty second call is
66
+ * the price of pinning the first two and inferring the third.
67
+ *
68
+ * Pairs with a bag, so reach for it through `withGraphTypes<TBag>()` rather
69
+ * than plain `createGraphJourney`: the bag is where `stepId`, `events` and
70
+ * `handlers` come from, and a definition that infers those itself will not line
71
+ * up with them.
72
+ *
73
+ * At runtime this returns its argument unchanged. The cast is what erases the
74
+ * narrowed `event` and the inferred `TResult` back down to the slot's wider
75
+ * shape — `commit`'s `result` sits at a contravariant position, so a pinned
76
+ * config cannot be assigned into an `unknown` slot directly. That is the same
77
+ * erasure the v1 builder did, and it is sound because the config has already
78
+ * been checked, against sharper types, at this call site.
79
+ */
80
+ export declare const defineWork: <TBag extends Bag, TType extends TBag["events"]["type"] = TBag["events"]["type"]>() => <TResult>(config: WorkConfig<TBag, TType, TResult>) => GraphOnEntry<TBag["context"], TBag["stepId"], TBag["events"], HandlersOf<TBag>, MetaOf<TBag>, ResultOf<TBag, TType>, TriggerOf<TBag, TType>>;
81
+ export {};
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var te=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var $e=(e,n)=>{for(var o in n)te(e,o,{get:n[o],enumerable:!0})},je=(e,n,o,p)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of He(n))!Pe.call(e,s)&&s!==o&&te(e,s,{get:()=>n[s],enumerable:!(p=Le(n,s))||p.enumerable});return e};var Be=e=>je(te({},"__esModule",{value:!0}),e);var Ke={};$e(Ke,{JourneyDisposedError:()=>G,createJourneyBuilder:()=>Ae,createJourneyMachine:()=>Re});module.exports=Be(Ke);var V=(e,n,o)=>{if(!(n in e))throw new Error(o)},Q=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),q=e=>Array.isArray(e)?e.map(n=>q(n)):Q(e)?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,q(o)])):e,pe=e=>{if(e===null)return"null";if(Array.isArray(e))return"array";if(typeof e=="object"){let n=e.constructor?.name;return n&&n!=="Object"?n:"object"}return typeof e};function oe(e,n,o,p=[]){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return;let s=p.length===0?n:`${n}.${p.join(".")}`;if(e===void 0)throw new Error(`${s} must be JSON-serializable. Received undefined.`);if(typeof e=="bigint"||typeof e=="symbol"||typeof e=="function")throw new Error(`${s} must be JSON-serializable. Received ${typeof e}.`);if(typeof e!="object")throw new Error(`${s} must be JSON-serializable. Received ${pe(e)}.`);if(o.seen.has(e))throw new Error(`${s} must be JSON-serializable. Circular references are not supported.`);if(o.seen.add(e),Array.isArray(e)){for(let[t,i]of e.entries())oe(i,n,o,[...p,String(t)]);return}if(!Q(e))throw new Error(`${s} must be JSON-serializable. Received non-plain ${pe(e)}.`);for(let[t,i]of Object.entries(e))oe(i,n,o,[...p,t])}function j(e,n="Journey context"){return oe(e,n,{seen:new WeakSet}),e}var B=e=>q(j(e)),_=e=>Array.isArray(e)?e.map(n=>_(n)):e instanceof Date?new Date(e.getTime()):e instanceof Map?new Map([...e.entries()].map(([n,o])=>[_(n),_(o)])):e instanceof Set?new Set([...e].map(n=>_(n))):Q(e)?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,_(o)])):e,ie=e=>{if(typeof e!="object"&&typeof e!="function"||e===null)return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{return _(e)}else return _(e)},re=e=>{if(!(typeof e!="object"||e===null||Object.isFrozen(e))){if(Array.isArray(e)){for(let n of e)re(n);Object.freeze(e);return}if(Q(e)){for(let n of Object.values(e))re(n);Object.freeze(e)}}},le=e=>typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.trunc(e)),b=()=>Date.now(),ye=e=>[...new Set(e)],De=(e,n)=>Object.fromEntries(n.map(o=>[o,e[o]===!0])),_e=(e,n)=>{let o=n??ye(e),p=Object.fromEntries(o.map(s=>[s,!1]));for(let s of e)p[s]=!0;return p},Ne=(e,n)=>({...e,[n]:!0}),ae=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function",Te=e=>typeof e=="number"&&Number.isFinite(e),z=(e,n)=>{if(e!==void 0&&!Te(e))throw new Error(`${n} must define a finite numeric "timeoutMs" when provided.`)},se=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}},ce=()=>{let e=globalThis;if(typeof e.__DEV__=="boolean")return e.__DEV__;let n=e.process?.env?.NODE_ENV;return n===void 0||n==="development"},X=(e,n)=>{if(!(!ce()||typeof console>"u")){if(n===void 0){console.warn(e);return}console.warn(e,n)}},Se=(e,n)=>{if(!(!ce()||typeof console>"u")){if(n===void 0){console.error(e);return}console.error(e,n)}},Fe=async(e,n,o)=>!Te(n)||n<=0?await e:await new Promise((p,s)=>{let t=setTimeout(()=>{s(o())},n);e.then(i=>{clearTimeout(t),p(i)},i=>{clearTimeout(t),s(i)})}),Ge=async(e,n)=>{if(n.aborted)throw n.reason;return await new Promise((o,p)=>{let s=()=>{n.removeEventListener("abort",s),p(n.reason)};n.addEventListener("abort",s,{once:!0}),e.then(t=>{n.removeEventListener("abort",s),o(t)},t=>{n.removeEventListener("abort",s),p(t)})})},Y=()=>({phase:"idle",eventType:null,transitionId:null,error:null}),Z=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(o=>[o,Y()]))}),ee=e=>e.type==="goToStepById"&&"stepId"in e,K=e=>e==="COMPLETE"||e==="TERMINATED",fe=e=>e.event==="completeJourney"?"COMPLETE":e.event==="terminateJourney"?"TERMINATED":e.to,Je=(e,n)=>{let o=n,p=new Set(["from","event","to","when","updateContext","onEnter","onLeave","id","label","timeoutMs"]);for(let[s,t]of e.entries()){if(!t||typeof t!="object")throw new Error(`Journey transition at index ${s} must be an object.`);for(let i of Object.keys(t))if(!p.has(i))throw new Error(`Journey transition at index ${s} contains unsupported field "${i}".`);if(typeof t.from!="string"||typeof t.event!="string")throw new Error(`Journey transition at index ${s} must define string "from" and "event".`);if(t.from!=="*"&&!(t.from in o))throw new Error(`Journey transition at index ${s} references unknown from step "${t.from}".`);if(z(t.timeoutMs,`Journey transition at index ${s}`),t.when!==void 0&&typeof t.when!="function")throw new Error(`Journey transition at index ${s} must define "when" as a function when provided.`);if(t.updateContext!==void 0&&typeof t.updateContext!="function")throw new Error(`Journey transition at index ${s} must define "updateContext" as a function when provided.`);if(t.onEnter!==void 0&&typeof t.onEnter!="function")throw new Error(`Journey transition at index ${s} must define "onEnter" as a function when provided.`);if(t.onLeave!==void 0&&typeof t.onLeave!="function")throw new Error(`Journey transition at index ${s} must define "onLeave" as a function when provided.`);if(t.id!==void 0&&typeof t.id!="string")throw new Error(`Journey transition at index ${s} must define "id" as a string when provided.`);if(t.label!==void 0&&typeof t.label!="string")throw new Error(`Journey transition at index ${s} must define "label" as a string when provided.`);if(t.event==="completeJourney"||t.event==="terminateJourney"){if("to"in t&&t.to!==void 0)throw new Error(`Journey transition at index ${s} with event "${t.event}" cannot define "to".`);continue}if(typeof t.to!="string")throw new Error(`Journey transition at index ${s} with event "${t.event}" must define string "to".`);if(!K(t.to)&&!(t.to in o))throw new Error(`Journey transition at index ${s} points to unknown step "${t.to}".`)}},k=(e,n,o={})=>({transitioned:n,...o.transitionId!==void 0?{transitionId:o.transitionId}:{},...o.label!==void 0?{label:o.label}:{},..."error"in o?{error:o.error}:{},snapshot:e}),D=(e,n,o,p,s,t)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let i=Math.max(0,Math.min(Math.trunc(n),e.length-1)),r=e[i],d=ye(t?[...Object.keys(t),...e]:e);return{status:p,currentStepId:r,history:{timeline:[...e],index:i},context:B(o),visited:t?De(t,d):_e(e,d),async:q(s)}},H=e=>{let n={...e,history:{timeline:[...e.history.timeline],index:e.history.index},context:B(e.context),visited:{...e.visited},async:q(e.async)};return re(n),n},xe=async(e,n,o,p,s,t,i)=>{for(let r of e){let d=r.from==="*"||r.from===n.currentStepId,l=r.event===o.type;if(!d||!l)continue;if(!r.when)return r;let y;if(p.aborted)throw p.reason;y=r.when({snapshot:n,context:n.context,from:n.currentStepId,timeline:n.history.timeline,index:n.history.index,event:o,signal:p,handlers:s});let a=ae(y),u=a?y:null,E;try{a?(t?.onAsyncGuardStart?.(r),E=await Fe(Ge(u,p),r.timeoutMs??i,()=>new se(`Transition guard timed out after ${r.timeoutMs??i}ms (event: ${o.type}, transition: ${r.id??"<anonymous>"}).`))):E=y}catch(g){throw a&&t?.onAsyncGuardError?.(r,g),g}if(a&&t?.onAsyncGuardSuccess?.(r),E)return r}return null},me=(e,n,o)=>{let p=e.history.timeline.slice(0,e.history.index+1),s=p;n!==e.currentStepId&&(s=[...p,n]);let t=s.length-1,i=Ne(e.visited,n);return D(s,t,o,e.status,e.async,i)};var he=({runtime:e})=>{let n=i=>i==="evaluating-when",o=i=>Object.values(i.byStep).reduce((r,d)=>r+(n(d.phase)?1:0),0),p=o(e.peekSnapshot().async),s=i=>{p=o(i)},t=(i,r,d)=>{if(d!==void 0&&!e.isRunActive(d))return;let l=e.peekSnapshot(),y=l.async.byStep[i]??Y(),a=r(y);if(y.phase===a.phase&&y.eventType===a.eventType&&y.transitionId===a.transitionId&&y.error===a.error)return;let u={...l.async.byStep,[i]:a},E=n(y.phase),g=n(a.phase),P=E===g?p:p+(g?1:-1);e.setSnapshot({...l,async:{isLoading:P>0,byStep:u}},{notify:!0,reason:"async"}),p=P};return{syncState:s,updateStepAsync:t,setStepLoading:(i,r,d,l,y)=>{t(i,()=>({phase:r,eventType:d,transitionId:l??null,error:null}),y)},setStepIdle:(i,r)=>{t(i,()=>Y(),r)},setStepError:(i,r,d,l,y)=>{t(i,()=>({phase:"error",eventType:r,transitionId:l??null,error:d}),y)}}};var Ve=e=>e.map(n=>typeof n=="string"?n:n.step),ze=e=>{let n=0;for(let o in e)e[o]&&(n+=1);return n},ve=(e,n,o)=>{let p=e.transitions===void 0?"headless":Array.isArray(e.transitions)?"linear":"graph",s=p==="linear"?Ve(e.transitions):null;return()=>{let t=o(),i=t.history.index,r={activeStepId:t.currentStepId,activeStepIndex:i,visitedStepCount:ze(t.visited),isLoading:t.async.isLoading,isIdle:t.status==="idled",isRunning:t.status==="running",isComplete:t.status==="completed",isTerminated:t.status==="terminated",isInitialStep:t.currentStepId===n.initial};if(p==="linear"&&s!==null){let d=s.length,l=s.indexOf(t.currentStepId);return{...r,activeStepIndex:l===-1?i:l,mode:"linear",stepCount:d,journeyLength:d,isFirstStep:l===0,isLastStep:l===d-1,stepOrder:s}}return p==="graph"?{...r,mode:"graph"}:{...r,mode:"headless"}}};var Ee=({runtime:e,asyncState:n,initial:o,initialContext:p,steps:s})=>{let t=r=>{X(`Journey machine has been disposed; "${r}" is a no-op.`)},i=()=>D([o],0,B(p),"idled",Z(s));return{startJourney:()=>e.isDisposed()?(t("startJourney"),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:b()}),e.getSnapshot()},()=>e.getSnapshot()),resetJourney:()=>e.isDisposed()?(t("resetJourney"),Promise.resolve(e.getSnapshot())):(e.cancelInFlight(),e.queue(async()=>{let r=e.setSnapshot(i(),{notify:!0,reason:"reset"});return e.emit({type:"journey.reset",stepId:r.currentStepId,timestamp:b()}),n.syncState(r.async),e.getSnapshot()},()=>e.getSnapshot())),updateContext:r=>e.isDisposed()?(t("updateContext"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let d=e.peekSnapshot(),l=j(r(B(d.context)));return e.setSnapshot({...d,context:l},{notify:!0,reason:"context"})},()=>e.getSnapshot()),clearStepError:r=>e.isDisposed()?(t("clearStepError"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let d=e.peekSnapshot(),l=r??d.currentStepId;return l in s&&n.setStepIdle(l),e.getSnapshot()},()=>e.getSnapshot()),dispose:()=>{e.dispose()}}};var be=({runtime:e,steps:n,transitions:o,scheduleLifecycle:p})=>({applyPreviousNavigation:(s,t,i=0)=>{let r=e.peekSnapshot();if(r.status!=="running")return k(e.getSnapshot(),!1);let d=le(s);if(r.history.index===0)return k(e.getSnapshot(),!1);let l=r.currentStepId,y=Math.max(0,r.history.index-d),a=r.history.index-y;if(a<=0)return k(e.getSnapshot(),!1);e.emit({type:"step.exit",stepId:l,timestamp:b()});let u=e.setSnapshot(D(r.history.timeline,y,r.context,r.status,r.async,r.visited),{notify:!0,reason:"navigation"});return e.emit({type:"navigation.previous",from:l,to:u.currentStepId,requestedSteps:d,appliedSteps:a,timestamp:b()}),e.emit({type:"step.enter",stepId:u.currentStepId,timestamp:b()}),p({previousSnapshot:r,snapshot:u,from:l,to:u.currentStepId,event:{type:"goToPreviousStep"},transitionId:t??null,runVersion:i}),k(u,!0,{...t!==void 0?{transitionId:t}:{}})},applyLastVisitedNavigation:(s,t=0)=>{let i=e.peekSnapshot();if(i.status!=="running")return k(e.getSnapshot(),!1);let r=i.history.timeline.length-1;if(i.history.index>=r)return k(e.getSnapshot(),!1);let d=i.currentStepId;e.emit({type:"step.exit",stepId:d,timestamp:b()});let l=e.setSnapshot(D(i.history.timeline,r,i.context,i.status,i.async,i.visited),{notify:!0,reason:"navigation"});return e.emit({type:"navigation.lastVisited",from:d,to:l.currentStepId,timestamp:b()}),e.emit({type:"step.enter",stepId:l.currentStepId,timestamp:b()}),p({previousSnapshot:i,snapshot:l,from:d,to:l.currentStepId,event:{type:"goToLastVisitedStep"},transitionId:s??null,runVersion:t}),k(l,!0,{...s!==void 0?{transitionId:s}:{}})},hasDeclaredTransitionForEvent:(s,t)=>o.some(i=>(i.from==="*"||i.from===s)&&i.event===t),commitTerminalTransition:(s,t,i,r,d,l,y=0)=>{let a=e.peekSnapshot(),u=a.history.timeline.slice(0,a.history.index+1),E=e.setSnapshot({...a,history:{timeline:u,index:u.length-1},context:l,status:t==="COMPLETE"?"completed":"terminated"},{notify:!0,reason:"transition"});return e.emit({type:"transition.success",from:s,to:t,eventType:i.type,transitionId:r,...d?.label!==void 0?{label:d.label}:{},timestamp:b()}),e.emit({type:t==="COMPLETE"?"journey.completed":"journey.terminated",stepId:E.currentStepId,timestamp:b()}),p({previousSnapshot:a,snapshot:E,from:s,to:t,event:i,transitionId:r,...d?.label!==void 0?{label:d.label}:{},runVersion:y,...d!==void 0?{transition:d}:{}}),k(E,!0,{...r!==null?{transitionId:r}:{},...d?.label!==void 0?{label:d.label}:{}})},commitStepTransition:(s,t,i,r,d,l=0)=>{V(n,t,`Transition points to unknown step "${t}".`);let y=e.peekSnapshot(),a=y.currentStepId;a!==t&&e.emit({type:"step.exit",stepId:a,timestamp:b()});let u=e.setSnapshot(me(y,t,d),{notify:!0,reason:"transition"});return e.emit({type:"transition.success",from:s,to:u.currentStepId,eventType:i.type,transitionId:r.id,...r.label!==void 0?{label:r.label}:{},timestamp:b()}),a!==u.currentStepId&&e.emit({type:"step.enter",stepId:u.currentStepId,timestamp:b()}),p({previousSnapshot:y,snapshot:u,from:s,to:u.currentStepId,event:i,transitionId:r.id,...r.label!==void 0?{label:r.label}:{},runVersion:l,transition:r}),k(u,!0,{transitionId:r.id,...r.label!==void 0?{label:r.label}:{}})}});var ge=({plugins:e,setupContext:n})=>{let o=[];for(let p of e)try{o.push({name:p.name,hooks:p.setup(n)})}catch(s){for(let r of[...o].reverse())try{r.hooks.dispose?.()}catch{}let t=s instanceof Error?s.message:String(s),i=new Error(`Journey plugin "${p.name}" setup failed: ${t}`);throw Object.assign(i,{cause:s}),i}return{hydrateSnapshot:p=>o.reduce((s,t)=>t.hooks.hydrateSnapshot?.(s)??s,p),onSnapshotChange:({previousSnapshot:p,snapshot:s,reason:t})=>{let i;for(let r of o)try{let d=r.hooks.onSnapshotChange?.({previousSnapshot:p,snapshot:s,reason:t});ae(d)&&X(`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){i??(i=d)}if(i!==void 0)throw i},extendMachine:p=>{let s=p,t=p,i=new Map;for(let r of o){let d=r.hooks.augmentMachine?.({machine:p,journey:n.journey,resolvedJourney:n.resolvedJourney});if(d)for(let[l,y]of Object.entries(d)){let a=i.get(l);if(a)throw new Error(`Journey plugin "${r.name}" cannot add "${l}" \u2014 already provided by plugin "${a}".`);if(l in s)throw new Error(`Journey plugin "${r.name}" cannot override machine property "${l}".`);i.set(l,r.name),t[l]=y}}return s},dispose:()=>{let p;for(let s of o)try{s.hooks.dispose?.()}catch(t){p??(p=t)}if(p!==void 0)throw p}}};var Ie=({snapshot:e,onSnapshotChange:n,onDispose:o,onListenerError:p})=>{let s=H(e),t=H(s),i=new Set,r=new Set,d=Promise.resolve(),l=0,y=!1,a=null,u=new Set,E=p??((f,v)=>{Se(`Journey ${v} listener threw an error.`,f)}),g=()=>{for(let f of i)try{f()}catch(v){E(v,"snapshot")}},P=f=>{for(let v of r)try{v(f)}catch(C){E(C,"event")}},c=(f,v={})=>{let C=t,R=H(f),A=H(R);return n?.({previousSnapshot:H(C),snapshot:H(A),reason:v.reason??"transition"}),s=R,t=A,v.notify&&g(),A},S=f=>!y&&f===l,J=()=>{l+=1,a&&!a.signal.aborted&&a.abort(),a=null;for(let f of u)f.signal.aborted||f.abort();u.clear(),d=Promise.resolve()},x=f=>{if(!S(f))return null;let v=new AbortController;return S(f)?(u.add(v),v):(v.abort(),null)},h=f=>{u.delete(f)},T=(f,v)=>{let C=l,R=async()=>{if(!S(C))return v();let L=new AbortController;a=L;try{return S(C)?await f(C,L.signal):(L.abort(),v())}finally{a===L&&(a=null)}},A=d.then(R,R);return d=A.then(()=>{},()=>{}),A},m=f=>y?()=>{}:(i.add(f),()=>{i.delete(f)});return{getSnapshot:()=>t,peekSnapshot:()=>s,setSnapshot:c,isDisposed:()=>y,isRunActive:S,cancelInFlight:J,openLifecycle:x,closeLifecycle:h,queue:T,notify:g,emit:P,subscribe:m,subscribeSelector:(f,v,C)=>{if(y)return()=>{};let R=C??Object.is,A=f(t);return m(()=>{let L=f(t);if(R(A,L))return;let F=A;A=L,v(L,F)})},subscribeEvent:f=>y?()=>{}:(r.add(f),()=>{r.delete(f)}),dispose:()=>{y||(y=!0,J(),i.clear(),r.clear(),o?.())}}};var Ce=(e,n,o,p,s,t,i,r,d)=>{let l=(c="send")=>k(e.getSnapshot(),!1,{...e.isDisposed()?{error:new G(c)}:{}}),y=(c,S,J)=>k(e.getSnapshot(),!1,{...S!==void 0?{transitionId:S}:{},...J!==void 0?{label:J}:{},error:c}),a=(c,S,J,x,h,T,m=!1)=>(m||n.setStepError(c,S,J,x??void 0,T),e.emit({type:"transition.error",from:c,eventType:S,transitionId:x,...h!==void 0?{label:h}:{},error:J,timestamp:b()}),y(J,x??void 0,h)),u=(c,S)=>ee(c)?(V(s,c.stepId,`Cannot goToStepById unknown step "${c.stepId}".`),{transitionsToEvaluate:t.filter(J=>(J.from==="*"||J.from===S)&&J.event==="goToStepById"&&"to"in J&&J.to===c.stepId),earlyResult:null}):{transitionsToEvaluate:t,earlyResult:null},E=async(c,S,J,x,h)=>{let T,m=null,I,M=!1;try{T=await xe(c,H(e.peekSnapshot()),S,h,i,{onAsyncGuardStart:w=>{n.setStepLoading(J,"evaluating-when",S.type,w.id,x)},onAsyncGuardSuccess:()=>{n.setStepIdle(J,x)},onAsyncGuardError:(w,f)=>{m=w.id??null,I=w.label,M=!0,n.setStepError(J,S.type,f,w.id,x)}},d)}catch(w){return e.isRunActive(x)?{transition:null,earlyResult:a(J,S.type,w,m,I,x,M)}:{transition:null,earlyResult:l(S.type)}}return{transition:T,earlyResult:null}},g=(c,S,J)=>{if(ee(c))return l(c.type);if(c.type==="goToPreviousStep"){let x=o.applyPreviousNavigation(1,c.type,J);return x.transitioned&&e.emit({type:"transition.success",from:S,to:x.snapshot.currentStepId,eventType:c.type,transitionId:null,timestamp:b()}),x}return c.type==="goToNextStep"&&!r&&!o.hasDeclaredTransitionForEvent(S,"goToNextStep")||c.type==="completeJourney"&&!o.hasDeclaredTransitionForEvent(S,"completeJourney")?o.commitTerminalTransition(S,"COMPLETE",c,null,void 0,e.peekSnapshot().context,J):c.type==="terminateJourney"&&!o.hasDeclaredTransitionForEvent(S,"terminateJourney")?o.commitTerminalTransition(S,"TERMINATED",c,null,void 0,e.peekSnapshot().context,J):l(c.type)},P=(c,S,J,x)=>{let h=e.peekSnapshot();if(!c.updateContext)return{nextContext:h.context,earlyResult:null};try{let T=c.updateContext({snapshot:H(h),context:h.context,from:h.currentStepId,timeline:h.history.timeline,index:h.history.index,event:S});return{nextContext:j(T),earlyResult:null}}catch(T){return e.isRunActive(x)?{nextContext:null,earlyResult:a(J,S.type,T,c.id,c.label,x)}:{nextContext:null,earlyResult:l(S.type)}}};return{buildCanceledSendResult:l,executeSend:async(c,S,J)=>{if(e.peekSnapshot().status!=="running")return l(c.type);let x=e.peekSnapshot().currentStepId,h=c;if(e.emit({type:"transition.start",from:x,event:c,timestamp:b()}),p){if(ee(c))return o.commitStepTransition(x,c.stepId,h,{from:x,event:"goToStepById",to:c.stepId},e.peekSnapshot().context,S);if(c.type!=="completeJourney"&&c.type!=="terminateJourney"&&c.type!=="goToPreviousStep")return l(c.type)}let T=u(c,x);if(T.earlyResult)return T.earlyResult;let m=await E(T.transitionsToEvaluate,h,x,S,J);if(m.earlyResult)return m.earlyResult;if(!e.isRunActive(S))return l(c.type);let{transition:I}=m;if(!I)return g(c,x,S);n.setStepIdle(x,S);let M=P(I,h,x,S);if(M.earlyResult)return M.earlyResult;let w=fe(I);return K(w)?o.commitTerminalTransition(x,w,h,I.id??null,I,M.nextContext,S):o.commitStepTransition(x,w,h,I,M.nextContext,S)}}};var we=e=>{let n=2166136261;for(let o=0;o<e.length;o+=1)n^=e.charCodeAt(o),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")},de=e=>{let n=new Map,o=new Set;return e.map(p=>{let s=p.event==="completeJourney"?"COMPLETE":p.event==="terminateJourney"?"TERMINATED":String(p.to),t=JSON.stringify({from:p.from,event:p.event,target:s}),i=(n.get(t)??0)+1;n.set(t,i);let r=JSON.stringify({from:p.from,event:p.event,target:s,ordinal:i}),d=0,l=(()=>{let y=we(r);for(;o.has(y);)d+=1,y=we(`${r}:${d}`);return y})();return o.add(l),{...p,id:l,...p.label!==void 0?{label:p.label}:{}}})},Me=e=>{let n=[],{transitions:o}=e;if(o===void 0)return{...e,transitions:de(n)};if(Array.isArray(o)){if(o.length===0)throw new Error("Journey linear transitions must include the initial step as the first item.");let[t,...i]=o;if(typeof t!="string")throw new Error("Journey linear transitions at index 0 must be a step id string.");if(!(t in e.steps))throw new Error(`Journey linear transitions reference unknown step "${t}".`);let r=e.initial??t;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=t,l=new Set([t]);for(let[y,a]of i.entries()){let u=y+1;if(typeof a=="string"){if(!(a in e.steps))throw new Error(`Journey linear transitions reference unknown step "${a}".`);if(l.has(a))throw new Error(`Journey linear transitions contain duplicate step "${a}" at index ${u}.`);l.add(a),n.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 ${u} must be a step id string or step config object.`);let E=new Set(["step","label","updateContext","onEnter","onLeave","timeoutMs"]);for(let g of Object.keys(a))if(!E.has(g))throw new Error(`Journey linear transition object at index ${u} contains unsupported field "${g}". Allowed fields are "step", "label", "updateContext", "onEnter", "onLeave", and "timeoutMs".`);if(typeof a.step!="string")throw new Error(`Journey linear transition object at index ${u} must define string "step".`);if(!(a.step in e.steps))throw new Error(`Journey linear transitions reference unknown step "${a.step}".`);if(l.has(a.step))throw new Error(`Journey linear transitions contain duplicate step "${a.step}" at index ${u}.`);if(l.add(a.step),a.updateContext!==void 0&&typeof a.updateContext!="function")throw new Error(`Journey linear transition object at index ${u} 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 ${u} 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 ${u} must define "onLeave" as a function when provided.`);z(a.timeoutMs,`Journey linear transition object at index ${u}`),n.push({...a.label!==void 0?{label:a.label}:{},...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:de(n)}}if(!o||typeof o!="object")throw new Error("Journey transitions must be an array or an object map when provided.");let p=o,s=[...Object.entries(p).filter(([t])=>t!=="global"),...p.global?[["global",p.global]]:[]];for(let[t,i]of s){if(t!=="global"&&!(t in e.steps))throw new Error(`Journey transitions reference unknown step "${t}".`);if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`Journey transitions for "${t}" must be an event map object.`);for(let[r,d]of Object.entries(i)){let l=r==="completeJourney"||r==="terminateJourney",y=l&&(d===!0||Array.isArray(d)&&d.length===0)?[{}]:d;if(!Array.isArray(y))throw new Error(`Journey transitions for "${t}.${r}" must be an array.`);for(let[a,u]of y.entries()){if(!u||typeof u!="object")throw new Error(`Journey transition at "${t}.${r}[${a}]" must be an object.`);let E=new Set(l?["when","updateContext","onEnter","onLeave","label","timeoutMs"]:["to","when","updateContext","onEnter","onLeave","label","timeoutMs"]);for(let g of Object.keys(u))if(!E.has(g))throw new Error(`Journey transition at "${t}.${r}[${a}]" contains unsupported field "${g}".`);if(!l&&typeof u.to!="string")throw new Error(`Journey transition at "${t}.${r}[${a}]" must define string "to".`);if(u.when!==void 0&&typeof u.when!="function")throw new Error(`Journey transition at "${t}.${r}[${a}]" must define "when" as a function when provided.`);if(u.updateContext!==void 0&&typeof u.updateContext!="function")throw new Error(`Journey transition at "${t}.${r}[${a}]" must define "updateContext" as a function when provided.`);if(u.onEnter!==void 0&&typeof u.onEnter!="function")throw new Error(`Journey transition at "${t}.${r}[${a}]" must define "onEnter" as a function when provided.`);if(u.onLeave!==void 0&&typeof u.onLeave!="function")throw new Error(`Journey transition at "${t}.${r}[${a}]" must define "onLeave" as a function when provided.`);if(u.label!==void 0&&typeof u.label!="string")throw new Error(`Journey transition at "${t}.${r}[${a}]" must define "label" as a string when provided.`);z(u.timeoutMs,`Journey transition at "${t}.${r}[${a}]"`),n.push({...u,from:t==="global"?"*":t,event:r})}}}return{...e,transitions:de(n)}};function Re(e,n){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 T of Object.keys(e.steps))if(T==="*"||T==="global"||T==="COMPLETE"||T==="TERMINATED")throw new Error(`Step id "${T}" 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.');j(e.context);let o=Me(e);V(o.steps,o.initial,`Journey initial step "${o.initial}" does not exist in steps registry.`),Je(o.transitions,o.steps);let p=n?.requireExplicitCompletion??!1;z(n?.defaultTimeoutMs,"Journey machine options");let s=n?.defaultTimeoutMs,t=B(o.context),i=Object.fromEntries(Object.keys(o.steps).map(T=>[T,ie(o.steps[T].meta)])),r=()=>D([o.initial],0,B(t),"idled",Z(o.steps)),d=ge({plugins:n?.plugins??[],setupContext:{journey:e,resolvedJourney:o,options:{requireExplicitCompletion:p,defaultTimeoutMs:s},buildInitialSnapshot:r}}),l=d.hydrateSnapshot(r());j(l.context,"Journey hydrated context");let y=n?.onListenerError,a=n?.onLifecycleError,u=Ie({snapshot:l,onSnapshotChange:d.onSnapshotChange,onDispose:d.dispose,...y!==void 0?{onListenerError:y}:{}}),E=he({runtime:u}),g=()=>Promise.resolve(k(u.getSnapshot(),!1)),P=({previousSnapshot:T,snapshot:m,from:I,to:M,event:w,transitionId:f,label:v,runVersion:C,transition:R})=>{let A=o.steps[I],L=K(M)?null:o.steps[M],F=o.handlers??{},U=O=>!u.isRunActive(C)||u.isDisposed()?Promise.resolve(k(u.getSnapshot(),!1)):g(O),ne=u.openLifecycle(C);if(!ne)return;let{signal:$}=ne,W=(O,Oe)=>{let ue={phase:Oe,from:I,to:M,eventType:w.type,transitionId:f,...v!==void 0?{label:v}:{}};u.emit({type:"lifecycle.error",...ue,error:O,timestamp:b()}),a?.(O,ue)};(async()=>{try{if(A?.onLeave)try{await A.onLeave({snapshot:T,context:T.context,from:I,to:M,event:w,transitionId:f,...v!==void 0?{label:v}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"step.onLeave");return}if(!u.isRunActive(C))return;if(R?.onLeave)try{await R.onLeave({snapshot:T,context:T.context,from:I,to:M,event:w,transitionId:f,...R.label!==void 0?{label:R.label}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"transition.onLeave");return}if(!u.isRunActive(C))return;if(L?.onEnter)try{await L.onEnter({snapshot:m,context:m.context,from:I,to:M,event:w,transitionId:f,...v!==void 0?{label:v}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"step.onEnter");return}if(!u.isRunActive(C))return;if(R?.onEnter)try{await R.onEnter({snapshot:m,context:m.context,from:I,to:M,event:w,transitionId:f,...R.label!==void 0?{label:R.label}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"transition.onEnter");return}}finally{u.closeLifecycle(ne)}})()},c=be({runtime:u,steps:o.steps,transitions:o.transitions,scheduleLifecycle:P}),S=Ce(u,E,c,e.transitions===void 0,o.steps,o.transitions,o.handlers??{},p,s),J=Ee({runtime:u,asyncState:E,initial:o.initial,initialContext:t,steps:o.steps}),x=ve(e,o,u.getSnapshot),h={getSnapshot:u.getSnapshot,getStepMeta:T=>ie(i[T]),getComputed:x,startJourney:J.startJourney,subscribe:u.subscribe,subscribeSelector:u.subscribeSelector,subscribeEvent:u.subscribeEvent,subscribeStart:T=>u.subscribeEvent(m=>{m.type==="journey.start"&&T(m)}),subscribeReset:T=>u.subscribeEvent(m=>{m.type==="journey.reset"&&T(m)}),subscribeComplete:T=>u.subscribeEvent(m=>{m.type==="journey.completed"&&T(m)}),subscribeTerminate:T=>u.subscribeEvent(m=>{m.type==="journey.terminated"&&T(m)}),resetJourney:J.resetJourney,updateContext:J.updateContext,clearStepError:J.clearStepError,dispose:J.dispose,goToPreviousStep:T=>u.queue(async m=>c.applyPreviousNavigation(T,"goToPreviousStep",m),()=>S.buildCanceledSendResult("goToPreviousStep")),goToLastVisitedStep:()=>u.queue(async T=>c.applyLastVisitedNavigation("goToLastVisitedStep",T),()=>S.buildCanceledSendResult("goToLastVisitedStep")),goToNextStep:()=>h.send({type:"goToNextStep"}),goToStepById:T=>h.send({type:"goToStepById",stepId:T}),terminateJourney:T=>T===void 0?h.send({type:"terminateJourney"}):h.send({type:"terminateJourney",payload:T}),completeJourney:T=>T===void 0?h.send({type:"completeJourney"}):h.send({type:"completeJourney",payload:T}),send:T=>u.queue((m,I)=>S.executeSend(T,m,I),()=>S.buildCanceledSendResult(T.type))};return g=h.send,d.extendMachine(h)}function N(e){return{_candidate:e,when(n){return N({...e,_when:n})},updateContext(n){return N({...e,_updateContext:n})},onEnter(n){return N({...e,_onEnter:n})},onLeave(n){return N({...e,_onLeave:n})},label(n){return N({...e,_label:n})},timeoutMs(n){return N({...e,_timeoutMs:n})}}}function ke(e){let n={to:e._to};return e._when!==void 0&&(n.when=e._when),e._updateContext!==void 0&&(n.updateContext=e._updateContext),e._onEnter!==void 0&&(n.onEnter=e._onEnter),e._onLeave!==void 0&&(n.onLeave=e._onLeave),e._label!==void 0&&(n.label=e._label),e._timeoutMs!==void 0&&(n.timeoutMs=e._timeoutMs),n}function qe(e){let n={};return e.when!==void 0&&(n.when=e.when),e.updateContext!==void 0&&(n.updateContext=e.updateContext),e.onEnter!==void 0&&(n.onEnter=e.onEnter),e.onLeave!==void 0&&(n.onLeave=e.onLeave),e.label!==void 0&&(n.label=e.label),e.timeoutMs!==void 0&&(n.timeoutMs=e.timeoutMs),n}function Ae(){function e(t){return N({_to:t,_when:void 0,_updateContext:void 0,_onEnter:void 0,_onLeave:void 0,_label:void 0,_timeoutMs:void 0})}function n(t){return typeof t=="function"?t({to:e}):t}function o(t){return t===!0||t.length===0?t:t.map(i=>qe(i))}function p(t,i){return{id:t,_meta:i?.meta,_onEnter:i?.onEnter,_onLeave:i?.onLeave,_on:i?.on}}function s(t){let i={},r={};for(let d of t.steps)if(i[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 l={};for(let[y,a]of Object.entries(d._on)){if(!a)continue;if(y==="completeJourney"||y==="terminateJourney"){l[y]=o(a);continue}let u=n(a);l[y]=u.map(E=>ke(E._candidate))}r[d.id]=l}if(t.global){let d={};for(let[l,y]of Object.entries(t.global))y!==void 0&&(l==="completeJourney"||l==="terminateJourney"?d[l]=o(y):Array.isArray(y)&&(d[l]=y.map(a=>ke(a._candidate))));r.global=d}return{initial:t.initial,context:t.context,...t.handlers!==void 0?{handlers:t.handlers}:{},steps:i,transitions:r}}return{createStep:p,to:e,build:s}}0&&(module.exports={JourneyDisposedError,createJourneyBuilder,createJourneyMachine});
1
+ "use strict";var j=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var ce=(n,e)=>{for(var t in e)j(n,t,{get:e[t],enumerable:!0})},he=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pe(e))!de.call(n,s)&&s!==t&&j(n,s,{get:()=>e[s],enumerable:!(r=le(e,s))||r.enumerable});return n};var ge=n=>he(j({},"__esModule",{value:!0}),n);var be={};ce(be,{JourneyError:()=>m,analyzeStructure:()=>ue,createGraphJourney:()=>F,createLinearJourney:()=>U,defineWork:()=>ae,isJourneyError:()=>Q,withGraphTypes:()=>oe,withLinearTypes:()=>re});module.exports=ge(be);var m=class extends Error{constructor(e,t,r={},s){super(`journey: ${t}`,s===void 0?void 0:{cause:s}),this.name="JourneyError",this.code=e,this.stepId=r.stepId,this.event=r.event,this.pluginName=r.pluginName}},Q=n=>n instanceof m;var R=(n,e)=>`${n.length}:${n}${e}`,Y=n=>n.label??`${n.event}[${n.index}] (${n.from} -> ${n.to})`,K=n=>n===null?null:{event:n.event,from:n.from,to:n.to,label:n.label??null,index:n.index},x=Object.freeze({isLoading:!1,isSuccess:!0,isError:!1,error:null}),A=Object.freeze({isLoading:!0,isSuccess:!1,isError:!1,error:null}),S=(n,e)=>Object.hasOwn(n,e);function D(n){console.error("[journey] subscriber threw:",n)}var E=(n,e)=>{let t=Object.keys(n);return t.length!==Object.keys(e).length?!1:t.every(r=>S(e,r)&&Object.is(n[r],e[r]))};function C(n){return{getSnapshot:()=>n.store.getSnapshot(),controls:{start:()=>n.start(),pause:()=>n.pause(),resume:()=>n.resume(),complete:e=>n.complete(e),terminate:e=>n.terminate(e),restart:()=>n.restart()},dispose:()=>n.dispose(),navigate:{goToStepById:e=>n.goToStepById(e),goToPreviousStep:e=>n.goToPreviousStep(e),goToNextStep:e=>n.goToNextStep(e),goToLastVisitedStep:()=>n.goToLastVisitedStep()},subscriptions:{subscribe:e=>n.store.subscribe(e),subscribeEvent:(e,t)=>n.store.subscribeEvent(e,t)},context:{update:e=>n.updateContext(e)},async:{clearError:()=>n.clearAsyncError()},plugins:n.pluginApis}}var G=()=>{let n=globalThis;if(typeof n.__DEV__=="boolean")return n.__DEV__;let e=n.process?.env?.NODE_ENV;return e===void 0||e==="development"},q=(n,e)=>{if(!(!G()||typeof console>"u")){if(e===void 0){console.warn(n);return}console.warn("%s",n,e)}};var N=class{constructor(e,t){this.listeners=new Set;this.eventListeners=new Map;this.disposed=!1;this.snapshot=e,this.onListenerError=t}report(e){if(!this.onListenerError){D(e);return}try{this.onListenerError(e)}catch(t){D(t)}}getSnapshot(){return this.snapshot}publish(e){if(!Object.is(this.snapshot,e)){this.snapshot=e;for(let t of[...this.listeners])try{t()}catch(r){this.report(r)}}}subscribe(e){return this.disposed?()=>{}:(this.listeners.add(e),()=>{this.listeners.delete(e)})}subscribeEvent(e,t){if(this.disposed)return()=>{};let r=this.eventListeners.get(e);return r||(r=new Set,this.eventListeners.set(e,r)),r.add(t),()=>{r.delete(t)}}emit(e,t){let r=this.eventListeners.get(e);if(r)for(let s of[...r])try{s(t)}catch(a){this.report(a)}}dispose(){this.disposed=!0,this.listeners.clear(),this.eventListeners.clear()}};var B=n=>typeof n=="object"&&n!==null&&G()?Object.freeze(n):n,fe=Object.freeze({}),Z=Object.freeze({}),w=(n,e)=>e!=null&&E(n,e)?e:Object.freeze(n),I=(n,e,t=Object.is)=>e!==void 0&&e.length===n.length&&n.every((r,s)=>t(r,e[s]))?e:Object.freeze([...n]),ye=(n,e)=>n===void 0?"none":e?"passed":"failed",P=class{constructor(e){this.pluginApis={};this.status="idle";this.timeline=[];this.currentIndex=-1;this.outcome=null;this.visitCounts=new Map;this.entryAsync=x;this.pending=null;this.disposed=!1;this.restoreSeed=null;this.generation=0;this.raiseQueue=[];this.processingRaised=!1;this.lastPluginExtensions={};this.lastSnapshot=null;this.transitionListeners=new Set;this.disposeCallbacks=[];this.snapshotDerivers=new Map;this.config=e,this.frozenStepOrder=Object.freeze([...e.stepIds]),this.restoreSeed=e.restore??null,this.context=B(e.restore?e.restore.context:e.initialContext),this.store=new N(this.buildSnapshot(),e.onListenerError),this.setupPlugins(),this.store.publish(this.buildSnapshot()),e.autoStart&&this.start()}start(){return this.disposed||this.status!=="idle"?!1:(this.setStatus("running"),this.enterInitialStep(),!0)}pause(){return this.disposed||this.status!=="running"||this.pending?!1:(this.setStatus("paused"),!0)}resume(){return this.disposed||this.status!=="paused"?!1:(this.setStatus("running"),!0)}complete(e){return this.disposed||this.status!=="running"||this.pending?!1:(this.outcome=Object.freeze({type:"completed",payload:e}),this.setStatus("completed"),!0)}terminate(e){return this.disposed||this.status==="terminated"?!1:(this.generation+=1,this.pending=null,this.entryAsync=x,this.raiseQueue=[],this.outcome=Object.freeze({type:"terminated",payload:e}),this.setStatus("terminated"),!0)}restart(){return this.disposed||this.status!=="completed"&&this.status!=="terminated"?!1:(this.generation+=1,this.pending=null,this.raiseQueue=[],this.timeline=[],this.currentIndex=-1,this.context=B(this.config.initialContext),this.outcome=null,this.visitCounts=new Map,this.entryAsync=x,this.setStatus("running"),this.enterInitialStep(),!0)}dispose(){if(!this.disposed){this.disposed=!0,this.generation+=1,this.pending=null,this.raiseQueue=[];for(let e of this.disposeCallbacks.splice(0))try{e()}catch{}this.transitionListeners.clear(),this.store.dispose()}}updateContext(e){if(this.disposed)return;let t=this.context;this.context=B(e(t));let r=this.publish();this.store.emit("contextChange",{snapshot:r,previous:t,current:this.context})}clearAsyncError(){this.disposed||!this.entryAsync.isError||(this.entryAsync=x,this.publish())}goToStepById(e){let t=this.checkNavigable();if(t)return this.blocked(t,e);if(!S(this.config.steps,e))return this.blocked({ok:!1,reason:"invalid-target"},e);if(e===this.currentStepId())return this.blocked({ok:!1,reason:"no-op"},e);if(this.config.kind==="graph"){let r=this.config.transitions.find(s=>s.from===this.currentStepId()&&s.to===e&&this.isEnabled(s));return r?this.runNavigation(e,{kind:"append"},this.eventFor(r),r):this.blocked({ok:!1,reason:"invalid-target"},e)}return this.runNavigation(e,{kind:"append"},null,null)}goToPreviousStep(e=1){let t=this.checkNavigable();if(t)return this.blocked(t,null);if(this.currentIndex<=0)return this.blocked({ok:!1,reason:"out-of-bounds"},null);let r=Math.max(0,this.currentIndex-Math.max(1,Math.floor(e))),s=this.timeline[r];return this.runNavigation(s,{kind:"pointer",index:r},null,null,void 0,"backward")}goToNextStep(e){let t=this.checkNavigable();if(t)return this.blocked(t,null);if(this.currentIndex<this.timeline.length-1){let r=this.currentIndex+1,s=this.timeline[r];return this.runNavigation(s,{kind:"pointer",index:r},null,null,e,"forward")}if(this.config.kind==="linear"){let r=this.config.stepIds.indexOf(this.currentStepId()??""),s=this.config.stepIds[r+1];return s===void 0?this.blocked({ok:!1,reason:"out-of-bounds"},null):this.runNavigation(s,{kind:"append"},null,null,e,"forward")}return this.blocked({ok:!1,reason:"out-of-bounds"},null)}goToLastVisitedStep(){let e=this.checkNavigable();if(e)return this.blocked(e,null);let t=this.timeline.length-1;if(this.currentIndex>=t)return this.blocked({ok:!1,reason:"no-op"},null);let r=this.timeline[t];return this.runNavigation(r,{kind:"pointer",index:t},null,null)}goToStepByIndex(e){let t=Number.isInteger(e)?this.config.stepIds[e]:void 0;return t===void 0?this.blocked({ok:!1,reason:"invalid-target"},null):this.goToStepById(t)}send(e,t,r){let s=this.checkNavigable();if(s)return this.blocked(s,null);let a=t===void 0?{type:e}:{type:e,payload:t},u=this.currentStepId(),o=r??(u===null?void 0:this.config.eventWork?.[R(u,e)]);if(o)return this.sendWithWork(e,a,o);let i=this.resolveTransition(e);return i?this.runNavigation(i.to,{kind:"append"},a,i):this.blocked({ok:!1,reason:"no-enabled-transition"},null)}async sendWithWork(e,t,r){let s=this.generation,a=this.currentStepId();if(a===null)return this.blocked({ok:!1,reason:"not-running"},null);let u=this.context,o=!1,i;this.pending={phase:"working",from:a,to:null},this.entryAsync=A,this.publish();try{let d={snapshot:this.store.getSnapshot(),from:a,event:t,handlers:this.config.handlers};if(i=await this.withTimeout(Promise.resolve(r.run(d)),`send work(${r.label??`${e} from ${a}`})`,r.timeoutMs),!this.isCurrent(s))return this.staleResult();let c=r.commit?.({...d,result:i,updateContext:h=>{u=h(u),o=!0}});if(typeof c=="object"&&c!==null&&"then"in c)throw new m("async-commit","send work commit must be synchronous")}catch(d){if(!this.isCurrent(s))return this.staleResult();this.pending=null,this.entryAsync=Object.freeze({isLoading:!1,isSuccess:!1,isError:!0,error:d});let c=this.publish();return this.store.emit("error",{snapshot:c,error:d,phase:"work",stepId:a}),this.blocked({ok:!1,reason:"error",error:d},null)}if(!this.isCurrent(s))return this.staleResult();let l=this.resolveTransition(e,u,i);return l?this.commitAndSettle(a,l.to,{kind:"append"},t,l,s,u,o,"jump"):(this.pending=null,this.entryAsync=x,this.publish(),this.blocked({ok:!1,reason:"no-enabled-transition"},null))}setupPlugins(){let e={getSnapshot:()=>this.store.getSnapshot(),structure:Object.freeze({kind:this.config.kind,stepIds:Object.freeze([...this.config.stepIds]),initial:this.config.initial,transitions:Object.freeze(this.config.transitions.map(t=>Object.freeze({event:t.event,from:t.from,to:t.to,guarded:t.when!==void 0,label:t.label??null,index:t.index})))}),onTransition:t=>(this.transitionListeners.add(t),()=>this.transitionListeners.delete(t)),onNavigationBlocked:t=>this.store.subscribeEvent("navigationBlocked",t),onStatusChange:t=>this.store.subscribeEvent("statusChange",t),onContextChange:t=>this.store.subscribeEvent("contextChange",t),onError:t=>this.store.subscribeEvent("error",t),onDispose:t=>{this.disposeCallbacks.push(t)},reportError:t=>this.store.report(t)};try{for(let t of this.config.plugins){if(S(this.pluginApis,t.name))throw new m("duplicate-plugin-name",`duplicate plugin name "${t.name}"`,{pluginName:t.name});let r=t.setup(e);this.pluginApis[t.name]=r.api,r.deriveSnapshot&&this.snapshotDerivers.set(t.name,r.deriveSnapshot)}}catch(t){throw this.dispose(),t}}currentStepId(){return this.currentIndex>=0?this.timeline[this.currentIndex]:null}eventFor(e){return{type:e.event}}isEnabled(e,t=this.context,r){if(!e.when)return!0;try{return e.when({context:t,handlers:this.config.handlers,result:r})}catch{return!1}}resolveTransition(e,t=this.context,r){return this.config.transitions.find(s=>s.event===e&&s.from===this.currentStepId()&&this.isEnabled(s,t,r))}checkNavigable(){return this.disposed?{ok:!1,reason:"disposed"}:this.status!=="running"?{ok:!1,reason:"not-running"}:this.pending?{ok:!1,reason:"transitioning"}:null}setStatus(e){let t=this.status;this.status=e;let r=this.publish();this.store.emit("statusChange",{snapshot:r,previous:t,current:e}),this.refreshPluginSnapshot()}refreshPluginSnapshot(){this.snapshotDerivers.size>0&&this.publish()}blocked(e,t){if(e.reason!=="disposed"){let r={snapshot:this.store.getSnapshot(),reason:e.reason,from:this.currentStepId(),to:t};"error"in e&&(r.error=e.error),this.store.emit("navigationBlocked",r)}return Promise.resolve({...e,from:this.currentStepId(),to:t})}hookArgs(e,t,r,s){return{snapshot:this.store.getSnapshot(),from:e,to:t,event:r,transition:s,updateContext:a=>this.updateContext(a),raise:a=>{this.config.kind!=="graph"||this.disposed||this.raiseQueue.push(a)}}}async invokeEffect(e,t,r,s){if(!e)return null;try{return await this.withTimeout(Promise.resolve(e(t)),r,s),null}catch(a){return{error:a}}}withTimeout(e,t,r){let s=r??this.config.defaultTimeoutMs;return s===void 0?e:new Promise((a,u)=>{let o=setTimeout(()=>u(new Error(`journey: ${t} timed out after ${s}ms`)),s);e.then(i=>{clearTimeout(o),a(i)},i=>{clearTimeout(o),u(i)})})}async enterInitialStep(){let e=this.generation,t=this.restoreSeed;if(this.restoreSeed=null,t){let s=t.timeline[t.currentIndex];this.pending={phase:"entering",from:null,to:s},this.timeline=[...t.timeline],this.currentIndex=t.currentIndex;for(let a of t.timeline)this.visitCounts.set(a,(this.visitCounts.get(a)??0)+1);this.commitEntry(null,s,"jump"),await this.runEntryEffects(null,s,null,null,e);return}let r=this.config.startAt??this.config.initial;this.pending={phase:"entering",from:null,to:r},this.timeline=[r],this.currentIndex=0,this.commitEntry(null,r,"jump"),await this.runEntryEffects(null,r,null,null,e)}async runNavigation(e,t,r,s,a,u){let o=this.generation,i=this.currentStepId(),l=this.context,d=!1;if(a&&i!==null&&u){this.pending={phase:"working",from:i,to:e},this.entryAsync=A,this.publish();try{let c={snapshot:this.store.getSnapshot(),from:i,to:e,direction:u},h=await this.withTimeout(Promise.resolve(a.run(c)),`${u} navigation work(${i} -> ${e})`,a.timeoutMs);if(!this.isCurrent(o))return this.staleResult();let f=a.commit?.({...c,result:h,updateContext:y=>{l=y(l),d=!0}});if(typeof f=="object"&&f!==null&&"then"in f)throw new m("async-commit","navigation work commit must be synchronous")}catch(c){if(!this.isCurrent(o))return this.staleResult();this.pending=null,this.entryAsync=Object.freeze({isLoading:!1,isSuccess:!1,isError:!0,error:c});let h=this.publish();return this.store.emit("error",{snapshot:h,error:c,phase:"work",stepId:i}),this.blocked({ok:!1,reason:"error",error:c},e)}}return this.isCurrent(o)?this.commitAndSettle(i,e,t,r,s,o,l,d,u??"jump"):this.staleResult()}async commitAndSettle(e,t,r,s,a,u,o,i,l){let d=this.context;r.kind==="pointer"?this.currentIndex=r.index:(this.timeline=[...this.timeline.slice(0,this.currentIndex+1),t],this.currentIndex=this.timeline.length-1),i&&(this.context=B(o));let c=e===null?void 0:this.config.steps[e];return this.pending={phase:c?.onLeave?"leaving":"entering",from:e,to:t},this.commitEntry(e,t,l,i?{previous:d,current:o}:void 0,c?.onLeave!==void 0||a?.onTransition!==void 0),await this.runEntryEffects(e,t,s,a,u),{ok:!0,from:e,to:t}}commitEntry(e,t,r,s,a=!1){this.visitCounts.set(t,(this.visitCounts.get(t)??0)+1);let u=this.config.steps[t];this.entryAsync=a||u?.onEnter?A:x;let o=this.publish();s&&this.store.emit("contextChange",{snapshot:o,...s}),e!==null&&this.store.emit("stepLeave",{snapshot:o,from:e,to:t}),this.store.emit("stepEnter",{snapshot:o,from:e,to:t,direction:r})}async runEntryEffects(e,t,r,s,a){let u=e===null?void 0:this.config.steps[e],o=this.config.steps[t],i=K(s),l=[],d=await this.invokeEffect(u?.onLeave,this.hookArgs(e,t,r,i),`onLeave(${e??""})`);if(!this.isCurrent(a))return;d&&e!==null&&l.push({error:d.error,phase:"leave",stepId:e}),this.pending={phase:"entering",from:e,to:t},this.publish();let c=await this.invokeEffect(s?.onTransition,this.hookArgs(e,t,r,i),`onTransition(${s?Y(s):r?.type??""})`,s?.timeoutMs);if(!this.isCurrent(a))return;c&&l.push({error:c.error,phase:"transition",stepId:t});let h=await this.invokeEffect(o?.onEnter,this.hookArgs(e,t,r,i),`onEnter(${t})`);if(!this.isCurrent(a))return;h&&l.push({error:h.error,phase:"enter",stepId:t}),this.entryAsync=l[0]?Object.freeze({isLoading:!1,isSuccess:!1,isError:!0,error:l[0].error}):x,this.pending=null;let f=this.publish();for(let y of l)this.store.emit("error",{snapshot:f,error:y.error,phase:y.phase,stepId:y.stepId});for(let y of[...this.transitionListeners])try{y({from:e,to:t,snapshot:f})}catch{}this.refreshPluginSnapshot(),this.processRaisedEvents(a)}async processRaisedEvents(e){if(this.processingRaised||!this.isCurrent(e))return;this.processingRaised=!0;let t=0;try{for(;this.raiseQueue.length>0&&this.isCurrent(e);){if(this.status!=="running"){this.raiseQueue=[];return}if(t+=1,t>25){this.raiseQueue=[],this.store.emit("error",{snapshot:this.store.getSnapshot(),error:new Error(`journey: raised-event cascade exceeded ${25} events; queue dropped`),phase:"raise",stepId:this.currentStepId()});return}let r=this.raiseQueue.shift();await this.send(r.type,r.payload)}}finally{this.processingRaised=!1}}isCurrent(e){return!this.disposed&&e===this.generation}staleResult(){let e=this.currentStepId();return this.disposed?{ok:!1,reason:"disposed",from:e,to:null}:{ok:!1,reason:"not-running",from:e,to:null}}publish(){let e=this.buildSnapshot();return this.store.publish(e),e}buildSnapshot(){let e=this.lastSnapshot,t=this.currentStepId(),r={},s=0;for(let h of this.config.stepIds){let f=(this.visitCounts.get(h)??0)>0;r[h]=f,f&&(s+=1)}let a=e?.history,u=a!=null&&E(a.visited,r)?a.visited:Object.freeze(r),o={status:this.status,context:this.context,transition:w({pending:this.pending!==null,phase:this.pending?.phase??null,from:this.pending?.from??null,to:this.pending?.to??null},e?.transition),history:w({timeline:I(this.timeline,a?.timeline),currentIndex:this.currentIndex,visited:u,canGoBack:this.currentIndex>0,canGoForward:this.currentIndex>=0&&this.currentIndex<this.timeline.length-1},a),machine:w({outcome:this.outcome},e?.machine)},i=t===null?null:{id:t,metadata:this.config.steps[t]?.metadata??fe,isFirstTimeVisit:(this.visitCounts.get(t)??0)===1,async:this.entryAsync},l;if(this.config.kind==="linear"){let h=e?.type==="linear"?e:null,f=t===null?-1:this.config.stepIds.indexOf(t);l={...o,type:"linear",currentStep:i===null?null:w({...i,index:f,isFirstStep:f===0,isLastStep:f===this.config.stepIds.length-1},h?.currentStep),steps:w({totalSteps:this.config.stepIds.length,stepOrder:this.frozenStepOrder,visitedStepCount:s},h?.steps),plugins:Z}}else{let h=[],f=[],y=[],g=[],p=new Map,T=new Set,b=!1;if(t!==null)for(let v of this.config.transitions){if(v.from!==t)continue;b=!0,h.includes(v.event)||h.push(v.event);let J=p.get(v.event)??0;p.set(v.event,J+1);let O=this.isEnabled(v),V=O&&!T.has(v.event);V&&T.add(v.event),g.push(Object.freeze({event:v.event,to:v.to,priority:J,guard:ye(v.when,O),enabled:O,selected:V})),O&&(f.includes(v.event)||f.push(v.event),y.includes(v.to)||y.push(v.to))}let k=e?.type==="graph"?e:null;l={...o,type:"graph",currentStep:i===null?null:w({...i,isTerminal:!b},k?.currentStep),steps:w({totalSteps:this.config.stepIds.length,visitedStepCount:s},k?.steps),declaredEvents:I(h,k?.declaredEvents),availableEvents:I(f,k?.availableEvents),availableSteps:I(y,k?.availableSteps),outgoingTransitions:I(g,k?.outgoingTransitions,(v,J)=>E(v,J)),plugins:Z}}if(this.snapshotDerivers.size>0){let h={};for(let[y,g]of this.snapshotDerivers)try{h[y]=g(l,this.lastPluginExtensions[y])}catch(p){this.store.report(p),S(this.lastPluginExtensions,y)&&(h[y]=this.lastPluginExtensions[y])}this.lastPluginExtensions=h;let f=e?.plugins;l={...l,plugins:f!=null&&E(f,h)?f:Object.freeze(h)}}let d=Object.freeze(l),c=e!==null&&E(d,e)?e:d;return this.lastSnapshot=c,c}};var ee=["context","transition","status"];function te(n){return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.trunc(n))}function ne(n,e){return{status:n.status,context:n.context,timeline:n.history.timeline,currentIndex:n.history.currentIndex,savedAt:e}}var me=new Set(["idle","running","paused","completed","terminated"]),ve=["__proto__","constructor","prototype"];function W(n,e=0){if(e>50||n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(r=>W(r,e+1));let t={};for(let[r,s]of Object.entries(n))ve.includes(r)||(t[r]=W(s,e+1));return t}function $(n){if(n===null)return null;let e;try{e=JSON.parse(n)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;return typeof t.status!="string"||!me.has(t.status)||!Array.isArray(t.timeline)||!t.timeline.every(r=>typeof r=="string")||typeof t.currentIndex!="number"||!Number.isInteger(t.currentIndex)||typeof t.savedAt!="number"||!Number.isFinite(t.savedAt)?null:{status:t.status,context:W(t.context),timeline:t.timeline,currentIndex:t.currentIndex,savedAt:t.savedAt}}function z(n){if(n.storage)return n.storage;let e;try{e=globalThis.localStorage}catch(t){throw new m("storage-unavailable","localStorage access was blocked by the environment; pass persist.storage explicitly",{},t)}if(!e)throw new m("storage-unavailable","persist.storage is required when localStorage is unavailable");return e}function L(n,e){let t;try{t=z(n).getItem(n.key)}catch{return null}let r=$(t);if(!r||r.status!=="running"&&r.status!=="paused"||!Number.isInteger(r.currentIndex)||r.currentIndex<0||r.currentIndex>=r.timeline.length)return null;for(let s of r.timeline)if(typeof s!="string"||!e(s))return null;return r}var _={status:"idle",lastSavedAt:null,error:null};function Te(n){let e=n.now??Date.now,t=te(n.debounceMs),r=new Set(n.saveOn??ee),s=0;return{name:"persistence",setup(a){s+=1,s>1&&q(`journey: persistence plugin instance shared by ${s} machines; they overwrite key "${n.key}". Create one per machine.`);let u=null,o=_,i=null,l=!1,d=p=>{u=p,o={status:"saved",lastSavedAt:p.savedAt,error:null}},c=p=>{o={...o,status:"error",error:p},a.reportError(p)},h=()=>{let p=ne(a.getSnapshot(),e());o={...o,status:"saving"};let T;try{T=n.storage.setItem(n.key,JSON.stringify(p))}catch(b){throw o={...o,status:"error",error:b},b}if(T!==void 0)return T.then(()=>d(p),c);d(p)},f=()=>{i!==null&&(clearTimeout(i),i=null)},y=()=>{i=null;try{let p=h()}catch(p){c(p)}},g=p=>{if(!(l||!r.has(p))){if(t===0){h();return}f(),o={...o,status:"pending"},i=setTimeout(y,t)}};return a.onContextChange(()=>g("context")),a.onTransition(()=>g("transition")),a.onStatusChange(({current:p})=>{if(p==="terminated"&&n.clearOnTerminate){f(),u=null,o=_,n.storage.removeItem(n.key);return}g("status")}),a.onDispose(()=>{l=!0,f()}),{api:{inspectPersistedState:()=>u,getPersistenceState:()=>o,readPersisted:()=>$(n.storage.getItem(n.key)),clearPersisted:()=>{f(),u=null,o=_;try{n.storage.removeItem(n.key)}catch(p){c(p)}},flushPersisted:async()=>{f();try{await h()}catch(p){c(p)}}},deriveSnapshot:(p,T)=>T===o?T:o}}}}function M(n){return Te({key:n.key,storage:z(n)})}function U(n,e={}){if(n.steps.length===0)throw new m("empty-definition","a linear journey needs at least one step");let t=[],r={};for(let o of n.steps){let i=typeof o=="string"?{id:o}:o;if(S(r,i.id))throw new m("duplicate-step-id",`duplicate step id "${i.id}"`,{stepId:i.id});t.push(i.id);let l={metadata:i.metadata??{}};i.onEnter&&(l.onEnter=i.onEnter),i.onLeave&&(l.onLeave=i.onLeave),r[i.id]=l}if(e.startAt!==void 0&&!S(r,e.startAt))throw new m("unknown-step",`startAt references unknown step "${e.startAt}"`,{stepId:e.startAt});let s=e.persist&&e.startAt===void 0?L(e.persist,o=>S(r,o)):null,a=new P({kind:"linear",stepIds:t,steps:r,initial:t[0],...e.startAt!==void 0?{startAt:e.startAt}:{},initialContext:n.context,...s?{restore:{context:s.context,timeline:s.timeline,currentIndex:s.currentIndex}}:{},transitions:[],handlers:void 0,autoStart:e.autoStart??!0,defaultTimeoutMs:e.defaultTimeoutMs,...e.onListenerError!==void 0?{onListenerError:e.onListenerError}:{},plugins:[...e.persist?[M(e.persist)]:[],...e.plugins??[]]}),u=C(a);return{...u,navigate:{...u.navigate,goToStepByIndex:o=>a.goToStepByIndex(o)}}}var re=()=>(n,e={})=>U(n,e);var se=(n,e,t)=>{if(typeof n!="string"||n.length===0)throw new m("invalid-label",`${e} must declare "label" as a non-empty string`,t);return n},ie=(n,e,t)=>{if(typeof n!="number"||!Number.isFinite(n)||n<=0)throw new m("invalid-timeout",`${e} must declare "timeoutMs" as a finite number greater than 0`,t);return n};function H(n){let e=Object.keys(n.steps);if(e.length===0)throw new m("empty-definition","a graph journey needs at least one step");if(!e.includes(n.initial))throw new m("unknown-initial-step",`initial step "${n.initial}" is not a declared step`,{stepId:n.initial});let t={};for(let u of e){let o=n.steps[u],i={metadata:o.metadata??{}};o.onEnter&&(i.onEnter=o.onEnter),o.onLeave&&(i.onLeave=o.onLeave),t[u]=i}let r=[],s={},a=(u,o,i,l)=>{if(!e.includes(i.to))throw new m("dangling-transition",`transition "${u}" references unknown step "${i.to}"`,{event:u,stepId:i.to});let d=`transition "${u}"[${l}] on step "${o}"`,c={event:u,from:o,to:i.to,index:l};i.when&&(c.when=i.when),i.onTransition&&(c.onTransition=i.onTransition),i.label!==void 0&&(c.label=se(i.label,d,{event:u,stepId:o})),i.timeoutMs!==void 0&&(c.timeoutMs=ie(i.timeoutMs,d,{event:u,stepId:o})),r.push(c)};for(let u of e){let o=n.steps[u]?.on;if(o)for(let[i,l]of Object.entries(o)){if(l===void 0)continue;if(typeof l=="string"){a(i,u,{to:l},0);continue}if(Array.isArray(l)){l.forEach((f,y)=>a(i,u,f,y));continue}let d=l,c=`work on "${i}" on step "${u}"`,h={run:d.run};d.commit&&(h.commit=d.commit),d.label!==void 0&&(h.label=se(d.label,c,{event:i,stepId:u})),d.timeoutMs!==void 0&&(h.timeoutMs=ie(d.timeoutMs,c,{event:i,stepId:u})),s[R(u,i)]=h,d.candidates.forEach((f,y)=>a(i,u,f,y))}}return{stepIds:e,steps:t,transitions:r,eventWork:s}}function F(n,e={}){let{stepIds:t,steps:r,transitions:s,eventWork:a}=H(n);if(e.startAt!==void 0&&!S(r,e.startAt))throw new m("unknown-step",`startAt references unknown step "${e.startAt}"`,{stepId:e.startAt});let u=e.persist&&e.startAt===void 0?L(e.persist,l=>S(r,l)):null,o=new P({kind:"graph",stepIds:t,steps:r,initial:n.initial,...e.startAt!==void 0?{startAt:e.startAt}:{},initialContext:n.context,...u?{restore:{context:u.context,timeline:u.timeline,currentIndex:u.currentIndex}}:{},transitions:s,...Object.keys(a).length>0?{eventWork:a}:{},handlers:e.handlers??n.handlers,autoStart:e.autoStart??!0,defaultTimeoutMs:e.defaultTimeoutMs,...e.onListenerError!==void 0?{onListenerError:e.onListenerError}:{},plugins:[...e.persist?[M(e.persist)]:[],...e.plugins??[]]});return{...C(o),send:(l,d)=>o.send(l,d)}}var oe=()=>(n,e={})=>F(n,e);var ae=()=>n=>n;function Se(n){let e=[],t=[...n.stepIds],r=new Set,s=new Set;n.transitions.forEach((g,p)=>{let T=`${g.from} ${g.event}`;if(s.has(T)){r.add(p),e.push({code:"shadowed-transition",severity:"warning",from:g.from,event:g.event,message:`Transition "${g.from}.${g.event}" is shadowed by an earlier unconditional candidate.`});return}g.guarded||s.add(T)});let a=n.transitions.filter((g,p)=>!r.has(p)),u=g=>a.filter(p=>p.from===g),o=new Set,i=[n.initial];for(;i.length>0;){let g=i.pop();if(!o.has(g)){o.add(g);for(let p of u(g))i.push(p.to)}}for(let g of t)o.has(g)||e.push({code:"unreachable-step",severity:"warning",stepId:g,message:`Step "${g}" is unreachable from the initial step "${n.initial}".`});let l=t.filter(g=>u(g).length===0),d=new Set,c=new Set,h=[],f=g=>{c.add(g),h.push(g);for(let p of u(g)){let T=h.indexOf(p.to);if(T>=0){let b=[...h.slice(T),p.to],k=b.join(" ");d.has(k)||(d.add(k),e.push({code:"cycle-detected",severity:"warning",from:p.from,event:p.event,steps:b,message:`Cycle detected: ${b.join(" -> ")}.`}));continue}c.has(p.to)||f(p.to)}h.pop()};f(n.initial);let y=l.some(g=>o.has(g));return y||e.push({code:"no-terminal-path",severity:"warning",stepId:n.initial,message:`No terminal step is reachable from the initial step "${n.initial}".`}),{issues:e,summary:{stepCount:t.length,reachableStepCount:o.size,unreachableStepCount:t.length-o.size,terminalStepIds:l,cycleCount:d.size,shadowedTransitionCount:r.size,terminalPathExists:y}}}function ue(n){let{stepIds:e,transitions:t}=H(n),r={kind:"graph",stepIds:e,initial:n.initial,transitions:t.map(s=>({event:s.event,from:s.from,to:s.to,guarded:s.when!==void 0,label:s.label??null,index:s.index}))};return Se(r)}0&&(module.exports={JourneyError,analyzeStructure,createGraphJourney,createLinearJourney,defineWork,isJourneyError,withGraphTypes,withLinearTypes});
2
2
  //# sourceMappingURL=index.cjs.map