@rxova/journey-core 1.0.0-rc.1 → 1.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +3 -3
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/journey-builder/index.d.cts +1 -1
- package/dist/journey-builder/index.d.ts +1 -1
- package/dist/journey-builder/types.d.cts +81 -24
- package/dist/journey-builder/types.d.ts +81 -24
- package/dist/journey-machine/controls.d.cts +1 -1
- package/dist/journey-machine/controls.d.ts +1 -1
- package/dist/journey-machine/helpers.d.cts +15 -7
- package/dist/journey-machine/helpers.d.ts +15 -7
- package/dist/journey-machine/navigation.d.cts +6 -5
- package/dist/journey-machine/navigation.d.ts +6 -5
- package/dist/journey-machine/send.d.cts +2 -2
- package/dist/journey-machine/send.d.ts +2 -2
- package/dist/plugins/analytics/index.cjs +1 -1
- package/dist/plugins/analytics/index.cjs.map +2 -2
- package/dist/plugins/analytics/index.js +1 -1
- package/dist/plugins/analytics/index.js.map +2 -2
- package/dist/plugins/autosave/index.cjs +1 -1
- package/dist/plugins/autosave/index.cjs.map +2 -2
- package/dist/plugins/autosave/index.js +1 -1
- package/dist/plugins/autosave/index.js.map +2 -2
- package/dist/plugins/diagnostics/index.cjs +1 -1
- package/dist/plugins/diagnostics/index.cjs.map +3 -3
- package/dist/plugins/diagnostics/index.js +1 -1
- package/dist/plugins/diagnostics/index.js.map +3 -3
- package/dist/plugins/execution-paths/index.cjs +1 -1
- package/dist/plugins/execution-paths/index.cjs.map +3 -3
- package/dist/plugins/execution-paths/index.js +1 -1
- package/dist/plugins/execution-paths/index.js.map +3 -3
- package/dist/plugins/persistence/index.cjs +1 -1
- package/dist/plugins/persistence/index.cjs.map +2 -2
- package/dist/plugins/persistence/index.js +1 -1
- package/dist/plugins/persistence/index.js.map +2 -2
- package/dist/types/analytics.types.d.cts +1 -0
- package/dist/types/analytics.types.d.ts +1 -0
- package/dist/types/diagnostics.types.d.cts +2 -2
- package/dist/types/diagnostics.types.d.ts +2 -2
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/journey.types.d.cts +3 -2
- package/dist/types/journey.types.d.ts +3 -2
- package/dist/types/machine.types.d.cts +4 -2
- package/dist/types/machine.types.d.ts +4 -2
- package/dist/types/observation.types.d.cts +9 -1
- package/dist/types/observation.types.d.ts +9 -1
- package/dist/types/transitions.types.d.cts +9 -4
- package/dist/types/transitions.types.d.ts +9 -4
- package/package.json +26 -2
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Typed state machine for multi-step UI flows.
|
|
|
6
6
|
<a href="https://www.npmjs.com/package/@rxova/journey-core">
|
|
7
7
|
<img src="https://img.shields.io/npm/v/@rxova/journey-core?color=0f8f6a" alt="npm" />
|
|
8
8
|
</a>
|
|
9
|
-
<img src="https://img.shields.io/badge/
|
|
9
|
+
<img src="https://img.shields.io/badge/7.58%20kB-brotli-0f8f6a" alt="size" />
|
|
10
10
|
<img src="https://img.shields.io/badge/zero%20dependencies-black" alt="zero deps" />
|
|
11
11
|
<img src="https://img.shields.io/badge/TypeScript-strict-3178C6?logo=typescript&logoColor=white" alt="TypeScript" />
|
|
12
12
|
</p>
|
|
@@ -36,7 +36,7 @@ const machine = createJourneyMachine({
|
|
|
36
36
|
transitions: ["account", "details", "review"]
|
|
37
37
|
});
|
|
38
38
|
|
|
39
|
-
machine.
|
|
39
|
+
machine.startJourney();
|
|
40
40
|
|
|
41
41
|
await machine.send({ type: "goToNextStep" }); // account → details
|
|
42
42
|
await machine.send({ type: "goToNextStep" }); // details → review
|
|
@@ -82,8 +82,7 @@ transitions: {
|
|
|
82
82
|
]
|
|
83
83
|
},
|
|
84
84
|
admin: { completeJourney: true },
|
|
85
|
-
dashboard: { completeJourney: true }
|
|
86
|
-
global: { terminateJourney: true }
|
|
85
|
+
dashboard: { completeJourney: true }
|
|
87
86
|
}
|
|
88
87
|
```
|
|
89
88
|
|
|
@@ -106,8 +105,7 @@ export const loginStep = createStep("login", {
|
|
|
106
105
|
const definition = build({
|
|
107
106
|
initial: "login",
|
|
108
107
|
context: { role: "user" },
|
|
109
|
-
steps: [loginStep, adminStep, dashboardStep]
|
|
110
|
-
global: { completeJourney: true, terminateJourney: true }
|
|
108
|
+
steps: [loginStep, adminStep, dashboardStep]
|
|
111
109
|
});
|
|
112
110
|
```
|
|
113
111
|
|
|
@@ -117,6 +115,9 @@ Use the **factory form** when you need `event.payload` narrowed to the specific
|
|
|
117
115
|
submit: ({ to }) => [to("admin").when(({ context, event }) => event.payload?.username !== "")];
|
|
118
116
|
```
|
|
119
117
|
|
|
118
|
+
Each transition modifier is single-use at the type level. Calling `.when()`, `.updateContext()`,
|
|
119
|
+
`.onEnter()`, `.onLeave()`, `.label()`, or `.timeoutMs()` twice on the same builder is a TypeScript error. If you bypass the type system, runtime keeps the existing last-call-wins behavior.
|
|
120
|
+
|
|
120
121
|
### Headless
|
|
121
122
|
|
|
122
123
|
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.
|
|
@@ -129,7 +130,7 @@ const machine = createJourneyMachine({
|
|
|
129
130
|
// no transitions — the caller drives the flow
|
|
130
131
|
});
|
|
131
132
|
|
|
132
|
-
machine.
|
|
133
|
+
machine.startJourney();
|
|
133
134
|
await machine.goToStepById("configure");
|
|
134
135
|
await machine.goToStepById("confirm");
|
|
135
136
|
await machine.goToPreviousStep(); // back to configure
|
|
@@ -138,7 +139,7 @@ await machine.completeJourney();
|
|
|
138
139
|
|
|
139
140
|
In headless mode, `goToStepById(...)` is the navigation primitive. `goToNextStep()` and custom events are explicit no-ops until you define transitions and move into linear or graph mode.
|
|
140
141
|
|
|
141
|
-
After `dispose()`, send-style APIs resolve with `transitioned: false` and `error: JourneyDisposedError`. Control APIs such as `
|
|
142
|
+
After `dispose()`, send-style APIs resolve with `transitioned: false` and `error: JourneyDisposedError`. Control APIs such as `startJourney()` and `updateContext()` stay no-op and emit a development warning.
|
|
142
143
|
|
|
143
144
|
`updateContext()` is the ordered context-write API. It runs through the same queue as `send()`, so it applies against the latest committed snapshot when it executes.
|
|
144
145
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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});
|
|
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});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|