xstate 4.10.0 → 4.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/LICENSE +22 -0
  3. package/README.md +2 -2
  4. package/dist/xstate.interpreter.js +1 -1
  5. package/dist/xstate.js +1 -1
  6. package/dist/xstate.web.js +2 -2
  7. package/es/Actor.d.ts +5 -3
  8. package/es/Actor.js +26 -4
  9. package/es/State.d.ts +5 -2
  10. package/es/StateNode.d.ts +8 -8
  11. package/es/StateNode.js +61 -41
  12. package/es/actions.d.ts +9 -5
  13. package/es/actions.js +28 -13
  14. package/es/index.d.ts +2 -2
  15. package/es/index.js +1 -1
  16. package/es/interpreter.d.ts +29 -15
  17. package/es/interpreter.js +99 -112
  18. package/es/invokeUtils.d.ts +7 -0
  19. package/es/invokeUtils.js +39 -0
  20. package/es/match.d.ts +4 -1
  21. package/es/serviceScope.d.ts +10 -0
  22. package/es/serviceScope.js +18 -0
  23. package/es/stateUtils.d.ts +1 -1
  24. package/es/types.d.ts +79 -32
  25. package/es/utils.d.ts +4 -3
  26. package/es/utils.js +12 -3
  27. package/lib/Actor.d.ts +5 -3
  28. package/lib/Actor.js +24 -3
  29. package/lib/Machine.js +1 -0
  30. package/lib/SimulatedClock.js +1 -0
  31. package/lib/State.d.ts +5 -2
  32. package/lib/State.js +1 -0
  33. package/lib/StateNode.d.ts +8 -8
  34. package/lib/StateNode.js +69 -42
  35. package/lib/actionTypes.js +1 -0
  36. package/lib/actions.d.ts +9 -5
  37. package/lib/actions.js +27 -19
  38. package/lib/constants.js +1 -0
  39. package/lib/devTools.js +1 -0
  40. package/lib/each.js +1 -0
  41. package/lib/environment.js +1 -0
  42. package/lib/index.d.ts +2 -2
  43. package/lib/index.js +29 -20
  44. package/lib/interpreter.d.ts +28 -14
  45. package/lib/interpreter.js +82 -88
  46. package/lib/invokeUtils.d.ts +7 -0
  47. package/lib/invokeUtils.js +42 -0
  48. package/lib/json.js +1 -0
  49. package/lib/mapState.js +1 -0
  50. package/lib/match.d.ts +4 -1
  51. package/lib/match.js +1 -0
  52. package/lib/patterns.js +1 -0
  53. package/lib/registry.js +1 -0
  54. package/lib/scheduler.js +1 -0
  55. package/lib/scxml.js +1 -0
  56. package/lib/serviceScope.d.ts +10 -0
  57. package/lib/serviceScope.js +15 -0
  58. package/lib/stateUtils.d.ts +1 -1
  59. package/lib/stateUtils.js +1 -0
  60. package/lib/types.d.ts +79 -32
  61. package/lib/types.js +1 -0
  62. package/lib/utils.d.ts +4 -3
  63. package/lib/utils.js +9 -2
  64. package/package.json +6 -6
