xstate 4.18.0 → 4.20.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.
@@ -1,4 +1,4 @@
1
- const t={};function e(t){return Object.keys(t)}function i(t,n,s="."){const r=o(t,s),a=o(n,s);return S(a)?!!S(r)&&a===r:S(r)?r in a:e(r).every(t=>t in a&&i(r[t],a[t]))}function n(t){try{return S(t)||"number"==typeof t?""+t:t.type}catch(t){throw new Error("Events must be strings or objects with a string event.type property.")}}function s(t,e){try{return m(t)?t:t.toString().split(e)}catch(e){throw new Error(`'${t}' is not a valid state path.`)}}function o(t,e){if("object"==typeof(i=t)&&"value"in i&&"context"in i&&"event"in i&&"_event"in i)return t.value;var i;if(m(t))return r(t);if("string"!=typeof t)return t;return r(s(t,e))}function r(t){if(1===t.length)return t[0];const e={};let i=e;for(let e=0;e<t.length-1;e++)e===t.length-2?i[t[e]]=t[e+1]:(i[t[e]]={},i=i[t[e]]);return e}function a(t,i){const n={},s=e(t);for(let e=0;e<s.length;e++){const o=s[e];n[o]=i(t[o],o,t,e)}return n}function c(t,i,n){const s={};for(const o of e(t)){const e=t[o];n(e)&&(s[o]=i(e,o,t))}return s}const h=t=>e=>{let i=e;for(const e of t)i=i[e];return i};function d(t){if(!t)return[[]];if(S(t))return[[t]];return u(e(t).map(e=>{const i=t[e];return"string"==typeof i||i&&Object.keys(i).length?d(t[e]).map(t=>[e].concat(t)):[[e]]}))}function u(t){return[].concat(...t)}function l(t){return m(t)?t:[t]}function f(t){return void 0===t?[]:l(t)}function p(t,e,i){if(b(t))return t(e,i.data);const n={};for(const s of Object.keys(t)){const o=t[s];b(o)?n[s]=o(e,i.data):n[s]=o}return n}function g(t){return t instanceof Promise||!(null===t||!b(t)&&"object"!=typeof t||!b(t.then))}function v(t,e){const[i,n]=[[],[]];for(const s of t)e(s)?i.push(s):n.push(s);return[i,n]}function y(t,e){return a(t.states,(t,i)=>{if(!t)return;const n=(S(e)?void 0:e[i])||(t?t.current:void 0);return n?{current:n,states:y(t,n)}:void 0})}function m(t){return Array.isArray(t)}function b(t){return"function"==typeof t}function S(t){return"string"==typeof t}function w(t,e){if(t)return S(t)?{type:"xstate.guard",name:t,predicate:e?e[t]:void 0}:b(t)?{type:"xstate.guard",name:t.name,predicate:t}:t}function x(t){try{return"subscribe"in t&&b(t.subscribe)}catch(t){return!1}}const O="function"==typeof Symbol&&Symbol.observable||"@@observable";function _(t){try{return"__xstatenode"in t}catch(t){return!1}}const j=(()=>{let t=0;return()=>(t++,t.toString(16))})();function E(t,e){return S(t)||"number"==typeof t?Object.assign({type:t},e):t}function N(t,e){if(!S(t)&&"$$type"in t&&"scxml"===t.$$type)return t;const i=E(t);return Object.assign({name:i.type,data:i,$$type:"scxml",type:"external"},e)}function T(t,e){return l(e).map(e=>void 0===e||"string"==typeof e||_(e)?{target:e,event:t}:Object.assign(Object.assign({},e),{event:t}))}function $(t,e,i,n,s){const{guards:o}=t.options,r={state:s,cond:e,_event:n};if("xstate.guard"===e.type)return e.predicate(i,n.data,r);const a=o[e.type];if(!a)throw new Error(`Guard '${e.type}' is not implemented on machine '${t.id}'.`);return a(i,n.data,r)}function k(t){return"string"==typeof t?{type:t}:t}function P(t,n){let s;for(const o of e(t))i(o,n)&&(!s||n.length>s.length)&&(s=o);return t[s]}
1
+ const t={};function e(t){return Object.keys(t)}function i(t,s,n="."){const r=o(t,n),a=o(s,n);return S(a)?!!S(r)&&a===r:S(r)?r in a:e(r).every(t=>t in a&&i(r[t],a[t]))}function s(t){try{return S(t)||"number"==typeof t?""+t:t.type}catch(t){throw new Error("Events must be strings or objects with a string event.type property.")}}function n(t,e){try{return m(t)?t:t.toString().split(e)}catch(e){throw new Error(`'${t}' is not a valid state path.`)}}function o(t,e){if("object"==typeof(i=t)&&"value"in i&&"context"in i&&"event"in i&&"_event"in i)return t.value;var i;if(m(t))return r(t);if("string"!=typeof t)return t;return r(n(t,e))}function r(t){if(1===t.length)return t[0];const e={};let i=e;for(let e=0;e<t.length-1;e++)e===t.length-2?i[t[e]]=t[e+1]:(i[t[e]]={},i=i[t[e]]);return e}function a(t,i){const s={},n=e(t);for(let e=0;e<n.length;e++){const o=n[e];s[o]=i(t[o],o,t,e)}return s}function c(t,i,s){const n={};for(const o of e(t)){const e=t[o];s(e)&&(n[o]=i(e,o,t))}return n}const h=t=>e=>{let i=e;for(const e of t)i=i[e];return i};function d(t){if(!t)return[[]];if(S(t))return[[t]];return u(e(t).map(e=>{const i=t[e];return"string"==typeof i||i&&Object.keys(i).length?d(t[e]).map(t=>[e].concat(t)):[[e]]}))}function u(t){return[].concat(...t)}function l(t){return m(t)?t:[t]}function f(t){return void 0===t?[]:l(t)}function p(t,e,i){if(b(t))return t(e,i.data);const s={};for(const n of Object.keys(t)){const o=t[n];b(o)?s[n]=o(e,i.data):s[n]=o}return s}function g(t){return t instanceof Promise||!(null===t||!b(t)&&"object"!=typeof t||!b(t.then))}function v(t,e){const[i,s]=[[],[]];for(const n of t)e(n)?i.push(n):s.push(n);return[i,s]}function y(t,e){return a(t.states,(t,i)=>{if(!t)return;const s=(S(e)?void 0:e[i])||(t?t.current:void 0);return s?{current:s,states:y(t,s)}:void 0})}function m(t){return Array.isArray(t)}function b(t){return"function"==typeof t}function S(t){return"string"==typeof t}function w(t,e){if(t)return S(t)?{type:"xstate.guard",name:t,predicate:e?e[t]:void 0}:b(t)?{type:"xstate.guard",name:t.name,predicate:t}:t}function x(t){try{return"subscribe"in t&&b(t.subscribe)}catch(t){return!1}}const O="function"==typeof Symbol&&Symbol.observable||"@@observable";function _(t){try{return"__xstatenode"in t}catch(t){return!1}}const j=(()=>{let t=0;return()=>(t++,t.toString(16))})();function E(t,e){return S(t)||"number"==typeof t?Object.assign({type:t},e):t}function N(t,e){if(!S(t)&&"$$type"in t&&"scxml"===t.$$type)return t;const i=E(t);return Object.assign({name:i.type,data:i,$$type:"scxml",type:"external"},e)}function T(t,e){return l(e).map(e=>void 0===e||"string"==typeof e||_(e)?{target:e,event:t}:Object.assign(Object.assign({},e),{event:t}))}function $(t,e,i,s,n){const{guards:o}=t.options,r={state:n,cond:e,_event:s};if("xstate.guard"===e.type)return e.predicate(i,s.data,r);const a=o[e.type];if(!a)throw new Error(`Guard '${e.type}' is not implemented on machine '${t.id}'.`);return a(i,s.data,r)}function k(t){return"string"==typeof t?{type:t}:t}function P(t,s){let n;for(const o of e(t))i(o,s)&&(!n||s.length>n.length)&&(n=o);return t[n]}
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
@@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
12
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */function C(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}var V,I;!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"}(V||(V={})),function(t){t.Parent="#_parent",t.Internal="#_internal"}(I||(I={}));const L=t=>"atomic"===t.type||"final"===t.type;function D(t){return e(t.states).map(e=>t.states[e])}function A(t){const e=[t];return L(t)?e:e.concat(u(D(t).map(A)))}function R(t,e){const i=M(new Set(t)),n=new Set(e);for(const t of n){let e=t.parent;for(;e&&!n.has(e);)n.add(e),e=e.parent}const s=M(n);for(const t of n)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const e of D(t))"history"!==e.type&&(n.has(e)||(n.add(e),i.get(e)?i.get(e).forEach(t=>n.add(t)):e.initialStateNodes.forEach(t=>n.add(t))))}else i.get(t)?i.get(t).forEach(t=>n.add(t)):t.initialStateNodes.forEach(t=>n.add(t));for(const t of n){let e=t.parent;for(;e&&!n.has(e);)n.add(e),e=e.parent}return n}function M(t){const e=new Map;for(const i of t)e.has(i)||e.set(i,[]),i.parent&&(e.has(i.parent)||e.set(i.parent,[]),e.get(i.parent).push(i));return e}function z(t,e){return function t(e,i){const n=i.get(e);if(!n)return{};if("compound"===e.type){const t=n[0];if(!t)return{};if(L(t))return t.key}const s={};return n.forEach(e=>{s[e.key]=t(e,i)}),s}(t,M(R([t],e)))}function F(t,e){return Array.isArray(t)?t.some(t=>t===e):t instanceof Set&&t.has(e)}function J(t,e){return"compound"===e.type?D(e).some(e=>"final"===e.type&&F(t,e)):"parallel"===e.type&&D(e).every(e=>J(t,e))}const U=V.Start,B=V.Stop,q=V.Raise,X=V.Send,H=V.Cancel,G=V.NullEvent,K=V.Assign,Q=(V.After,V.DoneState,V.Log),W=V.Init,Y=V.Invoke,Z=(V.ErrorExecution,V.ErrorPlatform),tt=V.ErrorCustom,et=V.Update,it=V.Choose,nt=V.Pure,st=N({type:W});function ot(t,e){return e&&e[t]||void 0}function rt(t,e){let i;if(S(t)||"number"==typeof t){const n=ot(t,e);i=b(n)?{type:t,exec:n}:n||{type:t,exec:void 0}}else if(b(t))i={type:t.name||t.toString(),exec:t};else{const n=ot(t.type,e);if(b(n))i=Object.assign(Object.assign({},t),{exec:n});else if(n){const e=n.type||t.type;i=Object.assign(Object.assign(Object.assign({},n),t),{type:e})}else i=t}return Object.defineProperty(i,"toString",{value:()=>i.type,enumerable:!1,configurable:!0}),i}const at=(t,e)=>{if(!t)return[];return(m(t)?t:[t]).map(t=>rt(t,e))};function ct(t){const e=rt(t);return Object.assign(Object.assign({id:S(t)?t:e.id},e),{type:e.type})}function ht(t){return S(t)?{type:q,event:t}:dt(t,{to:I.Internal})}function dt(t,e){return{to:e?e.to:void 0,type:X,event:b(t)?t:E(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:b(t)?t.name:n(t)}}function ut(t,e){return dt(t,Object.assign(Object.assign({},e),{to:I.Parent}))}function lt(){return ut(et)}const ft=(t,e)=>({context:t,event:e});const pt=t=>({type:H,sendId:t});function gt(t){const e=ct(t);return{type:V.Start,activity:e,exec:void 0}}function vt(t){const e=b(t)?t:ct(t);return{type:V.Stop,activity:e,exec:void 0}}const yt=t=>({type:K,assignment:t});function mt(t,e){const i=e?"#"+e:"";return`${V.After}(${t})${i}`}function bt(t,e){const i=`${V.DoneState}.${t}`,n={type:i,data:e,toString:()=>i};return n}function St(t,e){const i=`${V.DoneInvoke}.${t}`,n={type:i,data:e,toString:()=>i};return n}function wt(t,e){const i=`${V.ErrorPlatform}.${t}`,n={type:i,data:e,toString:()=>i};return n}function xt(t,e){return dt((t,e)=>e,Object.assign(Object.assign({},e),{to:t}))}function Ot(t,i,n,s,o){const[r,a]=v(o,t=>t.type===K);let c=r.length?function(t,i,n,s){return t?n.reduce((t,n)=>{const{assignment:o}=n,r={state:s,action:n,_event:i};let a={};if(b(o))a=o(t,i.data,r);else for(const n of e(o)){const e=o[n];a[n]=b(e)?e(t,i.data,r):e}return Object.assign({},t,a)},t):t}(n,s,r,i):n;return[u(a.map(e=>{var n;switch(e.type){case q:return{type:q,_event:N(e.event)};case X:return function(t,e,i,n){const s={_event:i},o=N(b(t.event)?t.event(e,i.data,s):t.event);let r;if(S(t.delay)){const o=n&&n[t.delay];r=b(o)?o(e,i.data,s):o}else r=b(t.delay)?t.delay(e,i.data,s):t.delay;const a=b(t.to)?t.to(e,i.data,s):t.to;return Object.assign(Object.assign({},t),{to:a,_event:o,event:o.data,delay:r})}(e,c,s,t.options.delays);case Q:return((t,e,i)=>Object.assign(Object.assign({},t),{value:S(t.expr)?t.expr:t.expr(e,i.data,{_event:i})}))(e,c,s);case it:{const o=null===(n=e.conds.find(e=>{const n=w(e.cond,t.options.guards);return!n||$(t,n,c,s,i)}))||void 0===n?void 0:n.actions;if(!o)return[];const r=Ot(t,i,c,s,at(f(o),t.options.actions));return c=r[1],r[0]}case nt:{const n=e.get(c,s.data);if(!n)return[];const o=Ot(t,i,c,s,at(f(n),t.options.actions));return c=o[1],o[0]}case B:return function(t,e,i){const n=b(t.activity)?t.activity(e,i.data):t.activity,s="string"==typeof n?{id:n}:n;return{type:V.Stop,activity:s}}(e,c,s);default:return rt(e,t.options.actions)}})),c]}function _t(t,e){const{exec:i}=t;return Object.assign(Object.assign({},t),{exec:void 0!==i?()=>i(e.context,e.event,{action:t,state:e,_event:e._event}):void 0})}class jt{constructor(e){this.actions=[],this.activities=t,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||t,this.meta=e.meta||{},this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,Object.defineProperty(this,"nextEvents",{get:()=>{return t=this.configuration,u([...new Set(t.map(t=>t.ownEvents))]);var t}})}static from(t,e){if(t instanceof jt)return t.context!==e?new jt({value:t.value,context:e,_event:t._event,_sessionid:null,historyValue:t.historyValue,history:t.history,actions:[],activities:t.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):t;return new jt({value:t,context:e,_event:st,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})}static create(t){return new jt(t)}static inert(t,e){if(t instanceof jt){if(!t.actions.length)return t;const i=st;return new jt({value:t.value,context:e,_event:i,_sessionid:null,historyValue:t.historyValue,history:t.history,activities:t.activities,configuration:t.configuration,transitions:[],children:{}})}return jt.from(t,e)}toStrings(t=this.value,i="."){if(S(t))return[t];const n=e(t);return n.concat(...n.map(e=>this.toStrings(t[e],i).map(t=>e+i+t)))}toJSON(){return C(this,["configuration","transitions"])}matches(t){return i(t,this.value)}}const Et=[],Nt=(t,e)=>{Et.push(t);const i=e(t);return Et.pop(),i};function Tt(t){return{id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:t})}}function $t(t,e,i){const n=Tt(e);return n.deferred=!0,_(t)&&(n.state=Nt(void 0,()=>(i?t.withContext(i):t).initialState)),n}function kt(t){if("string"==typeof t){const e={type:t,toString:()=>t};return e}return t}function Pt(t){return Object.assign(Object.assign({type:Y},t),{toJSON(){const e=C(t,["onDone","onError"]);return Object.assign(Object.assign({},e),{type:Y,src:kt(t.src)})}})}const Ct={},Vt=t=>"#"===t[0];class It{constructor(t,i,n){var s;this.config=t,this.context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.options=Object.assign({actions:{},guards:{},services:{},activities:{},delays:{}},i),this.parent=this.options._parent,this.key=this.config.key||this.options._key||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:"."),this.id=this.config.id||[this.machine.key,...this.path].join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&e(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:null!==(s=this.config.schema)&&void 0!==s?s:{},this.initial=this.config.initial,this.states=this.config.states?a(this.config.states,(t,e)=>{const i=new It(t,{_parent:this,_key:e});return Object.assign(this.idMap,Object.assign({[i.id]:i},i.idMap)),i}):Ct;let o=0;!function t(e){e.order=o++;for(const i of D(e))t(i)}(this),this.history=!0===this.config.history?"shallow":this.config.history||!1,this._transient=!!this.config.always||!!this.config.on&&(Array.isArray(this.config.on)?this.config.on.some(({event:t})=>""===t):""in this.config.on),this.strict=!!this.config.strict,this.onEntry=f(this.config.entry||this.config.onEntry).map(t=>rt(t)),this.onExit=f(this.config.exit||this.config.onExit).map(t=>rt(t)),this.meta=this.config.meta,this.doneData="final"===this.type?this.config.data:void 0,this.invoke=f(this.config.invoke).map((t,e)=>{if(_(t))return this.machine.options.services=Object.assign({[t.id]:t},this.machine.options.services),Pt({src:t.id,id:t.id});if(S(t.src))return Pt(Object.assign(Object.assign({},t),{id:t.id||t.src,src:t.src}));if(_(t.src)||b(t.src)){const i=`${this.id}:invocation[${e}]`;return this.machine.options.services=Object.assign({[i]:t.src},this.machine.options.services),Pt(Object.assign(Object.assign({id:i},t),{src:i}))}{const e=t.src;return Pt(Object.assign(Object.assign({id:e.type},t),{src:e}))}}),this.activities=f(this.config.activities).concat(this.invoke).map(t=>ct(t)),this.transition=this.transition.bind(this)}_init(){this.__cache.transitions||A(this).forEach(t=>t.on)}withConfig(t,e=this.context){const{actions:i,activities:n,guards:s,services:o,delays:r}=this.options;return new It(this.config,{actions:Object.assign(Object.assign({},i),t.actions),activities:Object.assign(Object.assign({},n),t.activities),guards:Object.assign(Object.assign({},s),t.guards),services:Object.assign(Object.assign({},o),t.services),delays:Object.assign(Object.assign({},r),t.delays)},e)}withContext(t){return new It(this.config,this.options,t)}get definition(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:a(this.states,t=>t.definition),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke}}toJSON(){return this.definition}get on(){if(this.__cache.on)return this.__cache.on;const t=this.transitions;return this.__cache.on=t.reduce((t,e)=>(t[e.eventType]=t[e.eventType]||[],t[e.eventType].push(e),t),{})}get after(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)}get transitions(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)}getCandidates(t){if(this.__cache.candidates[t])return this.__cache.candidates[t];const e=""===t,i=this.transitions.filter(i=>{const n=i.eventType===t;return e?n:n||"*"===i.eventType});return this.__cache.candidates[t]=i,i}getDelayedTransitions(){const t=this.config.after;if(!t)return[];const i=(t,e)=>{const i=mt(b(t)?`${this.id}:delay[${e}]`:t,this.id);return this.onEntry.push(dt(i,{delay:t})),this.onExit.push(pt(i)),i};return(m(t)?t.map((t,e)=>{const n=i(t.delay,e);return Object.assign(Object.assign({},t),{event:n})}):u(e(t).map((e,n)=>{const s=t[e],o=S(s)?{target:s}:s,r=isNaN(+e)?e:+e,a=i(r,n);return f(o).map(t=>Object.assign(Object.assign({},t),{event:a,delay:r}))}))).map(t=>{const{delay:e}=t;return Object.assign(Object.assign({},this.formatTransition(t)),{delay:e})})}getStateNodes(t){if(!t)return[];const i=t instanceof jt?t.value:o(t,this.delimiter);if(S(i)){const t=this.getStateNode(i).initial;return void 0!==t?this.getStateNodes({[i]:t}):[this.states[i]]}const n=e(i);return n.map(t=>this.getStateNode(t)).concat(n.reduce((t,e)=>{const n=this.getStateNode(e).getStateNodes(i[e]);return t.concat(n)},[]))}handles(t){const e=n(t);return this.events.includes(e)}resolveState(t){const e=Array.from(R([],this.getStateNodes(t.value)));return new jt(Object.assign(Object.assign({},t),{value:this.resolve(t.value),configuration:e,done:J(e,this)}))}transitionLeafNode(t,e,i){const n=this.getStateNode(t).next(e,i);return n&&n.transitions.length?n:this.next(e,i)}transitionCompoundNode(t,i,n){const s=e(t),o=this.getStateNode(s[0])._transition(t[s[0]],i,n);return o&&o.transitions.length?o:this.next(i,n)}transitionParallelNode(t,i,n){const s={};for(const o of e(t)){const e=t[o];if(!e)continue;const r=this.getStateNode(o)._transition(e,i,n);r&&(s[o]=r)}const o=e(s).map(t=>s[t]),r=u(o.map(t=>t.transitions));if(!o.some(t=>t.transitions.length>0))return this.next(i,n);const a=u(o.map(t=>t.entrySet)),c=u(e(s).map(t=>s[t].configuration));return{transitions:r,entrySet:a,exitSet:u(o.map(t=>t.exitSet)),configuration:c,source:i,actions:u(e(s).map(t=>s[t].actions))}}_transition(t,i,n){return S(t)?this.transitionLeafNode(t,i,n):1===e(t).length?this.transitionCompoundNode(t,i,n):this.transitionParallelNode(t,i,n)}next(t,e){const n=e.name,s=[];let r,a=[];for(const c of this.getCandidates(n)){const{cond:d,in:u}=c,l=t.context,f=!u||(S(u)&&Vt(u)?t.matches(o(this.getStateNodeById(u).path,this.delimiter)):i(o(u,this.delimiter),h(this.path.slice(0,-2))(t.value)));let p=!1;try{p=!d||$(this.machine,d,l,e,t)}catch(t){throw new Error(`Unable to evaluate guard '${d.name||d.type}' in transition for event '${n}' in state node '${this.id}':\n${t.message}`)}if(p&&f){void 0!==c.target&&(a=c.target),s.push(...c.actions),r=c;break}}if(!r)return;if(!a.length)return{transitions:[r],entrySet:[],exitSet:[],configuration:t.value?[this]:[],source:t,actions:s};const c=u(a.map(e=>this.getRelativeStateNodes(e,t.historyValue))),d=!!r.internal;return{transitions:[r],entrySet:d?[]:u(c.map(t=>this.nodesFromChild(t))),exitSet:d?[]:[this],configuration:c,source:t,actions:s}}nodesFromChild(t){if(t.escapes(this))return[];const e=[];let i=t;for(;i&&i!==this;)e.push(i),i=i.parent;return e.push(this),e}escapes(t){if(this===t)return!1;let e=this.parent;for(;e;){if(e===t)return!1;e=e.parent}return!0}getActions(t,e,i,n){const s=R([],n?this.getStateNodes(n.value):[this]),o=t.configuration.length?R(s,t.configuration):s;for(const e of o)F(s,e)||t.entrySet.push(e);for(const e of s)F(o,e)&&!F(t.exitSet,e.parent)||t.exitSet.push(e);t.source||(t.exitSet=[],t.entrySet.push(this));const r=u(t.entrySet.map(n=>{const s=[];if("final"!==n.type)return s;const o=n.parent;if(!o.parent)return s;s.push(bt(n.id,n.doneData),bt(o.id,n.doneData?p(n.doneData,e,i):void 0));const r=o.parent;return"parallel"===r.type&&D(r).every(e=>J(t.configuration,e))&&s.push(bt(r.id)),s}));t.exitSet.sort((t,e)=>e.order-t.order),t.entrySet.sort((t,e)=>t.order-e.order);const a=new Set(t.entrySet),c=new Set(t.exitSet),[h,d]=[u(Array.from(a).map(t=>[...t.activities.map(t=>gt(t)),...t.onEntry])).concat(r.map(ht)),u(Array.from(c).map(t=>[...t.onExit,...t.activities.map(t=>vt(t))]))];return at(d.concat(t.actions).concat(h),this.machine.options.actions)}transition(t=this.initialState,e,i){const n=N(e);let s;if(t instanceof jt)s=void 0===i?t:this.resolveState(jt.from(t,i));else{const e=S(t)?this.resolve(r(this.getResolvedPath(t))):this.resolve(t),n=i||this.machine.context;s=this.resolveState(jt.from(e,n))}if(this.strict&&!this.events.includes(n.name)&&(o=n.name,!/^(done|error)\./.test(o)))throw new Error(`Machine '${this.id}' does not accept event '${n.name}'`);var o;const a=this._transition(s.value,s,n)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},c=R([],this.getStateNodes(s.value)),h=a.configuration.length?R(c,a.configuration):c;return a.configuration=[...h],this.resolveTransition(a,s,n)}resolveRaisedTransition(t,e,i){const n=t.actions;return(t=this.transition(t,e))._event=i,t.event=i.data,t.actions.unshift(...n),t}resolveTransition(t,i,n=st,s=this.machine.context){const{configuration:o}=t,r=!i||t.transitions.length>0?z(this.machine,o):void 0,a=i?i.historyValue?i.historyValue:t.source?this.machine.historyValue(i.value):void 0:void 0,c=i?i.context:s,h=this.getActions(t,c,n,i),d=i?Object.assign({},i.activities):{};for(const t of h)t.type===U?d[t.activity.id||t.activity.type]=t:t.type===B&&(d[t.activity.id||t.activity.type]=!1);const[u,l]=Ot(this,i,c,n,h),[f,g]=v(u,t=>t.type===q||t.type===X&&t.to===I.Internal),m=u.filter(t=>{var e;return t.type===U&&(null===(e=t.activity)||void 0===e?void 0:e.type)===Y}).reduce((t,e)=>(t[e.activity.id]=function(t,e,i,n){var s;const o=k(t.src),r=null===(s=null==e?void 0:e.options.services)||void 0===s?void 0:s[o.type],a=t.data?p(t.data,i,n):void 0,c=r?$t(r,t.id,a):Tt(t.id);return c.meta=t,c}(e.activity,this.machine,l,n),t),i?Object.assign({},i.children):{}),b=r?t.configuration:i?i.configuration:[],w=b.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{}),x=J(b,this),O=new jt({value:r||i.value,context:l,_event:n,_sessionid:i?i._sessionid:null,historyValue:r?a?(_=a,j=r,{current:j,states:y(_,j)}):void 0:i?i.historyValue:void 0,history:!r||t.source?i:void 0,actions:r?g:[],activities:r?d:i?i.activities:{},meta:r?w:i?i.meta:void 0,events:[],configuration:b,transitions:t.transitions,children:m,done:x});var _,j;const E=c!==l;O.changed=n.name===et||E;const{history:N}=O;if(N&&delete N.history,!r)return O;let T=O;if(!x){for((this._transient||o.some(t=>t._transient))&&(T=this.resolveRaisedTransition(T,{type:G},n));f.length;){const t=f.shift();T=this.resolveRaisedTransition(T,t._event,n)}}const $=T.changed||(N?!!T.actions.length||E||typeof N.value!=typeof T.value||!function t(i,n){if(i===n)return!0;if(void 0===i||void 0===n)return!1;if(S(i)||S(n))return i===n;const s=e(i),o=e(n);return s.length===o.length&&s.every(e=>t(i[e],n[e]))}(T.value,N.value):void 0);return T.changed=$,T.history=N,T}getStateNode(t){if(Vt(t))return this.machine.getStateNodeById(t);if(!this.states)throw new Error(`Unable to retrieve child state '${t}' from '${this.id}'; no child states exist.`);const e=this.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${this.id}'`);return e}getStateNodeById(t){const e=Vt(t)?t.slice("#".length):t;if(e===this.id)return this;const i=this.machine.idMap[e];if(!i)throw new Error(`Child state node '#${e}' does not exist on machine '${this.id}'`);return i}getStateNodeByPath(t){if("string"==typeof t&&Vt(t))try{return this.getStateNodeById(t.slice(1))}catch(t){}const e=s(t,this.delimiter).slice();let i=this;for(;e.length;){const t=e.shift();if(!t.length)break;i=i.getStateNode(t)}return i}resolve(t){if(!t)return this.initialStateValue||Ct;switch(this.type){case"parallel":return a(this.initialStateValue,(e,i)=>e?this.getStateNode(i).resolve(t[i]||e):Ct);case"compound":if(S(t)){const e=this.getStateNode(t);return"parallel"===e.type||"compound"===e.type?{[t]:e.initialStateValue}:t}return e(t).length?a(t,(t,e)=>t?this.getStateNode(e).resolve(t):Ct):this.initialStateValue||{};default:return t||Ct}}getResolvedPath(t){if(Vt(t)){const e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error(`Unable to find state node '${t}'`);return e.path}return s(t,this.delimiter)}get initialStateValue(){if(this.__cache.initialStateValue)return this.__cache.initialStateValue;let t;if("parallel"===this.type)t=c(this.states,t=>t.initialStateValue||Ct,t=>!("history"===t.type));else if(void 0!==this.initial){if(!this.states[this.initial])throw new Error(`Initial state '${this.initial}' not found on '${this.key}'`);t=L(this.states[this.initial])?this.initial:{[this.initial]:this.states[this.initial].initialStateValue}}else t={};return this.__cache.initialStateValue=t,this.__cache.initialStateValue}getInitialState(t,e){const i=this.getStateNodes(t);return this.resolveTransition({configuration:i,entrySet:i,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,void 0,e)}get initialState(){this._init();const{initialStateValue:t}=this;if(!t)throw new Error(`Cannot retrieve initial state from simple state '${this.id}'.`);return this.getInitialState(t)}get target(){let t;if("history"===this.type){const e=this.config;t=S(e.target)&&Vt(e.target)?r(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t}getRelativeStateNodes(t,e,i=!0){return i?"history"===t.type?t.resolveHistory(e):t.initialStateNodes:[t]}get initialStateNodes(){if(L(this))return[this];if("compound"===this.type&&!this.initial)return[this];return u(d(this.initialStateValue).map(t=>this.getFromRelativePath(t)))}getFromRelativePath(t){if(!t.length)return[this];const[e,...i]=t;if(!this.states)throw new Error(`Cannot retrieve subPath '${e}' from node with no states`);const n=this.getStateNode(e);if("history"===n.type)return n.resolveHistory();if(!this.states[e])throw new Error(`Child state '${e}' does not exist on '${this.id}'`);return this.states[e].getFromRelativePath(i)}historyValue(t){if(e(this.states).length)return{current:t||this.initialStateValue,states:c(this.states,(e,i)=>{if(!t)return e.historyValue();const n=S(t)?void 0:t[i];return e.historyValue(n||e.initialStateValue)},t=>!t.history)}}resolveHistory(t){if("history"!==this.type)return[this];const e=this.parent;if(!t){const t=this.target;return t?u(d(t).map(t=>e.getFromRelativePath(t))):e.initialStateNodes}const i=(n=e.path,s="states",t=>{let e=t;for(const t of n)e=e[s][t];return e})(t).current;var n,s;return S(i)?[e.getStateNode(i)]:u(d(i).map(t=>"deep"===this.history?e.getFromRelativePath(t):[e.states[t[0]]]))}get stateIds(){const t=u(e(this.states).map(t=>this.states[t].stateIds));return[this.id].concat(t)}get events(){if(this.__cache.events)return this.__cache.events;const{states:t}=this,i=new Set(this.ownEvents);if(t)for(const n of e(t)){const e=t[n];if(e.states)for(const t of e.events)i.add(""+t)}return this.__cache.events=Array.from(i)}get ownEvents(){const t=new Set(this.transitions.filter(t=>!(!t.target&&!t.actions.length&&t.internal)).map(t=>t.eventType));return Array.from(t)}resolveTarget(t){if(void 0!==t)return t.map(t=>{if(!S(t))return t;const e=t[0]===this.delimiter;if(e&&!this.parent)return this.getStateNodeByPath(t.slice(1));const i=e?this.key+t:t;if(!this.parent)return this.getStateNodeByPath(i);try{return this.parent.getStateNodeByPath(i)}catch(t){throw new Error(`Invalid transition definition for state node '${this.id}':\n${t.message}`)}})}formatTransition(t){const e=function(t){if(void 0!==t&&""!==t)return f(t)}(t.target),i="internal"in t?t.internal:!e||e.some(t=>S(t)&&t[0]===this.delimiter),{guards:n}=this.machine.options,s=this.resolveTarget(e),o=Object.assign(Object.assign({},t),{actions:at(f(t.actions)),cond:w(t.cond,n),target:s,source:this,internal:i,eventType:t.event,toJSON:()=>Object.assign(Object.assign({},o),{target:o.target?o.target.map(t=>"#"+t.id):void 0,source:"#"+this.id})});return o}formatTransitions(){let t;if(this.config.on)if(Array.isArray(this.config.on))t=this.config.on;else{const i=this.config.on,n="*",s=i[n],o=void 0===s?[]:s,r=C(i,[n+""]);t=u(e(r).map(t=>T(t,r[t])).concat(T("*",o)))}else t=[];const i=this.config.always?T("",this.config.always):[],n=this.config.onDone?T(String(bt(this.id)),this.config.onDone):[],s=u(this.invoke.map(t=>{const e=[];return t.onDone&&e.push(...T(String(St(t.id)),t.onDone)),t.onError&&e.push(...T(String(wt(t.id)),t.onError)),e})),o=this.after,r=u([...n,...s,...t,...i].map(t=>f(t).map(t=>this.formatTransition(t))));for(const t of o)r.push(t);return r}}function Lt(t,e,i=t.context){const n="function"==typeof i?i():i;return new It(t,e,n)}function Dt(t,e){const i="function"==typeof t.context?t.context():t.context;return new It(t,e,i)}const At={deferEvents:!1};class Rt{constructor(t){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=Object.assign(Object.assign({},At),t)}initialize(t){if(this.initialized=!0,t){if(!this.options.deferEvents)return void this.schedule(t);this.process(t)}this.flushEvents()}schedule(t){if(this.initialized&&!this.processingEvent){if(0!==this.queue.length)throw new Error("Event queue should be empty when it is not processing events");this.process(t),this.flushEvents()}else this.queue.push(t)}clear(){this.queue=[]}flushEvents(){let t=this.queue.shift();for(;t;)this.process(t),t=this.queue.shift()}process(t){this.processingEvent=!0;try{t()}catch(t){throw this.clear(),t}finally{this.processingEvent=!1}}}const Mt=new Map;let zt=0;const Ft={bookId:()=>"x:"+zt++,register:(t,e)=>(Mt.set(t,e),t),get:t=>Mt.get(t),free(t){Mt.delete(t)}};function Jt(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0}function Ut(t){if(!Jt())return;const e=function(){const t=Jt();if(t&&"__xstate__"in t)return t.__xstate__}();e&&e.register(t)}const Bt={sync:!1,autoForward:!1};var qt;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(qt||(qt={}));class Xt{constructor(t,e=Xt.defaultOptions){this.machine=t,this.scheduler=new Rt,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=qt.NotStarted,this.children=new Map,this.forwardTo=new Set,this.init=this.start,this.send=(t,e)=>{if(m(t))return this.batch(t),this.state;const i=N(E(t,e));if(this.status===qt.Stopped)return this.state;if(this.status!==qt.Running&&!this.options.deferEvents)throw new Error(`Event "${i.name}" was sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ${JSON.stringify(i.data)}`);return this.scheduler.schedule(()=>{this.forward(i);const t=this.nextState(i);this.update(t,i)}),this._state},this.sendTo=(t,e)=>{const i=this.parent&&(e===I.Parent||this.parent.id===e),n=i?this.parent:S(e)?this.children.get(e)||Ft.get(e):(s=e)&&"function"==typeof s.send?e:void 0;var s;if(n)"machine"in n?n.send(Object.assign(Object.assign({},t),{name:t.name===tt?""+wt(this.id):t.name,origin:this.sessionId})):n.send(t.data);else if(!i)throw new Error(`Unable to send event to child '${e}' from service '${this.id}'.`)};const i=Object.assign(Object.assign({},Xt.defaultOptions),e),{clock:n,logger:s,parent:o,id:r}=i,a=void 0!==r?r:t.id;this.id=a,this.logger=s,this.clock=n,this.parent=o,this.options=i,this.scheduler=new Rt({deferEvents:this.options.deferEvents}),this.sessionId=Ft.bookId()}get initialState(){return this._initialState?this._initialState:Nt(this,()=>(this._initialState=this.machine.initialState,this._initialState))}get state(){return this._state}execute(t,e){for(const i of t.actions)this.exec(i,t,e)}update(t,e){if(t._sessionid=this.sessionId,this._state=t,this.options.execute&&this.execute(this.state),this.children.forEach(t=>{this.state.children[t.id]=t}),this.devTools&&this.devTools.send(e.data,t),t.event)for(const e of this.eventListeners)e(t.event);for(const e of this.listeners)e(t,t.event);for(const t of this.contextListeners)t(this.state.context,this.state.history?this.state.history.context:void 0);const i=J(t.configuration||[],this.machine);if(this.state.configuration&&i){const i=t.configuration.find(t=>"final"===t.type&&t.parent===this.machine),n=i&&i.doneData?p(i.doneData,t.context,e):void 0;for(const t of this.doneListeners)t(St(this.id,n));this.stop()}}onTransition(t){return this.listeners.add(t),this.status===qt.Running&&t(this.state,this.state.event),this}subscribe(t,e,i){if(!t)return{unsubscribe:()=>{}};let n,s=i;return"function"==typeof t?n=t:(n=t.next.bind(t),s=t.complete.bind(t)),this.listeners.add(n),this.status===qt.Running&&n(this.state),s&&this.onDone(s),{unsubscribe:()=>{n&&this.listeners.delete(n),s&&this.doneListeners.delete(s)}}}onEvent(t){return this.eventListeners.add(t),this}onSend(t){return this.sendListeners.add(t),this}onChange(t){return this.contextListeners.add(t),this}onStop(t){return this.stopListeners.add(t),this}onDone(t){return this.doneListeners.add(t),this}off(t){return this.listeners.delete(t),this.eventListeners.delete(t),this.sendListeners.delete(t),this.stopListeners.delete(t),this.doneListeners.delete(t),this.contextListeners.delete(t),this}start(t){if(this.status===qt.Running)return this;Ft.register(this.sessionId,this),this.initialized=!0,this.status=qt.Running;const e=void 0===t?this.initialState:Nt(this,()=>{return!S(e=t)&&"value"in e&&"history"in e?this.machine.resolveState(t):this.machine.resolveState(jt.from(t,this.machine.context));var e});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(()=>{this.update(e,st)}),this}stop(){for(const t of this.listeners)this.listeners.delete(t);for(const t of this.stopListeners)t(),this.stopListeners.delete(t);for(const t of this.contextListeners)this.contextListeners.delete(t);for(const t of this.doneListeners)this.doneListeners.delete(t);if(!this.initialized)return this;this.state.configuration.forEach(t=>{for(const e of t.definition.exit)this.exec(e,this.state)}),this.children.forEach(t=>{b(t.stop)&&t.stop()});for(const t of e(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.scheduler.clear(),this.initialized=!1,this.status=qt.Stopped,Ft.free(this.sessionId),this}batch(t){if(this.status===qt.NotStarted&&this.options.deferEvents);else if(this.status!==qt.Running)throw new Error(`${t.length} event(s) were sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.`);this.scheduler.schedule(()=>{let e=this.state,i=!1;const n=[];for(const s of t){const t=N(s);this.forward(t),e=Nt(this,()=>this.machine.transition(e,t)),n.push(...e.actions.map(t=>_t(t,e))),i=i||!!e.changed}e.changed=i,e.actions=n,this.update(e,N(t[t.length-1]))})}sender(t){return this.send.bind(this,t)}nextState(t){const e=N(t);if(0===e.name.indexOf(Z)&&!this.state.nextEvents.some(t=>0===t.indexOf(Z)))throw e.data.data;return Nt(this,()=>this.machine.transition(this.state,e))}forward(t){for(const e of this.forwardTo){const i=this.children.get(e);if(!i)throw new Error(`Unable to forward event '${t}' from interpreter '${this.id}' to nonexistant child '${e}'.`);i.send(t)}}defer(t){this.delayedEventsMap[t.id]=this.clock.setTimeout(()=>{t.to?this.sendTo(t._event,t.to):this.send(t._event)},t.delay)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}exec(t,e,i=this.machine.options.actions){const{context:n,_event:s}=e,o=t.exec||ot(t.type,i),r=b(o)?o:o?o.exec:t.exec;if(r)try{return r(n,s.data,{action:t,state:this.state,_event:s})}catch(t){throw this.parent&&this.parent.send({type:"xstate.error",data:t}),t}switch(t.type){case X:const e=t;if("number"==typeof e.delay)return void this.defer(e);e.to?this.sendTo(e._event,e.to):this.send(e._event);break;case H:this.cancel(t.sendId);break;case U:{const e=t.activity;if(!this.state.activities[e.id||e.type])break;if(e.type===V.Invoke){const t=k(e.src),i=this.machine.options.services?this.machine.options.services[t.type]:void 0,{id:o,data:r}=e,a="autoForward"in e?e.autoForward:!!e.forward;if(!i)return;const c=r?p(r,n,s):void 0,h=b(i)?i(n,s.data,{data:c,src:t}):i;g(h)?this.spawnPromise(Promise.resolve(h),o):b(h)?this.spawnCallback(h,o):x(h)?this.spawnObservable(h,o):_(h)&&this.spawnMachine(c?h.withContext(c):h,{id:o,autoForward:a})}else this.spawnActivity(e);break}case B:this.stopChild(t.activity.id);break;case Q:const{label:i,value:o}=t;i?this.logger(i,o):this.logger(o)}}removeChild(t){this.children.delete(t),this.forwardTo.delete(t),delete this.state.children[t]}stopChild(t){const e=this.children.get(t);e&&(this.removeChild(t),b(e.stop)&&e.stop())}spawn(t,e,i){if(g(t))return this.spawnPromise(Promise.resolve(t),e);if(b(t))return this.spawnCallback(t,e);if(function(t){try{return"function"==typeof t.send}catch(t){return!1}}(n=t)&&"id"in n)return this.spawnActor(t);if(x(t))return this.spawnObservable(t,e);if(_(t))return this.spawnMachine(t,Object.assign(Object.assign({},i),{id:e}));throw new Error(`Unable to spawn entity "${e}" of type "${typeof t}".`);var n}spawnMachine(t,e={}){const i=new Xt(t,Object.assign(Object.assign({},this.options),{parent:this,id:e.id||t.id})),n=Object.assign(Object.assign({},Bt),e);n.sync&&i.onTransition(t=>{this.send(et,{state:t,id:i.id})});const s=i;return this.children.set(i.id,s),n.autoForward&&this.forwardTo.add(i.id),i.onDone(t=>{this.removeChild(i.id),this.send(N(t,{origin:i.id}))}).start(),s}spawnPromise(t,e){let i=!1;t.then(t=>{i||(this.removeChild(e),this.send(N(St(e,t),{origin:e})))},t=>{if(!i){this.removeChild(e);const i=wt(e,t);try{this.send(N(i,{origin:e}))}catch(t){this.devTools&&this.devTools.send(i,this.state),this.machine.strict&&this.stop()}}});const n={id:e,send:()=>{},subscribe:(e,i,n)=>{const s=function(t,e,i){if("object"==typeof t)return t;const n=()=>{};return{next:t,error:e||n,complete:i||n}}(e,i,n);let o=!1;return t.then(t=>{o||(s.next(t),o||s.complete())},t=>{o||s.error(t)}),{unsubscribe:()=>o=!0}},stop:()=>{i=!0},toJSON:()=>({id:e})};return this.children.set(e,n),n}spawnCallback(t,e){let i=!1;const n=new Set,s=new Set,o=t=>{s.forEach(e=>e(t)),i||this.send(N(t,{origin:e}))};let r;try{r=t(o,t=>{n.add(t)})}catch(t){this.send(wt(e,t))}if(g(r))return this.spawnPromise(r,e);const a={id:e,send:t=>n.forEach(e=>e(t)),subscribe:t=>(s.add(t),{unsubscribe:()=>{s.delete(t)}}),stop:()=>{i=!0,b(r)&&r()},toJSON:()=>({id:e})};return this.children.set(e,a),a}spawnObservable(t,e){const i=t.subscribe(t=>{this.send(N(t,{origin:e}))},t=>{this.removeChild(e),this.send(N(wt(e,t),{origin:e}))},()=>{this.removeChild(e),this.send(N(St(e),{origin:e}))}),n={id:e,send:()=>{},subscribe:(e,i,n)=>t.subscribe(e,i,n),stop:()=>i.unsubscribe(),toJSON:()=>({id:e})};return this.children.set(e,n),n}spawnActor(t){return this.children.set(t.id,t),t}spawnActivity(t){const e=this.machine.options&&this.machine.options.activities?this.machine.options.activities[t.type]:void 0;if(!e)return;const i=e(this.state.context,t);this.spawnEffect(t.id,i)}spawnEffect(t,e){this.children.set(t,{id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),stop:e||void 0,toJSON:()=>({id:t})})}attachDev(){const t=Jt();if(this.options.devTools&&t){if(t.__REDUX_DEVTOOLS_EXTENSION__){const e="object"==typeof this.options.devTools?this.options.devTools:void 0;this.devTools=t.__REDUX_DEVTOOLS_EXTENSION__.connect(Object.assign(Object.assign({name:this.id,autoPause:!0,stateSanitizer:t=>({value:t.value,context:t.context,actions:t.actions})},e),{features:Object.assign({jump:!1,skip:!1},e?e.features:void 0)}),this.machine),this.devTools.init(this.state)}Ut(this)}}toJSON(){return{id:this.id}}[O](){return this}}Xt.defaultOptions=(t=>({execute:!0,deferEvents:!0,clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:t.console.log.bind(console),devTools:!1}))("undefined"!=typeof self?self:global),Xt.interpret=Gt;function Ht(t,e){const i=(t=>S(t)?Object.assign(Object.assign({},Bt),{name:t}):Object.assign(Object.assign(Object.assign({},Bt),{name:j()}),t))(e);return(e=>e?e.spawn(t,i.name,i):$t(t,i.name))(Et[Et.length-1])}function Gt(t,e){return new Xt(t,e)}function Kt(t,e,i){const n=jt.from(t,t instanceof jt?t.context:void 0);for(const[t,i]of e)if(n.matches(t))return i(n);return i(n)}function Qt(t){return t}const Wt={raise:ht,send:dt,sendParent:ut,sendUpdate:lt,log:function(t=ft,e){return{type:Q,label:e,expr:t}},cancel:pt,start:gt,stop:vt,assign:yt,after:mt,done:bt,respond:function(t,e){return dt(t,Object.assign(Object.assign({},e),{to:(t,e,{_event:i})=>i.origin}))},forwardTo:xt,escalate:function(t,e){return ut((e,i,n)=>({type:tt,data:b(t)?t(e,i,n):t}),Object.assign(Object.assign({},e),{to:I.Parent}))},choose:function(t){return{type:V.Choose,conds:t}},pure:function(t){return{type:V.Pure,get:t}}};export{V as ActionTypes,Xt as Interpreter,qt as InterpreterStatus,Lt as Machine,I as SpecialTargets,jt as State,It as StateNode,Wt as actions,yt as assign,Dt as createMachine,Qt as createSchema,St as doneInvoke,xt as forwardTo,Gt as interpret,P as mapState,Kt as matchState,i as matchesState,dt as send,ut as sendParent,lt as sendUpdate,Ht as spawn};
15
+ ***************************************************************************** */function C(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(i[s[n]]=t[s[n]])}return i}var V,I;!function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"}(V||(V={})),function(t){t.Parent="#_parent",t.Internal="#_internal"}(I||(I={}));const L=t=>"atomic"===t.type||"final"===t.type;function D(t){return e(t.states).map(e=>t.states[e])}function A(t){const e=[t];return L(t)?e:e.concat(u(D(t).map(A)))}function R(t,e){const i=M(new Set(t)),s=new Set(e);for(const t of s){let e=t.parent;for(;e&&!s.has(e);)s.add(e),e=e.parent}const n=M(s);for(const t of s)if("compound"!==t.type||n.get(t)&&n.get(t).length){if("parallel"===t.type)for(const e of D(t))"history"!==e.type&&(s.has(e)||(s.add(e),i.get(e)?i.get(e).forEach(t=>s.add(t)):e.initialStateNodes.forEach(t=>s.add(t))))}else i.get(t)?i.get(t).forEach(t=>s.add(t)):t.initialStateNodes.forEach(t=>s.add(t));for(const t of s){let e=t.parent;for(;e&&!s.has(e);)s.add(e),e=e.parent}return s}function M(t){const e=new Map;for(const i of t)e.has(i)||e.set(i,[]),i.parent&&(e.has(i.parent)||e.set(i.parent,[]),e.get(i.parent).push(i));return e}function z(t,e){return function t(e,i){const s=i.get(e);if(!s)return{};if("compound"===e.type){const t=s[0];if(!t)return{};if(L(t))return t.key}const n={};return s.forEach(e=>{n[e.key]=t(e,i)}),n}(t,M(R([t],e)))}function F(t,e){return Array.isArray(t)?t.some(t=>t===e):t instanceof Set&&t.has(e)}function J(t,e){return"compound"===e.type?D(e).some(e=>"final"===e.type&&F(t,e)):"parallel"===e.type&&D(e).every(e=>J(t,e))}const U=V.Start,B=V.Stop,q=V.Raise,X=V.Send,H=V.Cancel,G=V.NullEvent,K=V.Assign,Q=(V.After,V.DoneState,V.Log),W=V.Init,Y=V.Invoke,Z=(V.ErrorExecution,V.ErrorPlatform),tt=V.ErrorCustom,et=V.Update,it=V.Choose,st=V.Pure,nt=N({type:W});function ot(t,e){return e&&e[t]||void 0}function rt(t,e){let i;if(S(t)||"number"==typeof t){const s=ot(t,e);i=b(s)?{type:t,exec:s}:s||{type:t,exec:void 0}}else if(b(t))i={type:t.name||t.toString(),exec:t};else{const s=ot(t.type,e);if(b(s))i=Object.assign(Object.assign({},t),{exec:s});else if(s){const e=s.type||t.type;i=Object.assign(Object.assign(Object.assign({},s),t),{type:e})}else i=t}return Object.defineProperty(i,"toString",{value:()=>i.type,enumerable:!1,configurable:!0}),i}const at=(t,e)=>{if(!t)return[];return(m(t)?t:[t]).map(t=>rt(t,e))};function ct(t){const e=rt(t);return Object.assign(Object.assign({id:S(t)?t:e.id},e),{type:e.type})}function ht(t){return S(t)?{type:q,event:t}:dt(t,{to:I.Internal})}function dt(t,e){return{to:e?e.to:void 0,type:X,event:b(t)?t:E(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:b(t)?t.name:s(t)}}function ut(t,e){return dt(t,Object.assign(Object.assign({},e),{to:I.Parent}))}function lt(){return ut(et)}const ft=(t,e)=>({context:t,event:e});const pt=t=>({type:H,sendId:t});function gt(t){const e=ct(t);return{type:V.Start,activity:e,exec:void 0}}function vt(t){const e=b(t)?t:ct(t);return{type:V.Stop,activity:e,exec:void 0}}const yt=t=>({type:K,assignment:t});function mt(t,e){const i=e?"#"+e:"";return`${V.After}(${t})${i}`}function bt(t,e){const i=`${V.DoneState}.${t}`,s={type:i,data:e,toString:()=>i};return s}function St(t,e){const i=`${V.DoneInvoke}.${t}`,s={type:i,data:e,toString:()=>i};return s}function wt(t,e){const i=`${V.ErrorPlatform}.${t}`,s={type:i,data:e,toString:()=>i};return s}function xt(t,e){return dt((t,e)=>e,Object.assign(Object.assign({},e),{to:t}))}function Ot(t,i,s,n,o){const[r,a]=v(o,t=>t.type===K);let c=r.length?function(t,i,s,n){return t?s.reduce((t,s)=>{const{assignment:o}=s,r={state:n,action:s,_event:i};let a={};if(b(o))a=o(t,i.data,r);else for(const s of e(o)){const e=o[s];a[s]=b(e)?e(t,i.data,r):e}return Object.assign({},t,a)},t):t}(s,n,r,i):s;return[u(a.map(e=>{var s;switch(e.type){case q:return{type:q,_event:N(e.event)};case X:return function(t,e,i,s){const n={_event:i},o=N(b(t.event)?t.event(e,i.data,n):t.event);let r;if(S(t.delay)){const o=s&&s[t.delay];r=b(o)?o(e,i.data,n):o}else r=b(t.delay)?t.delay(e,i.data,n):t.delay;const a=b(t.to)?t.to(e,i.data,n):t.to;return Object.assign(Object.assign({},t),{to:a,_event:o,event:o.data,delay:r})}(e,c,n,t.options.delays);case Q:return((t,e,i)=>Object.assign(Object.assign({},t),{value:S(t.expr)?t.expr:t.expr(e,i.data,{_event:i})}))(e,c,n);case it:{const o=null===(s=e.conds.find(e=>{const s=w(e.cond,t.options.guards);return!s||$(t,s,c,n,i)}))||void 0===s?void 0:s.actions;if(!o)return[];const r=Ot(t,i,c,n,at(f(o),t.options.actions));return c=r[1],r[0]}case st:{const s=e.get(c,n.data);if(!s)return[];const o=Ot(t,i,c,n,at(f(s),t.options.actions));return c=o[1],o[0]}case B:return function(t,e,i){const s=b(t.activity)?t.activity(e,i.data):t.activity,n="string"==typeof s?{id:s}:s;return{type:V.Stop,activity:n}}(e,c,n);default:return rt(e,t.options.actions)}})),c]}function _t(t,e){const{exec:i}=t;return Object.assign(Object.assign({},t),{exec:void 0!==i?()=>i(e.context,e.event,{action:t,state:e,_event:e._event}):void 0})}class jt{constructor(e){var i;this.actions=[],this.activities=t,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||t,this.meta=e.meta||{},this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=null!==(i=e.tags)&&void 0!==i?i:new Set,Object.defineProperty(this,"nextEvents",{get:()=>{return t=this.configuration,[...new Set(u([...t.map(t=>t.ownEvents)]))];var t}})}static from(t,e){if(t instanceof jt)return t.context!==e?new jt({value:t.value,context:e,_event:t._event,_sessionid:null,historyValue:t.historyValue,history:t.history,actions:[],activities:t.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):t;return new jt({value:t,context:e,_event:nt,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})}static create(t){return new jt(t)}static inert(t,e){if(t instanceof jt){if(!t.actions.length)return t;const i=nt;return new jt({value:t.value,context:e,_event:i,_sessionid:null,historyValue:t.historyValue,history:t.history,activities:t.activities,configuration:t.configuration,transitions:[],children:{}})}return jt.from(t,e)}toStrings(t=this.value,i="."){if(S(t))return[t];const s=e(t);return s.concat(...s.map(e=>this.toStrings(t[e],i).map(t=>e+i+t)))}toJSON(){const{configuration:t,transitions:e,tags:i}=this,s=C(this,["configuration","transitions","tags"]);return Object.assign(Object.assign({},s),{tags:Array.from(i)})}matches(t){return i(t,this.value)}hasTag(t){return this.tags.has(t)}}const Et=[],Nt=(t,e)=>{Et.push(t);const i=e(t);return Et.pop(),i};function Tt(t){return{id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),getSnapshot:()=>{},toJSON:()=>({id:t})}}function $t(t,e,i){const s=Tt(e);return s.deferred=!0,_(t)&&(s.state=Nt(void 0,()=>(i?t.withContext(i):t).initialState)),s}function kt(t){if("string"==typeof t){const e={type:t,toString:()=>t};return e}return t}function Pt(t){return Object.assign(Object.assign({type:Y},t),{toJSON(){const e=C(t,["onDone","onError"]);return Object.assign(Object.assign({},e),{type:Y,src:kt(t.src)})}})}const Ct={},Vt=t=>"#"===t[0];class It{constructor(t,i,s){var n;this.config=t,this.context=s,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign({actions:{},guards:{},services:{},activities:{},delays:{}},i),this.parent=this.options._parent,this.key=this.config.key||this.options._key||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:"."),this.id=this.config.id||[this.machine.key,...this.path].join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&e(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:null!==(n=this.config.schema)&&void 0!==n?n:{},this.initial=this.config.initial,this.states=this.config.states?a(this.config.states,(t,e)=>{const i=new It(t,{_parent:this,_key:e});return Object.assign(this.idMap,Object.assign({[i.id]:i},i.idMap)),i}):Ct;let o=0;!function t(e){e.order=o++;for(const i of D(e))t(i)}(this),this.history=!0===this.config.history?"shallow":this.config.history||!1,this._transient=!!this.config.always||!!this.config.on&&(Array.isArray(this.config.on)?this.config.on.some(({event:t})=>""===t):""in this.config.on),this.strict=!!this.config.strict,this.onEntry=f(this.config.entry||this.config.onEntry).map(t=>rt(t)),this.onExit=f(this.config.exit||this.config.onExit).map(t=>rt(t)),this.meta=this.config.meta,this.doneData="final"===this.type?this.config.data:void 0,this.invoke=f(this.config.invoke).map((t,e)=>{if(_(t))return this.machine.options.services=Object.assign({[t.id]:t},this.machine.options.services),Pt({src:t.id,id:t.id});if(S(t.src))return Pt(Object.assign(Object.assign({},t),{id:t.id||t.src,src:t.src}));if(_(t.src)||b(t.src)){const i=`${this.id}:invocation[${e}]`;return this.machine.options.services=Object.assign({[i]:t.src},this.machine.options.services),Pt(Object.assign(Object.assign({id:i},t),{src:i}))}{const e=t.src;return Pt(Object.assign(Object.assign({id:e.type},t),{src:e}))}}),this.activities=f(this.config.activities).concat(this.invoke).map(t=>ct(t)),this.transition=this.transition.bind(this),this.tags=f(this.config.tags)}_init(){this.__cache.transitions||A(this).forEach(t=>t.on)}withConfig(t,e=this.context){const{actions:i,activities:s,guards:n,services:o,delays:r}=this.options;return new It(this.config,{actions:Object.assign(Object.assign({},i),t.actions),activities:Object.assign(Object.assign({},s),t.activities),guards:Object.assign(Object.assign({},n),t.guards),services:Object.assign(Object.assign({},o),t.services),delays:Object.assign(Object.assign({},r),t.delays)},e)}withContext(t){return new It(this.config,this.options,t)}get definition(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:a(this.states,t=>t.definition),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke}}toJSON(){return this.definition}get on(){if(this.__cache.on)return this.__cache.on;const t=this.transitions;return this.__cache.on=t.reduce((t,e)=>(t[e.eventType]=t[e.eventType]||[],t[e.eventType].push(e),t),{})}get after(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)}get transitions(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)}getCandidates(t){if(this.__cache.candidates[t])return this.__cache.candidates[t];const e=""===t,i=this.transitions.filter(i=>{const s=i.eventType===t;return e?s:s||"*"===i.eventType});return this.__cache.candidates[t]=i,i}getDelayedTransitions(){const t=this.config.after;if(!t)return[];const i=(t,e)=>{const i=mt(b(t)?`${this.id}:delay[${e}]`:t,this.id);return this.onEntry.push(dt(i,{delay:t})),this.onExit.push(pt(i)),i};return(m(t)?t.map((t,e)=>{const s=i(t.delay,e);return Object.assign(Object.assign({},t),{event:s})}):u(e(t).map((e,s)=>{const n=t[e],o=S(n)?{target:n}:n,r=isNaN(+e)?e:+e,a=i(r,s);return f(o).map(t=>Object.assign(Object.assign({},t),{event:a,delay:r}))}))).map(t=>{const{delay:e}=t;return Object.assign(Object.assign({},this.formatTransition(t)),{delay:e})})}getStateNodes(t){if(!t)return[];const i=t instanceof jt?t.value:o(t,this.delimiter);if(S(i)){const t=this.getStateNode(i).initial;return void 0!==t?this.getStateNodes({[i]:t}):[this,this.states[i]]}const s=e(i),n=s.map(t=>this.getStateNode(t));return n.push(this),n.concat(s.reduce((t,e)=>{const s=this.getStateNode(e).getStateNodes(i[e]);return t.concat(s)},[]))}handles(t){const e=s(t);return this.events.includes(e)}resolveState(t){const e=Array.from(R([],this.getStateNodes(t.value)));return new jt(Object.assign(Object.assign({},t),{value:this.resolve(t.value),configuration:e,done:J(e,this)}))}transitionLeafNode(t,e,i){const s=this.getStateNode(t).next(e,i);return s&&s.transitions.length?s:this.next(e,i)}transitionCompoundNode(t,i,s){const n=e(t),o=this.getStateNode(n[0])._transition(t[n[0]],i,s);return o&&o.transitions.length?o:this.next(i,s)}transitionParallelNode(t,i,s){const n={};for(const o of e(t)){const e=t[o];if(!e)continue;const r=this.getStateNode(o)._transition(e,i,s);r&&(n[o]=r)}const o=e(n).map(t=>n[t]),r=u(o.map(t=>t.transitions));if(!o.some(t=>t.transitions.length>0))return this.next(i,s);const a=u(o.map(t=>t.entrySet)),c=u(e(n).map(t=>n[t].configuration));return{transitions:r,entrySet:a,exitSet:u(o.map(t=>t.exitSet)),configuration:c,source:i,actions:u(e(n).map(t=>n[t].actions))}}_transition(t,i,s){return S(t)?this.transitionLeafNode(t,i,s):1===e(t).length?this.transitionCompoundNode(t,i,s):this.transitionParallelNode(t,i,s)}next(t,e){const s=e.name,n=[];let r,a=[];for(const c of this.getCandidates(s)){const{cond:d,in:u}=c,l=t.context,f=!u||(S(u)&&Vt(u)?t.matches(o(this.getStateNodeById(u).path,this.delimiter)):i(o(u,this.delimiter),h(this.path.slice(0,-2))(t.value)));let p=!1;try{p=!d||$(this.machine,d,l,e,t)}catch(t){throw new Error(`Unable to evaluate guard '${d.name||d.type}' in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(p&&f){void 0!==c.target&&(a=c.target),n.push(...c.actions),r=c;break}}if(!r)return;if(!a.length)return{transitions:[r],entrySet:[],exitSet:[],configuration:t.value?[this]:[],source:t,actions:n};const c=u(a.map(e=>this.getRelativeStateNodes(e,t.historyValue))),d=!!r.internal;return{transitions:[r],entrySet:d?[]:u(c.map(t=>this.nodesFromChild(t))),exitSet:d?[]:[this],configuration:c,source:t,actions:n}}nodesFromChild(t){if(t.escapes(this))return[];const e=[];let i=t;for(;i&&i!==this;)e.push(i),i=i.parent;return e.push(this),e}escapes(t){if(this===t)return!1;let e=this.parent;for(;e;){if(e===t)return!1;e=e.parent}return!0}getActions(t,e,i,s){const n=R([],s?this.getStateNodes(s.value):[this]),o=t.configuration.length?R(n,t.configuration):n;for(const e of o)F(n,e)||t.entrySet.push(e);for(const e of n)F(o,e)&&!F(t.exitSet,e.parent)||t.exitSet.push(e);t.source||(t.exitSet=[],t.entrySet.push(this));const r=u(t.entrySet.map(s=>{const n=[];if("final"!==s.type)return n;const o=s.parent;if(!o.parent)return n;n.push(bt(s.id,s.doneData),bt(o.id,s.doneData?p(s.doneData,e,i):void 0));const r=o.parent;return"parallel"===r.type&&D(r).every(e=>J(t.configuration,e))&&n.push(bt(r.id)),n}));t.exitSet.sort((t,e)=>e.order-t.order),t.entrySet.sort((t,e)=>t.order-e.order);const a=new Set(t.entrySet),c=new Set(t.exitSet),[h,d]=[u(Array.from(a).map(t=>[...t.activities.map(t=>gt(t)),...t.onEntry])).concat(r.map(ht)),u(Array.from(c).map(t=>[...t.onExit,...t.activities.map(t=>vt(t))]))];return at(d.concat(t.actions).concat(h),this.machine.options.actions)}transition(t=this.initialState,e,i){const s=N(e);let n;if(t instanceof jt)n=void 0===i?t:this.resolveState(jt.from(t,i));else{const e=S(t)?this.resolve(r(this.getResolvedPath(t))):this.resolve(t),s=i||this.machine.context;n=this.resolveState(jt.from(e,s))}if(this.strict&&!this.events.includes(s.name)&&(o=s.name,!/^(done|error)\./.test(o)))throw new Error(`Machine '${this.id}' does not accept event '${s.name}'`);var o;const a=this._transition(n.value,n,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:n,actions:[]},c=R([],this.getStateNodes(n.value)),h=a.configuration.length?R(c,a.configuration):c;return a.configuration=[...h],this.resolveTransition(a,n,s)}resolveRaisedTransition(t,e,i){const s=t.actions;return(t=this.transition(t,e))._event=i,t.event=i.data,t.actions.unshift(...s),t}resolveTransition(t,i,s=nt,n=this.machine.context){const{configuration:o}=t,r=!i||t.transitions.length>0?z(this.machine,o):void 0,a=i?i.historyValue?i.historyValue:t.source?this.machine.historyValue(i.value):void 0:void 0,c=i?i.context:n,h=this.getActions(t,c,s,i),d=i?Object.assign({},i.activities):{};for(const t of h)t.type===U?d[t.activity.id||t.activity.type]=t:t.type===B&&(d[t.activity.id||t.activity.type]=!1);const[l,f]=Ot(this,i,c,s,h),[g,m]=v(l,t=>t.type===q||t.type===X&&t.to===I.Internal),b=l.filter(t=>{var e;return t.type===U&&(null===(e=t.activity)||void 0===e?void 0:e.type)===Y}).reduce((t,e)=>(t[e.activity.id]=function(t,e,i,s){var n;const o=k(t.src),r=null===(n=null==e?void 0:e.options.services)||void 0===n?void 0:n[o.type],a=t.data?p(t.data,i,s):void 0,c=r?$t(r,t.id,a):Tt(t.id);return c.meta=t,c}(e.activity,this.machine,f,s),t),i?Object.assign({},i.children):{}),w=r?t.configuration:i?i.configuration:[],x=w.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{}),O=J(w,this),_=new jt({value:r||i.value,context:f,_event:s,_sessionid:i?i._sessionid:null,historyValue:r?a?(j=a,E=r,{current:E,states:y(j,E)}):void 0:i?i.historyValue:void 0,history:!r||t.source?i:void 0,actions:r?m:[],activities:r?d:i?i.activities:{},meta:r?x:i?i.meta:void 0,events:[],configuration:w,transitions:t.transitions,children:b,done:O,tags:null==i?void 0:i.tags});var j,E;const N=c!==f;_.changed=s.name===et||N;const{history:T}=_;if(T&&delete T.history,!r)return _;let $=_;if(!O){for((this._transient||o.some(t=>t._transient))&&($=this.resolveRaisedTransition($,{type:G},s));g.length;){const t=g.shift();$=this.resolveRaisedTransition($,t._event,s)}}const P=$.changed||(T?!!$.actions.length||N||typeof T.value!=typeof $.value||!function t(i,s){if(i===s)return!0;if(void 0===i||void 0===s)return!1;if(S(i)||S(s))return i===s;const n=e(i),o=e(s);return n.length===o.length&&n.every(e=>t(i[e],s[e]))}($.value,T.value):void 0);return $.changed=P,$.history=T,$.tags=new Set(u($.configuration.map(t=>t.tags))),$}getStateNode(t){if(Vt(t))return this.machine.getStateNodeById(t);if(!this.states)throw new Error(`Unable to retrieve child state '${t}' from '${this.id}'; no child states exist.`);const e=this.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${this.id}'`);return e}getStateNodeById(t){const e=Vt(t)?t.slice("#".length):t;if(e===this.id)return this;const i=this.machine.idMap[e];if(!i)throw new Error(`Child state node '#${e}' does not exist on machine '${this.id}'`);return i}getStateNodeByPath(t){if("string"==typeof t&&Vt(t))try{return this.getStateNodeById(t.slice(1))}catch(t){}const e=n(t,this.delimiter).slice();let i=this;for(;e.length;){const t=e.shift();if(!t.length)break;i=i.getStateNode(t)}return i}resolve(t){if(!t)return this.initialStateValue||Ct;switch(this.type){case"parallel":return a(this.initialStateValue,(e,i)=>e?this.getStateNode(i).resolve(t[i]||e):Ct);case"compound":if(S(t)){const e=this.getStateNode(t);return"parallel"===e.type||"compound"===e.type?{[t]:e.initialStateValue}:t}return e(t).length?a(t,(t,e)=>t?this.getStateNode(e).resolve(t):Ct):this.initialStateValue||{};default:return t||Ct}}getResolvedPath(t){if(Vt(t)){const e=this.machine.idMap[t.slice("#".length)];if(!e)throw new Error(`Unable to find state node '${t}'`);return e.path}return n(t,this.delimiter)}get initialStateValue(){if(this.__cache.initialStateValue)return this.__cache.initialStateValue;let t;if("parallel"===this.type)t=c(this.states,t=>t.initialStateValue||Ct,t=>!("history"===t.type));else if(void 0!==this.initial){if(!this.states[this.initial])throw new Error(`Initial state '${this.initial}' not found on '${this.key}'`);t=L(this.states[this.initial])?this.initial:{[this.initial]:this.states[this.initial].initialStateValue}}else t={};return this.__cache.initialStateValue=t,this.__cache.initialStateValue}getInitialState(t,e){const i=this.getStateNodes(t);return this.resolveTransition({configuration:i,entrySet:i,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,void 0,e)}get initialState(){this._init();const{initialStateValue:t}=this;if(!t)throw new Error(`Cannot retrieve initial state from simple state '${this.id}'.`);return this.getInitialState(t)}get target(){let t;if("history"===this.type){const e=this.config;t=S(e.target)&&Vt(e.target)?r(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t}getRelativeStateNodes(t,e,i=!0){return i?"history"===t.type?t.resolveHistory(e):t.initialStateNodes:[t]}get initialStateNodes(){if(L(this))return[this];if("compound"===this.type&&!this.initial)return[this];return u(d(this.initialStateValue).map(t=>this.getFromRelativePath(t)))}getFromRelativePath(t){if(!t.length)return[this];const[e,...i]=t;if(!this.states)throw new Error(`Cannot retrieve subPath '${e}' from node with no states`);const s=this.getStateNode(e);if("history"===s.type)return s.resolveHistory();if(!this.states[e])throw new Error(`Child state '${e}' does not exist on '${this.id}'`);return this.states[e].getFromRelativePath(i)}historyValue(t){if(e(this.states).length)return{current:t||this.initialStateValue,states:c(this.states,(e,i)=>{if(!t)return e.historyValue();const s=S(t)?void 0:t[i];return e.historyValue(s||e.initialStateValue)},t=>!t.history)}}resolveHistory(t){if("history"!==this.type)return[this];const e=this.parent;if(!t){const t=this.target;return t?u(d(t).map(t=>e.getFromRelativePath(t))):e.initialStateNodes}const i=(s=e.path,n="states",t=>{let e=t;for(const t of s)e=e[n][t];return e})(t).current;var s,n;return S(i)?[e.getStateNode(i)]:u(d(i).map(t=>"deep"===this.history?e.getFromRelativePath(t):[e.states[t[0]]]))}get stateIds(){const t=u(e(this.states).map(t=>this.states[t].stateIds));return[this.id].concat(t)}get events(){if(this.__cache.events)return this.__cache.events;const{states:t}=this,i=new Set(this.ownEvents);if(t)for(const s of e(t)){const e=t[s];if(e.states)for(const t of e.events)i.add(""+t)}return this.__cache.events=Array.from(i)}get ownEvents(){const t=new Set(this.transitions.filter(t=>!(!t.target&&!t.actions.length&&t.internal)).map(t=>t.eventType));return Array.from(t)}resolveTarget(t){if(void 0!==t)return t.map(t=>{if(!S(t))return t;const e=t[0]===this.delimiter;if(e&&!this.parent)return this.getStateNodeByPath(t.slice(1));const i=e?this.key+t:t;if(!this.parent)return this.getStateNodeByPath(i);try{return this.parent.getStateNodeByPath(i)}catch(t){throw new Error(`Invalid transition definition for state node '${this.id}':\n${t.message}`)}})}formatTransition(t){const e=function(t){if(void 0!==t&&""!==t)return f(t)}(t.target),i="internal"in t?t.internal:!e||e.some(t=>S(t)&&t[0]===this.delimiter),{guards:s}=this.machine.options,n=this.resolveTarget(e),o=Object.assign(Object.assign({},t),{actions:at(f(t.actions)),cond:w(t.cond,s),target:n,source:this,internal:i,eventType:t.event,toJSON:()=>Object.assign(Object.assign({},o),{target:o.target?o.target.map(t=>"#"+t.id):void 0,source:"#"+this.id})});return o}formatTransitions(){let t;if(this.config.on)if(Array.isArray(this.config.on))t=this.config.on;else{const i=this.config.on,s="*",n=i[s],o=void 0===n?[]:n,r=C(i,[s+""]);t=u(e(r).map(t=>T(t,r[t])).concat(T("*",o)))}else t=[];const i=this.config.always?T("",this.config.always):[],s=this.config.onDone?T(String(bt(this.id)),this.config.onDone):[],n=u(this.invoke.map(t=>{const e=[];return t.onDone&&e.push(...T(String(St(t.id)),t.onDone)),t.onError&&e.push(...T(String(wt(t.id)),t.onError)),e})),o=this.after,r=u([...s,...n,...t,...i].map(t=>f(t).map(t=>this.formatTransition(t))));for(const t of o)r.push(t);return r}}function Lt(t,e,i=t.context){const s="function"==typeof i?i():i;return new It(t,e,s)}function Dt(t,e){const i="function"==typeof t.context?t.context():t.context;return new It(t,e,i)}const At={deferEvents:!1};class Rt{constructor(t){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=Object.assign(Object.assign({},At),t)}initialize(t){if(this.initialized=!0,t){if(!this.options.deferEvents)return void this.schedule(t);this.process(t)}this.flushEvents()}schedule(t){if(this.initialized&&!this.processingEvent){if(0!==this.queue.length)throw new Error("Event queue should be empty when it is not processing events");this.process(t),this.flushEvents()}else this.queue.push(t)}clear(){this.queue=[]}flushEvents(){let t=this.queue.shift();for(;t;)this.process(t),t=this.queue.shift()}process(t){this.processingEvent=!0;try{t()}catch(t){throw this.clear(),t}finally{this.processingEvent=!1}}}const Mt=new Map;let zt=0;const Ft={bookId:()=>"x:"+zt++,register:(t,e)=>(Mt.set(t,e),t),get:t=>Mt.get(t),free(t){Mt.delete(t)}};function Jt(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0}function Ut(t){if(!Jt())return;const e=function(){const t=Jt();if(t&&"__xstate__"in t)return t.__xstate__}();e&&e.register(t)}const Bt={sync:!1,autoForward:!1};var qt;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(qt||(qt={}));class Xt{constructor(t,e=Xt.defaultOptions){this.machine=t,this.scheduler=new Rt,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=qt.NotStarted,this.children=new Map,this.forwardTo=new Set,this.init=this.start,this.send=(t,e)=>{if(m(t))return this.batch(t),this.state;const i=N(E(t,e));if(this.status===qt.Stopped)return this.state;if(this.status!==qt.Running&&!this.options.deferEvents)throw new Error(`Event "${i.name}" was sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ${JSON.stringify(i.data)}`);return this.scheduler.schedule(()=>{this.forward(i);const t=this.nextState(i);this.update(t,i)}),this._state},this.sendTo=(t,e)=>{const i=this.parent&&(e===I.Parent||this.parent.id===e),s=i?this.parent:S(e)?this.children.get(e)||Ft.get(e):(n=e)&&"function"==typeof n.send?e:void 0;var n;if(s)"machine"in s?s.send(Object.assign(Object.assign({},t),{name:t.name===tt?""+wt(this.id):t.name,origin:this.sessionId})):s.send(t.data);else if(!i)throw new Error(`Unable to send event to child '${e}' from service '${this.id}'.`)};const i=Object.assign(Object.assign({},Xt.defaultOptions),e),{clock:s,logger:n,parent:o,id:r}=i,a=void 0!==r?r:t.id;this.id=a,this.logger=n,this.clock=s,this.parent=o,this.options=i,this.scheduler=new Rt({deferEvents:this.options.deferEvents}),this.sessionId=Ft.bookId()}get initialState(){return this._initialState?this._initialState:Nt(this,()=>(this._initialState=this.machine.initialState,this._initialState))}get state(){return this._state}execute(t,e){for(const i of t.actions)this.exec(i,t,e)}update(t,e){if(t._sessionid=this.sessionId,this._state=t,this.options.execute&&this.execute(this.state),this.children.forEach(t=>{this.state.children[t.id]=t}),this.devTools&&this.devTools.send(e.data,t),t.event)for(const e of this.eventListeners)e(t.event);for(const e of this.listeners)e(t,t.event);for(const t of this.contextListeners)t(this.state.context,this.state.history?this.state.history.context:void 0);const i=J(t.configuration||[],this.machine);if(this.state.configuration&&i){const i=t.configuration.find(t=>"final"===t.type&&t.parent===this.machine),s=i&&i.doneData?p(i.doneData,t.context,e):void 0;for(const t of this.doneListeners)t(St(this.id,s));this.stop()}}onTransition(t){return this.listeners.add(t),this.status===qt.Running&&t(this.state,this.state.event),this}subscribe(t,e,i){if(!t)return{unsubscribe:()=>{}};let s,n=i;return"function"==typeof t?s=t:(s=t.next.bind(t),n=t.complete.bind(t)),this.listeners.add(s),this.status===qt.Running&&s(this.state),n&&this.onDone(n),{unsubscribe:()=>{s&&this.listeners.delete(s),n&&this.doneListeners.delete(n)}}}onEvent(t){return this.eventListeners.add(t),this}onSend(t){return this.sendListeners.add(t),this}onChange(t){return this.contextListeners.add(t),this}onStop(t){return this.stopListeners.add(t),this}onDone(t){return this.doneListeners.add(t),this}off(t){return this.listeners.delete(t),this.eventListeners.delete(t),this.sendListeners.delete(t),this.stopListeners.delete(t),this.doneListeners.delete(t),this.contextListeners.delete(t),this}start(t){if(this.status===qt.Running)return this;Ft.register(this.sessionId,this),this.initialized=!0,this.status=qt.Running;const e=void 0===t?this.initialState:Nt(this,()=>{return!S(e=t)&&"value"in e&&"history"in e?this.machine.resolveState(t):this.machine.resolveState(jt.from(t,this.machine.context));var e});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(()=>{this.update(e,nt)}),this}stop(){for(const t of this.listeners)this.listeners.delete(t);for(const t of this.stopListeners)t(),this.stopListeners.delete(t);for(const t of this.contextListeners)this.contextListeners.delete(t);for(const t of this.doneListeners)this.doneListeners.delete(t);if(!this.initialized)return this;this.state.configuration.forEach(t=>{for(const e of t.definition.exit)this.exec(e,this.state)}),this.children.forEach(t=>{b(t.stop)&&t.stop()});for(const t of e(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.scheduler.clear(),this.initialized=!1,this.status=qt.Stopped,Ft.free(this.sessionId),this}batch(t){if(this.status===qt.NotStarted&&this.options.deferEvents);else if(this.status!==qt.Running)throw new Error(`${t.length} event(s) were sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.`);this.scheduler.schedule(()=>{let e=this.state,i=!1;const s=[];for(const n of t){const t=N(n);this.forward(t),e=Nt(this,()=>this.machine.transition(e,t)),s.push(...e.actions.map(t=>_t(t,e))),i=i||!!e.changed}e.changed=i,e.actions=s,this.update(e,N(t[t.length-1]))})}sender(t){return this.send.bind(this,t)}nextState(t){const e=N(t);if(0===e.name.indexOf(Z)&&!this.state.nextEvents.some(t=>0===t.indexOf(Z)))throw e.data.data;return Nt(this,()=>this.machine.transition(this.state,e))}forward(t){for(const e of this.forwardTo){const i=this.children.get(e);if(!i)throw new Error(`Unable to forward event '${t}' from interpreter '${this.id}' to nonexistant child '${e}'.`);i.send(t)}}defer(t){this.delayedEventsMap[t.id]=this.clock.setTimeout(()=>{t.to?this.sendTo(t._event,t.to):this.send(t._event)},t.delay)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}exec(t,e,i=this.machine.options.actions){const{context:s,_event:n}=e,o=t.exec||ot(t.type,i),r=b(o)?o:o?o.exec:t.exec;if(r)try{return r(s,n.data,{action:t,state:this.state,_event:n})}catch(t){throw this.parent&&this.parent.send({type:"xstate.error",data:t}),t}switch(t.type){case X:const e=t;if("number"==typeof e.delay)return void this.defer(e);e.to?this.sendTo(e._event,e.to):this.send(e._event);break;case H:this.cancel(t.sendId);break;case U:{const e=t.activity;if(!this.state.activities[e.id||e.type])break;if(e.type===V.Invoke){const t=k(e.src),i=this.machine.options.services?this.machine.options.services[t.type]:void 0,{id:o,data:r}=e,a="autoForward"in e?e.autoForward:!!e.forward;if(!i)return;const c=r?p(r,s,n):void 0,h=b(i)?i(s,n.data,{data:c,src:t}):i;g(h)?this.spawnPromise(Promise.resolve(h),o):b(h)?this.spawnCallback(h,o):x(h)?this.spawnObservable(h,o):_(h)&&this.spawnMachine(c?h.withContext(c):h,{id:o,autoForward:a})}else this.spawnActivity(e);break}case B:this.stopChild(t.activity.id);break;case Q:const{label:i,value:o}=t;i?this.logger(i,o):this.logger(o)}}removeChild(t){this.children.delete(t),this.forwardTo.delete(t),delete this.state.children[t]}stopChild(t){const e=this.children.get(t);e&&(this.removeChild(t),b(e.stop)&&e.stop())}spawn(t,e,i){if(g(t))return this.spawnPromise(Promise.resolve(t),e);if(b(t))return this.spawnCallback(t,e);if(function(t){try{return"function"==typeof t.send}catch(t){return!1}}(s=t)&&"id"in s)return this.spawnActor(t);if(x(t))return this.spawnObservable(t,e);if(_(t))return this.spawnMachine(t,Object.assign(Object.assign({},i),{id:e}));throw new Error(`Unable to spawn entity "${e}" of type "${typeof t}".`);var s}spawnMachine(t,e={}){const i=new Xt(t,Object.assign(Object.assign({},this.options),{parent:this,id:e.id||t.id})),s=Object.assign(Object.assign({},Bt),e);s.sync&&i.onTransition(t=>{this.send(et,{state:t,id:i.id})});const n=i;return this.children.set(i.id,n),s.autoForward&&this.forwardTo.add(i.id),i.onDone(t=>{this.removeChild(i.id),this.send(N(t,{origin:i.id}))}).start(),n}spawnPromise(t,e){let i=!1,s=void 0;t.then(t=>{i||(s=t,this.removeChild(e),this.send(N(St(e,t),{origin:e})))},t=>{if(!i){this.removeChild(e);const i=wt(e,t);try{this.send(N(i,{origin:e}))}catch(t){this.devTools&&this.devTools.send(i,this.state),this.machine.strict&&this.stop()}}});const n={id:e,send:()=>{},subscribe:(e,i,s)=>{const n=function(t,e,i){if("object"==typeof t)return t;const s=()=>{};return{next:t,error:e||s,complete:i||s}}(e,i,s);let o=!1;return t.then(t=>{o||(n.next(t),o||n.complete())},t=>{o||n.error(t)}),{unsubscribe:()=>o=!0}},stop:()=>{i=!0},toJSON:()=>({id:e}),getSnapshot:()=>s};return this.children.set(e,n),n}spawnCallback(t,e){let i=!1;const s=new Set,n=new Set;let o=void 0;const r=t=>{o=t,n.forEach(e=>e(t)),i||this.send(N(t,{origin:e}))};let a;try{a=t(r,t=>{s.add(t)})}catch(t){this.send(wt(e,t))}if(g(a))return this.spawnPromise(a,e);const c={id:e,send:t=>s.forEach(e=>e(t)),subscribe:t=>(n.add(t),{unsubscribe:()=>{n.delete(t)}}),stop:()=>{i=!0,b(a)&&a()},toJSON:()=>({id:e}),getSnapshot:()=>o};return this.children.set(e,c),c}spawnObservable(t,e){let i=void 0;const s=t.subscribe(t=>{i=t,this.send(N(t,{origin:e}))},t=>{this.removeChild(e),this.send(N(wt(e,t),{origin:e}))},()=>{this.removeChild(e),this.send(N(St(e),{origin:e}))}),n={id:e,send:()=>{},subscribe:(e,i,s)=>t.subscribe(e,i,s),stop:()=>s.unsubscribe(),getSnapshot:()=>i,toJSON:()=>({id:e})};return this.children.set(e,n),n}spawnActor(t){return this.children.set(t.id,t),t}spawnActivity(t){const e=this.machine.options&&this.machine.options.activities?this.machine.options.activities[t.type]:void 0;if(!e)return;const i=e(this.state.context,t);this.spawnEffect(t.id,i)}spawnEffect(t,e){this.children.set(t,{id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),stop:e||void 0,getSnapshot:()=>{},toJSON:()=>({id:t})})}attachDev(){const t=Jt();if(this.options.devTools&&t){if(t.__REDUX_DEVTOOLS_EXTENSION__){const e="object"==typeof this.options.devTools?this.options.devTools:void 0;this.devTools=t.__REDUX_DEVTOOLS_EXTENSION__.connect(Object.assign(Object.assign({name:this.id,autoPause:!0,stateSanitizer:t=>({value:t.value,context:t.context,actions:t.actions})},e),{features:Object.assign({jump:!1,skip:!1},e?e.features:void 0)}),this.machine),this.devTools.init(this.state)}Ut(this)}}toJSON(){return{id:this.id}}[O](){return this}getSnapshot(){return this._state}}Xt.defaultOptions=(t=>({execute:!0,deferEvents:!0,clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:t.console.log.bind(console),devTools:!1}))("undefined"!=typeof self?self:global),Xt.interpret=Gt;function Ht(t,e){const i=(t=>S(t)?Object.assign(Object.assign({},Bt),{name:t}):Object.assign(Object.assign(Object.assign({},Bt),{name:j()}),t))(e);return(e=>e?e.spawn(t,i.name,i):$t(t,i.name))(Et[Et.length-1])}function Gt(t,e){return new Xt(t,e)}function Kt(t,e,i){const s=jt.from(t,t instanceof jt?t.context:void 0);for(const[t,i]of e)if(s.matches(t))return i(s);return i(s)}function Qt(t){return t}const Wt={raise:ht,send:dt,sendParent:ut,sendUpdate:lt,log:function(t=ft,e){return{type:Q,label:e,expr:t}},cancel:pt,start:gt,stop:vt,assign:yt,after:mt,done:bt,respond:function(t,e){return dt(t,Object.assign(Object.assign({},e),{to:(t,e,{_event:i})=>i.origin}))},forwardTo:xt,escalate:function(t,e){return ut((e,i,s)=>({type:tt,data:b(t)?t(e,i,s):t}),Object.assign(Object.assign({},e),{to:I.Parent}))},choose:function(t){return{type:V.Choose,conds:t}},pure:function(t){return{type:V.Pure,get:t}}};export{V as ActionTypes,Xt as Interpreter,qt as InterpreterStatus,Lt as Machine,I as SpecialTargets,jt as State,It as StateNode,Wt as actions,yt as assign,Dt as createMachine,Qt as createSchema,St as doneInvoke,xt as forwardTo,Gt as interpret,P as mapState,Kt as matchState,i as matchesState,dt as send,ut as sendParent,lt as sendUpdate,Ht as spawn};
package/es/Actor.d.ts CHANGED
@@ -11,15 +11,15 @@ export interface Actor<TContext = any, TEvent extends EventObject = AnyEventObje
11
11
  state?: any;