@@ -1,4 +1,4 @@
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,i,s){if(b(t))return t(i,s.data);const n={};for(const o of e(t)){const e=t[o];b(e)?n[o]=e(i,s.data):n[o]=e}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,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 _="function"==typeof Symbol&&Symbol.observable||"@@observable";function O(t){try{return"__xstatenode"in t}catch(t){return!1}}const E=(()=>{let t=0;return()=>(t++,t.toString(16))})();function j(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=j(t);return Object.assign({name:i.type,data:i,$$type:"scxml",type:"external"},e)}function $(t,e){return l(e).map(e=>void 0===e||"string"==typeof e||O(e)?{target:e,event:t}:Object.assign(Object.assign({},e),{event:t}))}function T(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,s){let n;for(const o of e(t))i(o,s)&&(!n||s.length>n.length)&&(n=o);return t[n]}
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,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(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. All rights reserved.
4
4
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -12,4 +12,4 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
12
12
 
13
13
  See the Apache Version 2.0 License for specific language governing permissions
14
14
  and limitations under the License.
15
- ***************************************************************************** */function P(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,C;!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"}(C||(C={}));const I=t=>"atomic"===t.type||"final"===t.type;function L(t){return e(t.states).map(e=>t.states[e])}function A(t){const e=[t];return I(t)?e:e.concat(u(L(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 L(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 D(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(I(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 z(t,e){return"compound"===e.type?L(e).some(e=>"final"===e.type&&F(t,e)):"parallel"===e.type&&L(e).every(e=>z(t,e))}const J=V.Start,U=V.Stop,B=V.Raise,q=V.Send,X=V.Cancel,H=V.NullEvent,G=V.Assign,K=(V.After,V.DoneState,V.Log),Q=V.Init,W=V.Invoke,Y=(V.ErrorExecution,V.ErrorPlatform),Z=V.ErrorCustom,tt=V.Update,et=V.Choose,it=V.Pure,st=N({type:Q});function nt(t,e){return e&&e[t]||void 0}function ot(t,e){let i;if(S(t)||"number"==typeof t){const s=nt(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=nt(t.type,e);if(b(s))i=Object.assign(Object.assign({},t),{exec:s});else if(s){const{type:e}=t,n=P(t,["type"]);i=Object.assign(Object.assign({type:e},s),n)}else i=t}return Object.defineProperty(i,"toString",{value:()=>i.type,enumerable:!1,configurable:!0}),i}const rt=(t,e)=>{if(!t)return[];return(m(t)?t:[t]).map(t=>ot(t,e))};function at(t){const e=ot(t);return Object.assign(Object.assign({id:S(t)?t:e.id},e),{type:e.type})}function ct(t){return S(t)?{type:B,event:t}:ht(t,{to:C.Internal})}function ht(t,e){return{to:e?e.to:void 0,type:q,event:b(t)?t:j(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:b(t)?t.name:s(t)}}function dt(t,e){return ht(t,Object.assign(Object.assign({},e),{to:C.Parent}))}function ut(){return dt(tt)}const lt=(t,e)=>({context:t,event:e});const ft=t=>({type:X,sendId:t});function pt(t){const e=at(t);return{type:V.Start,activity:e,exec:void 0}}function gt(t){const e=at(t);return{type:V.Stop,activity:e,exec:void 0}}const vt=t=>({type:G,assignment:t});function yt(t,e){const i=e?`#${e}`:"";return`${V.After}(${t})${i}`}function mt(t,e){const i=`${V.DoneState}.${t}`,s={type:i,data:e,toString:()=>i};return s}function bt(t,e){const i=`${V.DoneInvoke}.${t}`,s={type:i,data:e,toString:()=>i};return s}function St(t,e){const i=`${V.ErrorPlatform}.${t}`,s={type:i,data:e,toString:()=>i};return s}function wt(t,e){return ht((t,e)=>e,Object.assign(Object.assign({},e),{to:t}))}function xt(t,i,s,n,o){const[r,a]=v(o,t=>t.type===G);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 B:return{type:B,_event:N(e.event)};case q: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 K: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 et:{const o=null===(s=e.conds.find(e=>{const s=w(e.cond,t.options.guards);return!s||T(t,s,c,n,i)}))||void 0===s?void 0:s.actions;if(!o)return[];const r=xt(t,i,c,n,rt(f(o),t.options.actions));return c=r[1],r[0]}case it:{const s=e.get(c,n.data);if(!s)return[];const o=xt(t,i,c,n,rt(f(s),t.options.actions));return c=o[1],o[0]}default:return ot(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 Ot{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 Ot)return t.context!==e?new Ot({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 Ot({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 Ot(t)}static inert(t,e){if(t instanceof Ot){if(!t.actions.length)return t;const i=st;return new Ot({value:t.value,context:e,_event:i,_sessionid:null,historyValue:t.historyValue,history:t.history,activities:t.activities,configuration:t.configuration,transitions:[],children:{}})}return Ot.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(){return P(this,["configuration","transitions"])}matches(t){return i(t,this.value)}}function Et(t){try{return"function"==typeof t.send}catch(t){return!1}}const jt={},Nt=t=>"#"===t[0];class $t{constructor(t,i,s){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.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.initial=this.config.initial,this.states=this.config.states?a(this.config.states,(t,e)=>{const i=new $t(t,{_parent:this,_key:e});return Object.assign(this.idMap,Object.assign({[i.id]:i},i.idMap)),i}):jt;let n=0;!function t(e){e.order=n++;for(const i of L(e))t(i)}(this),this.history=!0===this.config.history?"shallow":this.config.history||!1,this._transient=!!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=>ot(t)),this.onExit=f(this.config.exit||this.config.onExit).map(t=>ot(t)),this.meta=this.config.meta,this.data="final"===this.type?this.config.data:void 0,this.invoke=f(this.config.invoke).map((t,e)=>{if(O(t))return this.machine.options.services=Object.assign({[t.id]:t},this.machine.options.services),{type:W,src:t.id,id:t.id};if("string"!=typeof t.src){const i=`${this.id}:invocation[${e}]`;return this.machine.options.services=Object.assign({[i]:t.src},this.machine.options.services),Object.assign(Object.assign({type:W,id:i},t),{src:i})}return Object.assign(Object.assign({},t),{type:W,id:t.id||t.src,src:t.src})}),this.activities=f(this.config.activities).concat(this.invoke).map(t=>at(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:s,guards:n,services:o,delays:r}=this.options;return new $t(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 $t(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.data,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=yt(b(t)?`${this.id}:delay[${e}]`:t,this.id);return this.onEntry.push(ht(i,{delay:t})),this.onExit.push(ft(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 Ot?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 s=e(i);return s.map(t=>this.getStateNode(t)).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 Ot(Object.assign(Object.assign({},t),{value:this.resolve(t.value),configuration:e}))}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)&&Nt(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||T(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(mt(s.id,s.data),mt(o.id,s.data?p(s.data,e,i):void 0));const r=o.parent;return"parallel"===r.type&&L(r).every(e=>z(t.configuration,e))&&n.push(mt(r.id,r.data)),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=>pt(t)),...t.onEntry])).concat(r.map(ct)),u(Array.from(c).map(t=>[...t.onExit,...t.activities.map(t=>gt(t))]))];return rt(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 Ot)n=void 0===i?t:this.resolveState(Ot.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(Ot.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=st,n=this.machine.context){const{configuration:o}=t,r=!i||t.transitions.length>0?D(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===J?d[t.activity.id||t.activity.type]=t:t.type===U&&(d[t.activity.id||t.activity.type]=!1);const[u,l]=xt(this,i,c,s,h),[f,p]=v(u,t=>t.type===B||t.type===q&&t.to===C.Internal),g=u.filter(t=>t.type===J&&t.activity.type===W).reduce((t,e)=>(t[e.activity.id]=function(t){const e={id:i=t.id,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:i})};var i;return e.meta=t,e}(e.activity),t),i?Object.assign({},i.children):{}),m=r?t.configuration:i?i.configuration:[],b=m.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{}),w=z(m,this),x=new Ot({value:r||i.value,context:l,_event:s,_sessionid:i?i._sessionid:null,historyValue:r?a?(_=a,O=r,{current:O,states:y(_,O)}):void 0:i?i.historyValue:void 0,history:!r||t.source?i:void 0,actions:r?p:[],activities:r?d:i?i.activities:{},meta:r?b:i?i.meta:void 0,events:[],configuration:m,transitions:t.transitions,children:g,done:w});var _,O;const E=c!==l;x.changed=s.name===tt||E;const{history:j}=x;if(j&&delete j.history,!r)return x;let N=x;if(!w){for((this._transient||o.some(t=>t._transient))&&(N=this.resolveRaisedTransition(N,{type:H},s));f.length;){const t=f.shift();N=this.resolveRaisedTransition(N,t._event,s)}}const $=N.changed||(j?!!N.actions.length||E||typeof j.value!=typeof N.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]))}(N.value,j.value):void 0);return N.changed=$,N.historyValue=x.historyValue,N.history=j,N}getStateNode(t){if(Nt(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=Nt(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&&Nt(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||jt;switch(this.type){case"parallel":return a(this.initialStateValue,(e,i)=>e?this.getStateNode(i).resolve(t[i]||e):jt);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):jt):this.initialStateValue||{};default:return t||jt}}getResolvedPath(t){if(Nt(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||jt,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=I(this.states[this.initial])?this.initial:{[this.initial]:this.states[this.initial].initialStateValue}}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)&&Nt(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(I(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:rt(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=P(i,[s+""]);t=u(e(r).map(t=>$(t,r[t])).concat($("*",o)))}else t=[];const i=this.config.onDone?$(String(mt(this.id)),this.config.onDone):[],s=u(this.invoke.map(t=>{const e=[];return t.onDone&&e.push(...$(String(bt(t.id)),t.onDone)),t.onError&&e.push(...$(String(St(t.id)),t.onError)),e})),n=this.after,o=u([...i,...s,...t].map(t=>f(t).map(t=>this.formatTransition(t))));for(const t of n)o.push(t);return o}}function Tt(t,e,i=t.context){const s="function"==typeof i?i():i;return new $t(t,e,s)}function kt(t,e){const i="function"==typeof t.context?t.context():t.context;return new $t(t,e,i)}const Pt={deferEvents:!1};class Vt{constructor(t){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=Object.assign(Object.assign({},Pt),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 Ct=new Map;let It=0;const Lt={bookId:()=>`x:${It++}`,register:(t,e)=>(Ct.set(t,e),t),get:t=>Ct.get(t),free(t){Ct.delete(t)}},At={sync:!1,autoForward:!1},Rt=(()=>{const t=[];return(e,i)=>{e&&t.push(e);const s=i(e||t[t.length-1]);return e&&t.pop(),s}})();var Mt;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(Mt||(Mt={}));class Dt{constructor(t,e=Dt.defaultOptions){this.machine=t,this.scheduler=new Vt,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=Mt.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(j(t,e));if(this._status===Mt.Stopped)return this.state;if(this._status===Mt.NotStarted&&this.options.deferEvents);else if(this._status!==Mt.Running)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===C.Parent||this.parent.id===e),s=i?this.parent:Et(e)?e:this.children.get(e)||Lt.get(e);if(s)"machine"in s?s.send(Object.assign(Object.assign({},t),{name:t.name===Z?`${St(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({},Dt.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 Vt({deferEvents:this.options.deferEvents}),this.sessionId=Lt.bookId()}get initialState(){return this._initialState?this._initialState:Rt(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.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=z(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.data?p(i.data,t.context,e):void 0;for(const t of this.doneListeners)t(bt(this.id,s));this.stop()}}onTransition(t){return this.listeners.add(t),this._status===Mt.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===Mt.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===Mt.Running)return this;Lt.register(this.sessionId,this),this.initialized=!0,this._status=Mt.Running;const e=void 0===t?this.initialState:Rt(this,()=>{return!S(e=t)&&"value"in e&&"history"in e?this.machine.resolveState(t):this.machine.resolveState(Ot.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);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=Mt.Stopped,Lt.free(this.sessionId),this}batch(t){if(this._status===Mt.NotStarted&&this.options.deferEvents);else if(this._status!==Mt.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=Rt(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(Y)&&!this.state.nextEvents.some(t=>0===t.indexOf(Y)))throw e.data.data;return Rt(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||nt(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 q: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 X:this.cancel(t.sendId);break;case J:{const e=t.activity;if(!this.state.activities[e.id||e.type])break;if(e.type===V.Invoke){const t=this.machine.options.services?this.machine.options.services[e.src]:void 0,{id:i,data:o}=e,r="autoForward"in e?e.autoForward:!!e.forward;if(!t)return;const a=b(t)?t(s,n.data):t;g(a)?this.state.children[i]=this.spawnPromise(Promise.resolve(a),i):b(a)?this.state.children[i]=this.spawnCallback(a,i):x(a)?this.state.children[i]=this.spawnObservable(a,i):O(a)&&(this.state.children[i]=this.spawnMachine(o?a.withContext(p(o,s,n)):a,{id:i,autoForward:r}))}else this.spawnActivity(e);break}case U:this.stopChild(t.activity.id);break;case K: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(Et(t))return this.spawnActor(t);if(x(t))return this.spawnObservable(t,e);if(O(t))return this.spawnMachine(t,Object.assign(Object.assign({},i),{id:e}));throw new Error(`Unable to spawn entity "${e}" of type "${typeof t}".`)}spawnMachine(t,e={}){const i=new Dt(t,Object.assign(Object.assign({},this.options),{parent:this,id:e.id||t.id})),s=Object.assign(Object.assign({},At),e);s.sync&&i.onTransition(t=>{this.send(tt,{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;t.then(t=>{i||(this.removeChild(e),this.send(N(bt(e,t),{origin:e})))},t=>{if(!i){this.removeChild(e);const i=St(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 s={id:e,send:()=>{},subscribe:(e,i,s)=>{let n=!1;return t.then(t=>{n||(e&&e(t),n||s&&s())},t=>{n||i(t)}),{unsubscribe:()=>n=!0}},stop:()=>{i=!0},toJSON:()=>({id:e})};return this.children.set(e,s),s}spawnCallback(t,e){let i=!1;const s=new Set,n=new Set,o=t=>{n.forEach(e=>e(t)),i||this.send(t)};let r;try{r=t(o,t=>{s.add(t)})}catch(t){this.send(St(e,t))}if(g(r))return this.spawnPromise(r,e);const a={id:e,send:t=>s.forEach(e=>e(t)),subscribe:t=>(n.add(t),{unsubscribe:()=>{n.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(St(e,t),{origin:e}))},()=>{this.removeChild(e),this.send(N(bt(e),{origin:e}))}),s={id:e,send:()=>{},subscribe:(e,i,s)=>t.subscribe(e,i,s),stop:()=>i.unsubscribe(),toJSON:()=>({id:e})};return this.children.set(e,s),s}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(){if(this.options.devTools&&"undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__){const t="object"==typeof this.options.devTools?this.options.devTools:void 0;this.devTools=window.__REDUX_DEVTOOLS_EXTENSION__.connect(Object.assign(Object.assign({name:this.id,autoPause:!0,stateSanitizer:t=>({value:t.value,context:t.context,actions:t.actions})},t),{features:Object.assign({jump:!1,skip:!1},t?t.features:void 0)}),this.machine),this.devTools.init(this.state)}}toJSON(){return{id:this.id}}[_](){return this}}Dt.defaultOptions=(t=>({execute:!0,deferEvents:!0,clock:{setTimeout:(e,i)=>t.setTimeout.call(null,e,i),clearTimeout:e=>t.clearTimeout.call(null,e)},logger:t.console.log.bind(console),devTools:!1}))("undefined"==typeof window?global:window),Dt.interpret=zt;function Ft(t,e){const i=(t=>S(t)?Object.assign(Object.assign({},At),{name:t}):Object.assign(Object.assign(Object.assign({},At),{name:E()}),t))(e);return Rt(void 0,e=>e?e.spawn(t,i.name,i):((t="null")=>({id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:t})}))(i.name))}function zt(t,e){return new Dt(t,e)}function Jt(t,e,i){const s=Ot.from(t,t instanceof Ot?t.context:void 0);for(const[t,i]of e)if(s.matches(t))return i(s);return i(s)}const Ut={raise:ct,send:ht,sendParent:dt,sendUpdate:ut,log:function(t=lt,e){return{type:K,label:e,expr:t}},cancel:ft,start:pt,stop:gt,assign:vt,after:yt,done:mt,respond:function(t,e){return ht(t,Object.assign(Object.assign({},e),{to:(t,e,{_event:i})=>i.origin}))},forwardTo:wt,escalate:function(t,e){return dt((e,i,s)=>({type:Z,data:b(t)?t(e,i,s):t}),Object.assign(Object.assign({},e),{to:C.Parent}))},choose:function(t){return{type:V.Choose,conds:t}},pure:function(t){return{type:V.Pure,get:t}}};export{V as ActionTypes,Dt as Interpreter,Tt as Machine,C as SpecialTargets,Ot as State,$t as StateNode,Ut as actions,vt as assign,kt as createMachine,bt as doneInvoke,wt as forwardTo,zt as interpret,k as mapState,Jt as matchState,i as matchesState,ht as send,dt as sendParent,ut as sendUpdate,Ft as spawn};
15
+ ***************************************************************************** */function V(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 C,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"}(C||(C={})),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 F(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 z(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&&z(t,e)):"parallel"===e.type&&D(e).every(e=>J(t,e))}const U=C.Start,B=C.Stop,q=C.Raise,X=C.Send,H=C.Cancel,G=C.NullEvent,K=C.Assign,Q=(C.After,C.DoneState,C.Log),W=C.Init,Y=C.Invoke,Z=(C.ErrorExecution,C.ErrorPlatform),tt=C.ErrorCustom,et=C.Update,it=C.Choose,st=C.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:C.Start,activity:e,exec:void 0}}function vt(t){const e=b(t)?t:ct(t);return{type:C.Stop,activity:e,exec:void 0}}const yt=t=>({type:K,assignment:t});function mt(t,e){const i=e?`#${e}`:"";return`${C.After}(${t})${i}`}function bt(t,e){const i=`${C.DoneState}.${t}`,s={type:i,data:e,toString:()=>i};return s}function St(t,e){const i=`${C.DoneInvoke}.${t}`,s={type:i,data:e,toString:()=>i};return s}function wt(t,e){const i=`${C.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(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:C.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){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: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(){return V(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 $t(t){return{id:t,send:()=>{},subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:t})}}function Tt(t,e,i){const s=$t(e);return s.deferred=!0,_(t)&&(s.state=Nt(void 0,()=>(i?t.withContext(i):t).initialState)),s}function kt(t){try{return"function"==typeof t.send}catch(t){return!1}}function Pt(t){if("string"==typeof t){const e={type:t,toString:()=>t};return e}return t}function Vt(t){return Object.assign(Object.assign({type:Y},t),{toJSON(){const e=V(t,["onDone","onError"]);return Object.assign(Object.assign({},e),{type:Y,src:Pt(t.src)})}})}const Ct={},It=t=>"#"===t[0];class Lt{constructor(t,i,s){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.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.initial=this.config.initial,this.states=this.config.states?a(this.config.states,(t,e)=>{const i=new Lt(t,{_parent:this,_key:e});return Object.assign(this.idMap,Object.assign({[i.id]:i},i.idMap)),i}):Ct;let n=0;!function t(e){e.order=n++;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),Vt({src:t.id,id:t.id});if(S(t.src))return Vt(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),Vt(Object.assign(Object.assign({id:i},t),{src:i}))}{const e=t.src;return Vt(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:s,guards:n,services:o,delays:r}=this.options;return new Lt(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 Lt(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.states[i]]}const s=e(i);return s.map(t=>this.getStateNode(t)).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}))}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)&&It(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||T(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)z(n,e)||t.entrySet.push(e);for(const e of n)z(o,e)&&!z(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?F(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[u,l]=Ot(this,i,c,s,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,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?Tt(r,t.id,a):$t(t.id);return c.meta=t,c}(e.activity,this.machine,l,s),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:s,_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=s.name===et||E;const{history:N}=O;if(N&&delete N.history,!r)return O;let $=O;if(!x){for((this._transient||o.some(t=>t._transient))&&($=this.resolveRaisedTransition($,{type:G},s));f.length;){const t=f.shift();$=this.resolveRaisedTransition($,t._event,s)}}const T=$.changed||(N?!!$.actions.length||E||typeof N.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,N.value):void 0);return $.changed=T,$.historyValue=O.historyValue,$.history=N,$}getStateNode(t){if(It(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=It(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&&It(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(It(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}}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)&&It(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=V(i,[s+""]);t=u(e(r).map(t=>$(t,r[t])).concat($("*",o)))}else t=[];const i=this.config.always?$("",this.config.always):[],s=this.config.onDone?$(String(bt(this.id)),this.config.onDone):[],n=u(this.invoke.map(t=>{const e=[];return t.onDone&&e.push(...$(String(St(t.id)),t.onDone)),t.onError&&e.push(...$(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 Dt(t,e,i=t.context){const s="function"==typeof i?i():i;return new Lt(t,e,s)}function At(t,e){const i="function"==typeof t.context?t.context():t.context;return new Lt(t,e,i)}const Rt={deferEvents:!1};class Mt{constructor(t){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=Object.assign(Object.assign({},Rt),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 Ft=new Map;let zt=0;const Jt={bookId:()=>`x:${zt++}`,register:(t,e)=>(Ft.set(t,e),t),get:t=>Ft.get(t),free(t){Ft.delete(t)}},Ut={sync:!1,autoForward:!1};var Bt;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(Bt||(Bt={}));class qt{constructor(t,e=qt.defaultOptions){this.machine=t,this.scheduler=new Mt,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=Bt.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===Bt.Stopped)return this.state;if(this.status!==Bt.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:kt(e)?e:this.children.get(e)||Jt.get(e);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({},qt.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 Mt({deferEvents:this.options.deferEvents}),this.sessionId=Jt.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){this.state.configuration.forEach(e=>{for(const i of e.definition.exit)this.exec(i,t)});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===Bt.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===Bt.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===Bt.Running)return this;Jt.register(this.sessionId,this),this.initialized=!0,this.status=Bt.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);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=Bt.Stopped,Jt.free(this.sessionId),this}batch(t){if(this.status===Bt.NotStarted&&this.options.deferEvents);else if(this.status!==Bt.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===C.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(kt(t))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}".`)}spawnMachine(t,e={}){const i=new qt(t,Object.assign(Object.assign({},this.options),{parent:this,id:e.id||t.id})),s=Object.assign(Object.assign({},Ut),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;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 s={id:e,send:()=>{},subscribe:(e,i,s)=>{let n=!1;return t.then(t=>{n||(e&&e(t),n||s&&s())},t=>{n||i(t)}),{unsubscribe:()=>n=!0}},stop:()=>{i=!0},toJSON:()=>({id:e})};return this.children.set(e,s),s}spawnCallback(t,e){let i=!1;const s=new Set,n=new Set,o=t=>{n.forEach(e=>e(t)),i||this.send(t)};let r;try{r=t(o,t=>{s.add(t)})}catch(t){this.send(wt(e,t))}if(g(r))return this.spawnPromise(r,e);const a={id:e,send:t=>s.forEach(e=>e(t)),subscribe:t=>(n.add(t),{unsubscribe:()=>{n.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}))}),s={id:e,send:()=>{},subscribe:(e,i,s)=>t.subscribe(e,i,s),stop:()=>i.unsubscribe(),toJSON:()=>({id:e})};return this.children.set(e,s),s}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(){if(this.options.devTools&&"undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__){const t="object"==typeof this.options.devTools?this.options.devTools:void 0;this.devTools=window.__REDUX_DEVTOOLS_EXTENSION__.connect(Object.assign(Object.assign({name:this.id,autoPause:!0,stateSanitizer:t=>({value:t.value,context:t.context,actions:t.actions})},t),{features:Object.assign({jump:!1,skip:!1},t?t.features:void 0)}),this.machine),this.devTools.init(this.state)}}toJSON(){return{id:this.id}}[O](){return this}}qt.defaultOptions=(t=>({execute:!0,deferEvents:!0,clock:{setTimeout:(e,i)=>t.setTimeout.call(null,e,i),clearTimeout:e=>t.clearTimeout.call(null,e)},logger:t.console.log.bind(console),devTools:!1}))("undefined"!=typeof self?self:global),qt.interpret=Ht;function Xt(t,e){const i=(t=>S(t)?Object.assign(Object.assign({},Ut),{name:t}):Object.assign(Object.assign(Object.assign({},Ut),{name:j()}),t))(e);return(e=>e?e.spawn(t,i.name,i):Tt(t,i.name))(Et[Et.length-1])}function Ht(t,e){return new qt(t,e)}function Gt(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)}const Kt={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:C.Choose,conds:t}},pure:function(t){return{type:C.Pure,get:t}}};export{C as ActionTypes,qt as Interpreter,Bt as InterpreterStatus,Dt as Machine,I as SpecialTargets,jt as State,Lt as StateNode,Kt as actions,yt as assign,At as createMachine,St as doneInvoke,xt as forwardTo,Ht as interpret,P as mapState,Gt as matchState,i as matchesState,dt as send,ut as sendParent,lt as sendUpdate,Xt as spawn};
package/es/Actor.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { EventObject, Subscribable, InvokeDefinition, AnyEventObject } from './types';
1
+ import { EventObject, Subscribable, InvokeDefinition, AnyEventObject, StateMachine, Spawnable, SCXML } from './types';
2
2
  export interface Actor<TContext = any, TEvent extends EventObject = AnyEventObject> extends Subscribable<TContext> {
3
3
  id: string;
4
4
  send: (event: TEvent) => any;
@@ -8,14 +8,16 @@ export interface Actor<TContext = any, TEvent extends EventObject = AnyEventObje
8
8
  };
9
9
  meta?: InvokeDefinition<TContext, TEvent>;
10
10
  state?: any;
11
+ deferred?: boolean;
11
12
  }
12
13
  export declare function createNullActor(id: string): Actor;
13
14
  /**
14
- * Creates a null actor that is able to be invoked given the provided
15
+ * Creates a deferred actor that is able to be invoked given the provided
15
16
  * invocation information in its `.meta` value.
16
17
  *
17
18
  * @param invokeDefinition The meta information needed to invoke the actor.
18
19
  */
19
- export declare function createInvocableActor<TC, TE extends EventObject>(invokeDefinition: InvokeDefinition<TC, TE>): Actor;
20
+ export declare function createInvocableActor<TC, TE extends EventObject>(invokeDefinition: InvokeDefinition<TC, TE>, machine: StateMachine<TC, any, TE>, context: TC, _event: SCXML.Event<TE>): Actor;
21
+ export declare function createDeferredActor(entity: Spawnable, id: string, data?: any): Actor;
20
22
  export declare function isActor(item: any): item is Actor;
21
23
  //# sourceMappingURL=Actor.d.ts.map
package/es/Actor.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { toInvokeSource, mapContext, isMachine } from './utils.js';
2
+ import { provide } from './serviceScope.js';
3
+
1
4
  function createNullActor(id) {
2
5
  return {
3
6
  id: id,
@@ -19,19 +22,38 @@ function createNullActor(id) {
19
22
  };
20
23
  }
21
24
  /**
22
- * Creates a null actor that is able to be invoked given the provided
25
+ * Creates a deferred actor that is able to be invoked given the provided
23
26
  * invocation information in its `.meta` value.
24
27
  *
25
28
  * @param invokeDefinition The meta information needed to invoke the actor.
26
29
  */
27
30
 
28
31
 
29
- function createInvocableActor(invokeDefinition) {
30
- var tempActor = createNullActor(invokeDefinition.id);
32
+ function createInvocableActor(invokeDefinition, machine, context, _event) {
33
+ var _a;
34
+
35
+ var invokeSrc = toInvokeSource(invokeDefinition.src);
36
+ var serviceCreator = (_a = machine === null || machine === void 0 ? void 0 : machine.options.services) === null || _a === void 0 ? void 0 : _a[invokeSrc.type];
37
+ var resolvedData = invokeDefinition.data ? mapContext(invokeDefinition.data, context, _event) : undefined;
38
+ var tempActor = serviceCreator ? createDeferredActor(serviceCreator, invokeDefinition.id, resolvedData) : createNullActor(invokeDefinition.id);
31
39
  tempActor.meta = invokeDefinition;
32
40
  return tempActor;
33
41
  }
34
42
 
43
+ function createDeferredActor(entity, id, data) {
44
+ var tempActor = createNullActor(id);
45
+ tempActor.deferred = true;
46
+
47
+ if (isMachine(entity)) {
48
+ // "mute" the existing service scope so potential spawned actors within the `.initialState` stay deferred here
49
+ tempActor.state = provide(undefined, function () {
50
+ return (data ? entity.withContext(data) : entity).initialState;
51
+ });
52
+ }
53
+
54
+ return tempActor;
55
+ }
56
+
35
57
  function isActor(item) {
36
58
  try {
37
59
  return typeof item.send === 'function';
@@ -40,4 +62,4 @@ function isActor(item) {
40
62
  }
41
63
  }
42
64
 
43
- export { createInvocableActor, createNullActor, isActor };
65
+ export { createDeferredActor, createInvocableActor, createNullActor, isActor };
package/es/State.d.ts CHANGED
@@ -2,7 +2,10 @@ import { StateValue, ActivityMap, EventObject, HistoryValue, ActionObject, Event
2
2
  import { StateNode } from './StateNode';
3
3
  import { Actor } from './Actor';
4
4
  export declare function stateValuesEqual(a: StateValue | undefined, b: StateValue | undefined): boolean;
5
- export declare function isState<TContext, TEvent extends EventObject, TStateSchema extends StateSchema<TContext> = any, TTypestate extends Typestate<TContext> = any>(state: object | string): state is State<TContext, TEvent, TStateSchema, TTypestate>;
5
+ export declare function isState<TContext, TEvent extends EventObject, TStateSchema extends StateSchema<TContext> = any, TTypestate extends Typestate<TContext> = {
6
+ value: any;
7
+ context: TContext;
8
+ }>(state: object | string): state is State<TContext, TEvent, TStateSchema, TTypestate>;
6
9
  export declare function bindActionToState<TC, TE extends EventObject>(action: ActionObject<TC, TE>, state: State<TC, TE>): ActionObject<TC, TE>;
7
10
  export declare class State<TContext, TEvent extends EventObject = EventObject, TStateSchema extends StateSchema<TContext> = any, TTypestate extends Typestate<TContext> = {
8
11
  value: any;
@@ -11,7 +14,7 @@ export declare class State<TContext, TEvent extends EventObject = EventObject, T
11
14
  value: StateValue;
12
15
  context: TContext;
13
16
  historyValue?: HistoryValue | undefined;
14
- history?: State<TContext, TEvent, TStateSchema>;
17
+ history?: State<TContext, TEvent, TStateSchema, TTypestate>;
15
18
  actions: Array<ActionObject<TContext, TEvent>>;
16
19
  activities: ActivityMap;
17
20
  meta: any;
package/es/StateNode.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { Event, StateValue, StateValueMap, MachineOptions, EventObject, HistoryValue, StateNodeDefinition, TransitionDefinition, DelayedTransitionDefinition, ActivityDefinition, StateNodeConfig, StateSchema, StateNodesConfig, InvokeDefinition, ActionObject, Mapper, PropertyMapper, SCXML, Typestate, TransitionDefinitionMap } from './types';
2
2
  import { State } from './State';
3
- declare class StateNode<TContext = any, TStateSchema extends StateSchema = any, TEvent extends EventObject = EventObject, TTypestate extends Typestate<TContext> = any> {
3
+ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any, TEvent extends EventObject = EventObject, TTypestate extends Typestate<TContext> = {
4
+ value: any;
5
+ context: TContext;
6
+ }> {
4
7
  /**
5
8
  * The raw config used to create the machine.
6
9
  */
@@ -92,7 +95,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
92
95
  /**
93
96
  * The data sent with the "done.state._id_" event if this is a final state node.
94
97
  */
95
- data?: Mapper<TContext, TEvent> | PropertyMapper<TContext, TEvent>;
98
+ doneData?: Mapper<TContext, TEvent, any> | PropertyMapper<TContext, TEvent, any>;
96
99
  /**
97
100
  * The string delimiter for serializing the path to a string. The default is "."
98
101
  */
@@ -156,7 +159,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
156
159
  *
157
160
  * @param state The state value or State instance
158
161
  */
159
- getStateNodes(state: StateValue | State<TContext, TEvent>): Array<StateNode<TContext, any, TEvent>>;
162
+ getStateNodes(state: StateValue | State<TContext, TEvent, any, TTypestate>): Array<StateNode<TContext, any, TEvent>>;
160
163
  /**
161
164
  * Returns `true` if this state node explicitly handles the given event.
162
165
  *
@@ -170,7 +173,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
170
173
  *
171
174
  * @param state The state to resolve
172
175
  */
173
- resolveState(state: State<TContext, TEvent>): State<TContext, TEvent>;
176
+ resolveState(state: State<TContext, TEvent>): State<TContext, TEvent, TStateSchema, TTypestate>;
174
177
  private transitionLeafNode;
175
178
  private transitionCompoundNode;
176
179
  private transitionParallelNode;
@@ -190,10 +193,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
190
193
  * @param event The event that was sent at the current state
191
194
  * @param context The current context (extended state) of the current state
192
195
  */
193
- transition(state: string | StateValueMap | State<TContext, TEvent, any, {
194
- value: any;
195
- context: TContext;
196
- }> | undefined, event: Event<TEvent> | SCXML.Event<TEvent>, context?: TContext): State<TContext, TEvent, TStateSchema, TTypestate>;
196
+ transition(state: string | StateValueMap | State<TContext, TEvent, any, TTypestate> | undefined, event: Event<TEvent> | SCXML.Event<TEvent>, context?: TContext): State<TContext, TEvent, TStateSchema, TTypestate>;
197
197
  private resolveRaisedTransition;
198
198
  private resolveTransition;
199
199
  /**
package/es/StateNode.js CHANGED
@@ -8,6 +8,7 @@ import { start as start$1, stop as stop$1, invoke, update, nullEvent, raise as r
8
8
  import { done, start, raise, stop, toActionObjects, resolveActions, doneInvoke, error, toActionObject, toActivityDefinition, after, send, cancel, initEvent } from './actions.js';
9
9
  import { State, stateValuesEqual } from './State.js';
10
10
  import { createInvocableActor } from './Actor.js';
11
+ import { toInvokeDefinition } from './invokeUtils.js';
11
12
  var NULL_EVENT = '';
12
13
  var STATE_IDENTIFIER = '#';
13
14
  var WILDCARD = '*';
@@ -124,10 +125,10 @@ function () {
124
125
  dfs(this); // History config
125
126
 
126
127
  this.history = this.config.history === true ? 'shallow' : this.config.history || false;
127
- this._transient = !this.config.on ? false : Array.isArray(this.config.on) ? this.config.on.some(function (_a) {
128
+ this._transient = !!this.config.always || (!this.config.on ? false : Array.isArray(this.config.on) ? this.config.on.some(function (_a) {
128
129
  var event = _a.event;
129
130
  return event === NULL_EVENT;
130
- }) : NULL_EVENT in this.config.on;
131
+ }) : NULL_EVENT in this.config.on);
131
132
  this.strict = !!this.config.strict; // TODO: deprecate (entry)
132
133
 
133
134
  this.onEntry = toArray(this.config.entry || this.config.onEntry).map(function (action) {
@@ -138,39 +139,47 @@ function () {
138
139
  return toActionObject(action);
139
140
  });
140
141
  this.meta = this.config.meta;
141
- this.data = this.type === 'final' ? this.config.data : undefined;
142
+ this.doneData = this.type === 'final' ? this.config.data : undefined;
142
143
  this.invoke = toArray(this.config.invoke).map(function (invokeConfig, i) {
143
144
  var _a, _b;
144
145
 
145
146
  if (isMachine(invokeConfig)) {
146
147
  _this.machine.options.services = __assign((_a = {}, _a[invokeConfig.id] = invokeConfig, _a), _this.machine.options.services);
147
- return {
148
- type: invoke,
148
+ return toInvokeDefinition({
149
149
  src: invokeConfig.id,
150
150
  id: invokeConfig.id
151
- };
152
- } else if (typeof invokeConfig.src !== 'string') {
151
+ });
152
+ } else if (isString(invokeConfig.src)) {
153
+ return toInvokeDefinition(__assign(__assign({}, invokeConfig), {
154
+ id: invokeConfig.id || invokeConfig.src,
155
+ src: invokeConfig.src
156
+ }));
157
+ } else if (isMachine(invokeConfig.src) || isFunction(invokeConfig.src)) {
153
158
  var invokeSrc = _this.id + ":invocation[" + i + "]"; // TODO: util function
154
159
 
155
160
  _this.machine.options.services = __assign((_b = {}, _b[invokeSrc] = invokeConfig.src, _b), _this.machine.options.services);
156
- return __assign(__assign({
157
- type: invoke,
161
+ return toInvokeDefinition(__assign(__assign({
158
162
  id: invokeSrc
159
163
  }, invokeConfig), {
160
164
  src: invokeSrc
161
- });
165
+ }));
162
166
  } else {
163
- return __assign(__assign({}, invokeConfig), {
164
- type: invoke,
165
- id: invokeConfig.id || invokeConfig.src,
166
- src: invokeConfig.src
167
- });
167
+ var invokeSource = invokeConfig.src;
168
+ return toInvokeDefinition(__assign(__assign({
169
+ id: invokeSource.type
170
+ }, invokeConfig), {
171
+ src: invokeSource
172
+ }));
168
173
  }
169
174
  });
170
175
  this.activities = toArray(this.config.activities).concat(this.invoke).map(function (activity) {
171
176
  return toActivityDefinition(activity);
172
177
  });
173
- this.transition = this.transition.bind(this);
178
+ this.transition = this.transition.bind(this); // TODO: this is the real fix for initialization once
179
+ // state node getters are deprecated
180
+ // if (!this.parent) {
181
+ // this._init();
182
+ // }
174
183
  }
175
184
 
176
185
  StateNode.prototype._init = function () {
@@ -243,11 +252,11 @@ function () {
243
252
  activities: this.activities || [],
244
253
  meta: this.meta,
245
254
  order: this.order || -1,
246
- data: this.data,
255
+ data: this.doneData,
247
256
  invoke: this.invoke
248
257
  };
249
258
  },
250
- enumerable: true,
259
+ enumerable: false,
251
260
  configurable: true
252
261
  });
253
262
 
@@ -271,14 +280,14 @@ function () {
271
280
  return map;
272
281
  }, {});
273
282
  },
274
- enumerable: true,
283
+ enumerable: false,
275
284
  configurable: true
276
285
  });
277
286
  Object.defineProperty(StateNode.prototype, "after", {
278
287
  get: function () {
279
288
  return this.__cache.delayedTransitions || (this.__cache.delayedTransitions = this.getDelayedTransitions(), this.__cache.delayedTransitions);
280
289
  },
281
- enumerable: true,
290
+ enumerable: false,
282
291
  configurable: true
283
292
  });
284
293
  Object.defineProperty(StateNode.prototype, "transitions", {
@@ -288,7 +297,7 @@ function () {
288
297
  get: function () {
289
298
  return this.__cache.transitions || (this.__cache.transitions = this.formatTransitions(), this.__cache.transitions);
290
299
  },
291
- enumerable: true,
300
+ enumerable: false,
292
301
  configurable: true
293
302
  });
294
303
 
@@ -714,15 +723,15 @@ function () {
714
723
  return events;
715
724
  }
716
725
 
717
- events.push(done(sn.id, sn.data), // TODO: deprecate - final states should not emit done events for their own state.
718
- done(parent.id, sn.data ? mapContext(sn.data, currentContext, _event) : undefined));
726
+ events.push(done(sn.id, sn.doneData), // TODO: deprecate - final states should not emit done events for their own state.
727
+ done(parent.id, sn.doneData ? mapContext(sn.doneData, currentContext, _event) : undefined));
719
728
  var grandparent = parent.parent;
720
729
 
721
730
  if (grandparent.type === 'parallel') {
722
731
  if (getChildren(grandparent).every(function (parentNode) {
723
732
  return isInFinalState(transition.configuration, parentNode);
724
733
  })) {
725
- events.push(done(grandparent.id, grandparent.data));
734
+ events.push(done(grandparent.id));
726
735
  }
727
736
  }
728
737
 
@@ -807,6 +816,7 @@ function () {
807
816
 
808
817
  var currentActions = state.actions;
809
818
  state = this.transition(state, _event); // Save original event to state
819
+ // TODO: this should be the raised event! Delete in V5 (breaking)
810
820
 
811
821
  state._event = originalEvent;
812
822
  state.event = originalEvent.data;
@@ -819,6 +829,8 @@ function () {
819
829
  StateNode.prototype.resolveTransition = function (stateTransition, currentState, _event, context) {
820
830
  var e_6, _a;
821
831
 
832
+ var _this = this;
833
+
822
834
  if (_event === void 0) {
823
835
  _event = initEvent;
824
836
  }
@@ -871,10 +883,12 @@ function () {
871
883
  nonRaisedActions = _c[1];
872
884
 
873
885
  var invokeActions = resolvedActions.filter(function (action) {
874
- return action.type === start$1 && action.activity.type === invoke;
886
+ var _a;
887
+
888
+ return action.type === start$1 && ((_a = action.activity) === null || _a === void 0 ? void 0 : _a.type) === invoke;
875
889
  });
876
890
  var children = invokeActions.reduce(function (acc, action) {
877
- acc[action.activity.id] = createInvocableActor(action.activity);
891
+ acc[action.activity.id] = createInvocableActor(action.activity, _this.machine, updatedContext, _event);
878
892
  return acc;
879
893
  }, currentState ? __assign({}, currentState.children) : {});
880
894
  var resolvedConfiguration = resolvedStateValue ? stateTransition.configuration : currentState ? currentState.configuration : [];
@@ -1105,7 +1119,7 @@ function () {
1105
1119
  this.__cache.initialStateValue = initialStateValue;
1106
1120
  return this.__cache.initialStateValue;
1107
1121
  },
1108
- enumerable: true,
1122
+ enumerable: false,
1109
1123
  configurable: true
1110
1124
  });
1111
1125
 
@@ -1127,7 +1141,8 @@ function () {
1127
1141
  * entering the initial state.
1128
1142
  */
1129
1143
  get: function () {
1130
- this._init();
1144
+ this._init(); // TODO: this should be in the constructor (see note in constructor)
1145
+
1131
1146
 
1132
1147
  var initialStateValue = this.initialStateValue;
1133
1148
 
@@ -1137,7 +1152,7 @@ function () {
1137
1152
 
1138
1153
  return this.getInitialState(initialStateValue);
1139
1154
  },
1140
- enumerable: true,
1155
+ enumerable: false,
1141
1156
  configurable: true
1142
1157
  });
1143
1158
  Object.defineProperty(StateNode.prototype, "target", {
@@ -1160,7 +1175,7 @@ function () {
1160
1175
 
1161
1176
  return target;
1162
1177
  },
1163
- enumerable: true,
1178
+ enumerable: false,
1164
1179
  configurable: true
1165
1180
  });
1166
1181
  /**
@@ -1201,7 +1216,7 @@ function () {
1201
1216
  return _this.getFromRelativePath(initialPath);
1202
1217
  }));
1203
1218
  },
1204
- enumerable: true,
1219
+ enumerable: false,
1205
1220
  configurable: true
1206
1221
  });
1207
1222
  /**
@@ -1303,7 +1318,7 @@ function () {
1303
1318
  }));
1304
1319
  return [this.id].concat(childStateIds);
1305
1320
  },
1306
- enumerable: true,
1321
+ enumerable: false,
1307
1322
  configurable: true
1308
1323
  });
1309
1324
  Object.defineProperty(StateNode.prototype, "events", {
@@ -1360,7 +1375,7 @@ function () {
1360
1375
 
1361
1376
  return this.__cache.events = Array.from(events);
1362
1377
  },
1363
- enumerable: true,
1378
+ enumerable: false,
1364
1379
  configurable: true
1365
1380
  });
1366
1381
  Object.defineProperty(StateNode.prototype, "ownEvents", {
@@ -1377,7 +1392,7 @@ function () {
1377
1392
  }));
1378
1393
  return Array.from(events);
1379
1394
  },
1380
- enumerable: true,
1395
+ enumerable: false,
1381
1396
  configurable: true
1382
1397
  });
1383
1398
 
@@ -1439,7 +1454,7 @@ function () {
1439
1454
  target: transition.target ? transition.target.map(function (t) {
1440
1455
  return "#" + t.id;
1441
1456
  }) : undefined,
1442
- source: "#{this.id}"
1457
+ source: "#" + _this.id
1443
1458
  });
1444
1459
  }
1445
1460
  });
@@ -1463,19 +1478,24 @@ function () {
1463
1478
  _c = WILDCARD,
1464
1479
  _d = _b[_c],
1465
1480
  wildcardConfigs = _d === void 0 ? [] : _d,
1466
- strictOnConfigs_1 = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
1481
+ strictTransitionConfigs_1 = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
1482
+
1483
+ onConfig = flatten(keys(strictTransitionConfigs_1).map(function (key) {
1484
+ if (!IS_PRODUCTION && key === NULL_EVENT) {
1485
+ warn(false, "Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. " + ("Please check the `on` configuration for \"#" + _this.id + "\"."));
1486
+ }
1467
1487
 
1468
- onConfig = flatten(keys(strictOnConfigs_1).map(function (key) {
1469
- var arrayified = toTransitionConfigArray(key, strictOnConfigs_1[key]);
1488
+ var transitionConfigArray = toTransitionConfigArray(key, strictTransitionConfigs_1[key]);
1470
1489
 
1471
1490
  if (!IS_PRODUCTION) {
1472
- validateArrayifiedTransitions(_this, key, arrayified);
1491
+ validateArrayifiedTransitions(_this, key, transitionConfigArray);
1473
1492
  }
1474
1493
 
1475
- return arrayified;
1494
+ return transitionConfigArray;
1476
1495
  }).concat(toTransitionConfigArray(WILDCARD, wildcardConfigs)));
1477
1496
  }
1478
1497
 
1498
+ var eventlessConfig = this.config.always ? toTransitionConfigArray('', this.config.always) : [];
1479
1499
  var doneConfig = this.config.onDone ? toTransitionConfigArray(String(done(this.id)), this.config.onDone) : [];
1480
1500
 
1481
1501
  if (!IS_PRODUCTION) {
@@ -1496,7 +1516,7 @@ function () {
1496
1516
  return settleTransitions;
1497
1517
  }));
1498
1518
  var delayedTransitions = this.after;
1499
- var formattedTransitions = flatten(__spread(doneConfig, invokeConfig, onConfig).map(function (transitionConfig) {
1519
+ var formattedTransitions = flatten(__spread(doneConfig, invokeConfig, onConfig, eventlessConfig).map(function (transitionConfig) {
1500
1520
  return toArray(transitionConfig).map(function (transition) {
1501
1521
  return _this.formatTransition(transition);
1502
1522
  });