12
12
  deferred?: boolean;
13
13
  }
14
- export declare function createNullActor(id: string): Actor;
14
+ export declare function createNullActor(id: string): SpawnedActorRef<any>;
15
15
  /**
16
16
  * Creates a deferred actor that is able to be invoked given the provided
17
17
  * invocation information in its `.meta` value.
18
18
  *
19
19
  * @param invokeDefinition The meta information needed to invoke the actor.
20
20
  */
21
- export declare function createInvocableActor<TC, TE extends EventObject>(invokeDefinition: InvokeDefinition<TC, TE>, machine: StateMachine<TC, any, TE, any>, context: TC, _event: SCXML.Event<TE>): Actor;
22
- export declare function createDeferredActor(entity: Spawnable, id: string, data?: any): Actor;
21
+ export declare function createInvocableActor<TC, TE extends EventObject>(invokeDefinition: InvokeDefinition<TC, TE>, machine: StateMachine<TC, any, TE, any>, context: TC, _event: SCXML.Event<TE>): SpawnedActorRef<any>;
22
+ export declare function createDeferredActor(entity: Spawnable, id: string, data?: any): SpawnedActorRef<any, undefined>;
23
23
  export declare function isActor(item: any): item is ActorRef<any>;
24
24
  export declare function isSpawnedActor(item: any): item is SpawnedActorRef<any>;
25
25
  //# sourceMappingURL=Actor.d.ts.map
package/es/Actor.js CHANGED
@@ -14,6 +14,9 @@ function createNullActor(id) {
14
14
  }
15
15
  };
16
16
  },
17
+ getSnapshot: function () {
18
+ return undefined;
19
+ },
17
20
  toJSON: function () {
18
21
  return {
19
22
  id: id
@@ -35,17 +38,20 @@ function createInvocableActor(invokeDefinition, machine, context, _event) {
35
38
  var invokeSrc = toInvokeSource(invokeDefinition.src);
36
39
  var serviceCreator = (_a = machine === null || machine === void 0 ? void 0 : machine.options.services) === null || _a === void 0 ? void 0 : _a[invokeSrc.type];
37
40
  var resolvedData = invokeDefinition.data ? mapContext(invokeDefinition.data, context, _event) : undefined;
38
- var tempActor = serviceCreator ? createDeferredActor(serviceCreator, invokeDefinition.id, resolvedData) : createNullActor(invokeDefinition.id);
41
+ var tempActor = serviceCreator ? createDeferredActor(serviceCreator, invokeDefinition.id, resolvedData) : createNullActor(invokeDefinition.id); // @ts-ignore
42
+
39
43
  tempActor.meta = invokeDefinition;
40
44
  return tempActor;
41
45
  }
42
46
 
43
47
  function createDeferredActor(entity, id, data) {
44
- var tempActor = createNullActor(id);
48
+ var tempActor = createNullActor(id); // @ts-ignore
49
+
45
50
  tempActor.deferred = true;
46
51
 
47
52
  if (isMachine(entity)) {
48
53
  // "mute" the existing service scope so potential spawned actors within the `.initialState` stay deferred here
54
+ // @ts-ignore
49
55
  tempActor.state = provide(undefined, function () {
50
56
  return (data ? entity.withContext(data) : entity).initialState;
51
57
  });
package/es/State.d.ts CHANGED
@@ -50,6 +50,7 @@ export declare class State<TContext, TEvent extends EventObject = EventObject, T
50
50
  * An object mapping actor IDs to spawned actors/invoked services.
51
51
  */
52
52
  children: Record<string, ActorRef<any>>;
53
+ tags: Set<string>;
53
54
  /**
54
55
  * Creates a new State instance for the given `stateValue` and `context`.
55
56
  * @param stateValue
@@ -86,7 +87,9 @@ export declare class State<TContext, TEvent extends EventObject = EventObject, T
86
87
  * @param delimiter The character(s) that separate each subpath in the string state node path.
87
88
  */
88
89
  toStrings(stateValue?: StateValue, delimiter?: string): string[];
89
- toJSON(): Pick<this, Exclude<keyof this, "configuration" | "transitions">>;
90
+ toJSON(): Omit<this, "configuration" | "transitions" | "tags"> & {
91
+ tags: string[];
92
+ };
90
93
  /**
91
94
  * Whether the current state value is a subset of the given parent state value.
92
95
  * @param parentStateValue
@@ -97,5 +100,10 @@ export declare class State<TContext, TEvent extends EventObject = EventObject, T
97
100
  } extends TTypestate ? TTypestate : never : never)['context'], TEvent, TStateSchema, TTypestate> & {
98
101
  value: TSV;
99
102
  };
103
+ /**
104
+ * Whether the current state configuration has a state node with the specified `tag`.
105
+ * @param tag
106
+ */
107
+ hasTag(tag: string): boolean;
100
108
  }
101
109
  //# sourceMappingURL=State.d.ts.map
package/es/State.js CHANGED
@@ -1,4 +1,4 @@
1
- import { __spread, __rest, __assign } from './_virtual/_tslib.js';
1
+ import { __spreadArray, __read, __rest, __assign } from './_virtual/_tslib.js';
2
2
  import { EMPTY_ACTIVITY_MAP } from './constants.js';
3
3
  import { isString, matchesState, keys } from './utils.js';
4
4
  import { nextEvents } from './stateUtils.js';
@@ -68,6 +68,8 @@ function () {
68
68
  function State(config) {
69
69
  var _this = this;
70
70
 
71
+ var _a;
72
+
71
73
  this.actions = [];
72
74
  this.activities = EMPTY_ACTIVITY_MAP;
73
75
  this.meta = {};
@@ -89,6 +91,7 @@ function () {
89
91
  this.transitions = config.transitions;
90
92
  this.children = config.children;
91
93
  this.done = !!config.done;
94
+ this.tags = (_a = config.tags) !== null && _a !== void 0 ? _a : new Set();
92
95
  Object.defineProperty(this, 'nextEvents', {
93
96
  get: function () {
94
97
  return nextEvents(_this.configuration);
@@ -204,20 +207,23 @@ function () {
204
207
  }
205
208
 
206
209
  var valueKeys = keys(stateValue);
207
- return valueKeys.concat.apply(valueKeys, __spread(valueKeys.map(function (key) {
210
+ return valueKeys.concat.apply(valueKeys, __spreadArray([], __read(valueKeys.map(function (key) {
208
211
  return _this.toStrings(stateValue[key], delimiter).map(function (s) {
209
212
  return key + delimiter + s;
210
213
  });
211
- })));
214
+ }))));
212
215
  };
213
216
 
214
217
  State.prototype.toJSON = function () {
215
218
  var _a = this,
216
219
  configuration = _a.configuration,
217
220
  transitions = _a.transitions,
218
- jsonValues = __rest(_a, ["configuration", "transitions"]);
221
+ tags = _a.tags,
222
+ jsonValues = __rest(_a, ["configuration", "transitions", "tags"]);
219
223
 
220
- return jsonValues;
224
+ return __assign(__assign({}, jsonValues), {
225
+ tags: Array.from(tags)
226
+ });
221
227
  };
222
228
  /**
223
229
  * Whether the current state value is a subset of the given parent state value.
@@ -228,6 +234,15 @@ function () {
228
234
  State.prototype.matches = function (parentStateValue) {
229
235
  return matchesState(parentStateValue, this.value);
230
236
  };
237
+ /**
238
+ * Whether the current state configuration has a state node with the specified `tag`.
239
+ * @param tag
240
+ */
241
+
242
+
243
+ State.prototype.hasTag = function (tag) {
244
+ return this.tags.has(tag);
245
+ };
231
246
 
232
247
  return State;
233
248
  }();
package/es/StateNode.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Event, StateValue, StateValueMap, MachineOptions, EventObject, HistoryValue, StateNodeDefinition, TransitionDefinition, DelayedTransitionDefinition, ActivityDefinition, StateNodeConfig, StateSchema, StateNodesConfig, InvokeDefinition, ActionObject, Mapper, PropertyMapper, SCXML, Typestate, TransitionDefinitionMap, MachineSchema } from './types';
1
+ import { Event, StateValue, MachineOptions, EventObject, HistoryValue, StateNodeDefinition, TransitionDefinition, DelayedTransitionDefinition, ActivityDefinition, StateNodeConfig, StateSchema, StateNodesConfig, InvokeDefinition, ActionObject, Mapper, PropertyMapper, SCXML, Typestate, TransitionDefinitionMap, MachineSchema } from './types';
2
2
  import { State } from './State';
3
3
  declare class StateNode<TContext = any, TStateSchema extends StateSchema = any, TEvent extends EventObject = EventObject, TTypestate extends Typestate<TContext> = {
4
4
  value: any;
@@ -113,6 +113,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
113
113
  __xstatenode: true;
114
114
  private __cache;
115
115
  private idMap;
116
+ tags: string[];
116
117
  constructor(
117
118
  /**
118
119
  * The raw config used to create the machine.
@@ -135,7 +136,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
135
136
  *
136
137
  * @param context Custom context (will override predefined context, not recursive)
137
138
  */
138
- withContext(context: TContext): StateNode<TContext, TStateSchema, TEvent>;
139
+ withContext(context: TContext): StateNode<TContext, TStateSchema, TEvent, TTypestate>;
139
140
  /**
140
141
  * The well-structured state node definition.
141
142
  */
@@ -160,7 +161,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
160
161
  *
161
162
  * @param state The state value or State instance
162
163
  */
163
- getStateNodes(state: StateValue | State<TContext, TEvent, any, TTypestate>): Array<StateNode<TContext, any, TEvent, any>>;
164
+ getStateNodes(state: StateValue | State<TContext, TEvent, any, TTypestate>): Array<StateNode<TContext, any, TEvent, TTypestate>>;
164
165
  /**
165
166
  * Returns `true` if this state node explicitly handles the given event.
166
167
  *
@@ -194,13 +195,13 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
194
195
  * @param event The event that was sent at the current state
195
196
  * @param context The current context (extended state) of the current state
196
197
  */
197
- transition(state: string | StateValueMap | State<TContext, TEvent, any, TTypestate> | undefined, event: Event<TEvent> | SCXML.Event<TEvent>, context?: TContext): State<TContext, TEvent, TStateSchema, TTypestate>;
198
+ transition(state: StateValue | State<TContext, TEvent, any, TTypestate> | undefined, event: Event<TEvent> | SCXML.Event<TEvent>, context?: TContext): State<TContext, TEvent, TStateSchema, TTypestate>;
198
199
  private resolveRaisedTransition;
199
200
  private resolveTransition;
200
201
  /**
201
202
  * Returns the child state node from its relative `stateKey`, or throws.
202
203
  */
203
- getStateNode(stateKey: string): StateNode<TContext, any, TEvent>;
204
+ getStateNode(stateKey: string): StateNode<TContext, any, TEvent, TTypestate>;
204
205
  /**
205
206
  * Returns the state node with the given `stateId`, or throws.
206
207
  *
package/es/StateNode.js CHANGED
@@ -1,4 +1,4 @@
1
- import { __assign, __values, __spread, __read, __rest } from './_virtual/_tslib.js';
1
+ import { __assign, __values, __spreadArray, __read, __rest } from './_virtual/_tslib.js';
2
2
  import { STATE_DELIMITER } from './constants.js';
3
3
  import { IS_PRODUCTION } from './environment.js';
4
4
  import { mapValues, isArray, flatten, keys, toArray, toStateValue, isString, getEventType, matchesState, path, evaluateGuard, mapContext, toSCXMLEvent, pathToStateValue, isBuiltInEvent, partition, updateHistoryValue, toStatePath, mapFilterValues, warn, toStatePaths, nestedPath, normalizeTarget, toGuard, toTransitionConfigArray, isMachine, isFunction } from './utils.js';
@@ -78,13 +78,14 @@ function () {
78
78
  delayedTransitions: undefined
79
79
  };
80
80
  this.idMap = {};
81
+ this.tags = [];
81
82
  this.options = Object.assign(createDefaultOptions(), options);
82
83
  this.parent = this.options._parent;
83
84
  this.key = this.config.key || this.options._key || this.config.id || '(machine)';
84
85
  this.machine = this.parent ? this.parent.machine : this;
85
86
  this.path = this.parent ? this.parent.path.concat(this.key) : [];
86
87
  this.delimiter = this.config.delimiter || (this.parent ? this.parent.delimiter : STATE_DELIMITER);
87
- this.id = this.config.id || __spread([this.machine.key], this.path).join(this.delimiter);
88
+ this.id = this.config.id || __spreadArray([this.machine.key], __read(this.path)).join(this.delimiter);
88
89
  this.version = this.parent ? this.parent.version : this.config.version;
89
90
  this.type = this.config.type || (this.config.parallel ? 'parallel' : this.config.states && keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');
90
91
  this.schema = this.parent ? this.machine.schema : (_a = this.config.schema) !== null && _a !== void 0 ? _a : {};
@@ -183,7 +184,8 @@ function () {
183
184
  this.activities = toArray(this.config.activities).concat(this.invoke).map(function (activity) {
184
185
  return toActivityDefinition(activity);
185
186
  });
186
- this.transition = this.transition.bind(this); // TODO: this is the real fix for initialization once
187
+ this.transition = this.transition.bind(this);
188
+ this.tags = toArray(this.config.tags); // TODO: this is the real fix for initialization once
187
189
  // state node getters are deprecated
188
190
  // if (!this.parent) {
189
191
  // this._init();
@@ -396,13 +398,14 @@ function () {
396
398
 
397
399
  if (isString(stateValue)) {
398
400
  var initialStateValue = this.getStateNode(stateValue).initial;
399
- return initialStateValue !== undefined ? this.getStateNodes((_a = {}, _a[stateValue] = initialStateValue, _a)) : [this.states[stateValue]];
401
+ return initialStateValue !== undefined ? this.getStateNodes((_a = {}, _a[stateValue] = initialStateValue, _a)) : [this, this.states[stateValue]];
400
402
  }
401
403
 
402
404
  var subStateKeys = keys(stateValue);
403
405
  var subStateNodes = subStateKeys.map(function (subStateKey) {
404
406
  return _this.getStateNode(subStateKey);
405
407
  });
408
+ subStateNodes.push(this);
406
409
  return subStateNodes.concat(subStateKeys.reduce(function (allSubStateNodes, subStateKey) {
407
410
  var subStateNode = _this.getStateNode(subStateKey).getStateNodes(stateValue[subStateKey]);
408
411
 
@@ -577,7 +580,7 @@ function () {
577
580
  nextStateNodes = candidate.target;
578
581
  }
579
582
 
580
- actions.push.apply(actions, __spread(candidate.actions));
583
+ actions.push.apply(actions, __spreadArray([], __read(candidate.actions)));
581
584
  selectedTransition = candidate;
582
585
  break;
583
586
  }
@@ -756,13 +759,13 @@ function () {
756
759
  var exitStates = new Set(transition.exitSet);
757
760
 
758
761
  var _c = __read([flatten(Array.from(entryStates).map(function (stateNode) {
759
- return __spread(stateNode.activities.map(function (activity) {
762
+ return __spreadArray(__spreadArray([], __read(stateNode.activities.map(function (activity) {
760
763
  return start(activity);
761
- }), stateNode.onEntry);
764
+ }))), __read(stateNode.onEntry));
762
765
  })).concat(doneEvents.map(raise)), flatten(Array.from(exitStates).map(function (stateNode) {
763
- return __spread(stateNode.onExit, stateNode.activities.map(function (activity) {
766
+ return __spreadArray(__spreadArray([], __read(stateNode.onExit)), __read(stateNode.activities.map(function (activity) {
764
767
  return stop(activity);
765
- }));
768
+ })));
766
769
  }))], 2),
767
770
  entryActions = _c[0],
768
771
  exitActions = _c[1];
@@ -816,7 +819,7 @@ function () {
816
819
  };
817
820
  var prevConfig = getConfiguration([], this.getStateNodes(currentState.value));
818
821
  var resolvedConfig = stateTransition.configuration.length ? getConfiguration(prevConfig, stateTransition.configuration) : prevConfig;
819
- stateTransition.configuration = __spread(resolvedConfig);
822
+ stateTransition.configuration = __spreadArray([], __read(resolvedConfig));
820
823
  return this.resolveTransition(stateTransition, currentState, _event);
821
824
  };
822
825
 
@@ -830,7 +833,7 @@ function () {
830
833
  state._event = originalEvent;
831
834
  state.event = originalEvent.data;
832
835
 
833
- (_a = state.actions).unshift.apply(_a, __spread(currentActions));
836
+ (_a = state.actions).unshift.apply(_a, __spreadArray([], __read(currentActions)));
834
837
 
835
838
  return state;
836
839
  };
@@ -924,7 +927,8 @@ function () {
924
927
  configuration: resolvedConfiguration,
925
928
  transitions: stateTransition.transitions,
926
929
  children: children,
927
- done: isDone
930
+ done: isDone,
931
+ tags: currentState === null || currentState === void 0 ? void 0 : currentState.tags
928
932
  });
929
933
  var didUpdateContext = currentContext !== updatedContext;
930
934
  nextState.changed = _event.name === update || didUpdateContext; // Dispose of penultimate histories to prevent memory leaks
@@ -963,6 +967,9 @@ function () {
963
967
  maybeNextState.changed = changed; // Preserve original history after raised events
964
968
 
965
969
  maybeNextState.history = history;
970
+ maybeNextState.tags = new Set(flatten(maybeNextState.configuration.map(function (sn) {
971
+ return sn.tags;
972
+ })));
966
973
  return maybeNextState;
967
974
  };
968
975
  /**
@@ -1517,17 +1524,17 @@ function () {
1517
1524
  var settleTransitions = [];
1518
1525
 
1519
1526
  if (invokeDef.onDone) {
1520
- settleTransitions.push.apply(settleTransitions, __spread(toTransitionConfigArray(String(doneInvoke(invokeDef.id)), invokeDef.onDone)));
1527
+ settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(doneInvoke(invokeDef.id)), invokeDef.onDone))));
1521
1528
  }
1522
1529
 
1523
1530
  if (invokeDef.onError) {
1524
- settleTransitions.push.apply(settleTransitions, __spread(toTransitionConfigArray(String(error(invokeDef.id)), invokeDef.onError)));
1531
+ settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(error(invokeDef.id)), invokeDef.onError))));
1525
1532
  }
1526
1533
 
1527
1534
  return settleTransitions;
1528
1535
  }));
1529
1536
  var delayedTransitions = this.after;
1530
- var formattedTransitions = flatten(__spread(doneConfig, invokeConfig, onConfig, eventlessConfig).map(function (transitionConfig) {
1537
+ var formattedTransitions = flatten(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(doneConfig)), __read(invokeConfig)), __read(onConfig)), __read(eventlessConfig)).map(function (transitionConfig) {
1531
1538
  return toArray(transitionConfig).map(function (transition) {
1532
1539
  return _this.formatTransition(transition);
1533
1540
  });
@@ -79,10 +79,10 @@ function __read(o, n) {
79
79
  return ar;
80
80
  }
81
81
 
82
- function __spread() {
83
- for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
82
+ function __spreadArray(to, from) {
83
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i];
84
84
 
85
- return ar;
85
+ return to;
86
86
  }
87
87
 
88
- export { __assign, __read, __rest, __spread, __values };
88
+ export { __assign, __read, __rest, __spreadArray, __values };
package/es/actions.d.ts CHANGED
@@ -9,7 +9,7 @@ export declare const initEvent: SCXML.Event<{
9
9
  }>;
10
10
  export declare function getActionFunction<TContext, TEvent extends EventObject>(actionType: ActionType, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | undefined;
11
11
  export declare function toActionObject<TContext, TEvent extends EventObject>(action: Action<TContext, TEvent>, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): ActionObject<TContext, TEvent>;
12
- export declare const toActionObjects: <TContext, TEvent extends EventObject>(action?: string | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | Action<TContext, TEvent>[] | undefined, actionFunctionMap?: Record<string, ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent>> | undefined) => ActionObject<TContext, TEvent>[];
12
+ export declare const toActionObjects: <TContext, TEvent extends EventObject>(action?: SingleOrArray<Action<TContext, TEvent>> | undefined, actionFunctionMap?: ActionFunctionMap<TContext, TEvent> | undefined) => ActionObject<TContext, TEvent>[];
13
13
  export declare function toActivityDefinition<TContext, TEvent extends EventObject>(action: string | ActivityDefinition<TContext, TEvent>): ActivityDefinition<TContext, TEvent>;
14
14
  /**
15
15
  * Raises an event. This places the event in the internal event queue, so that
@@ -1,6 +1,5 @@
1
1
  import { StateMachine, Event, EventObject, DefaultContext, StateSchema, StateValue, InterpreterOptions, SingleOrArray, DoneEvent, MachineOptions, SCXML, EventData, Observer, Spawnable, Typestate } from './types';
2
2
  import { State } from './State';
3
- import { Actor } from './Actor';
4
3
  import { ActorRefFrom, SpawnedActorRef, Subscription } from '.';
5
4
  export declare type StateListener<TContext, TEvent extends EventObject, TStateSchema extends StateSchema<TContext> = any, TTypestate extends Typestate<TContext> = {
6
5
  value: any;
@@ -26,7 +25,7 @@ export declare enum InterpreterStatus {
26
25
  export declare class Interpreter<TContext, TStateSchema extends StateSchema = any, TEvent extends EventObject = EventObject, TTypestate extends Typestate<TContext> = {
27
26
  value: any;
28
27
  context: TContext;
29
- }> implements Actor<State<TContext, TEvent, TStateSchema, TTypestate>, TEvent> {
28
+ }> implements SpawnedActorRef<TEvent, State<TContext, TEvent, TStateSchema, TTypestate>> {
30
29
  machine: StateMachine<TContext, TStateSchema, TEvent, TTypestate>;
31
30
  /**
32
31
  * The default interpreter options:
@@ -122,7 +121,7 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
122
121
  /**
123
122
  * Alias for Interpreter.prototype.start
124
123
  */
125
- init: (initialState?: string | import("./types").StateValueMap | State<TContext, TEvent, TStateSchema, TTypestate> | undefined) => Interpreter<TContext, TStateSchema, TEvent, TTypestate>;
124
+ init: (initialState?: StateValue | State<TContext, TEvent, TStateSchema, TTypestate> | undefined) => Interpreter<TContext, TStateSchema, TEvent, TTypestate>;
126
125
  /**
127
126
  * Starts the interpreter from the given state, or the initial state.
128
127
  * @param initialState The state to start the statechart from
@@ -182,6 +181,7 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
182
181
  toJSON(): {
183
182
  id: string;
184
183
  };
184
+ getSnapshot(): State<TContext, TEvent, TStateSchema, TTypestate>;
185
185
  }
186
186
  export declare function spawn<TC, TE extends EventObject>(entity: StateMachine<TC, any, TE>, nameOrOptions?: string | SpawnOptions): ActorRefFrom<StateMachine<TC, any, TE>>;
187
187
  export declare function spawn(entity: Spawnable, nameOrOptions?: string | SpawnOptions): SpawnedActorRef<any>;