Files
30-seconds-of-code/node_modules/xstate/dist/xstate.web.js
2019-08-20 15:52:05 +02:00

2 lines
37 KiB
JavaScript

var t,e;!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.Update="xstate.update",t.Pure="xstate.pure"}(t||(t={})),function(t){t.Parent="#_parent",t.Internal="#_internal"}(e||(e={}));const i=".",s={},n="xstate.guard";function o(t){return!$(t)&&("value"in t&&"tree"in t&&"history"in t)}function r(t){return Object.keys(t)}function a(t,e,s=i){const n=d(t,s),o=d(e,s);return $(o)?!!$(n)&&o===n:$(n)?n in o:r(n).every(t=>t in o&&a(n[t],o[t]))}function h(t){try{return $(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 c(t,e){try{return N(t)?t:t.toString().split(e)}catch(e){throw new Error(`'${t}' is not a valid state path.`)}}function d(t,e){if(o(t))return t.value;if(N(t))return u(t);if("string"!=typeof t&&!o(t))return t;return u(c(t,e))}function u(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 l(t,e){const i={},s=r(t);for(let n=0;n<s.length;n++){const o=s[n];i[o]=e(t[o],o,t,n)}return i}function f(t,e,i){const s={};for(const n of r(t)){const o=t[n];i(o)&&(s[n]=e(o,n,t))}return s}const p=t=>e=>{let i=e;for(const e of t)i=i[e];return i};function v(t){if(!t)return[[]];if($(t))return[[t]];return y(r(t).map(e=>{const i=t[e];return"string"==typeof i||i&&Object.keys(i).length?v(t[e]).map(t=>[e].concat(t)):[[e]]}))}function y(t){return[].concat(...t)}function g(t){return N(t)?t:void 0===t?[]:[t]}function m(t,e,i){if(O(t))return t(e,i);const s={};for(const n of r(t)){const o=t[n];O(o)?s[n]=o(e,i):s[n]=o}return s}function w(t){return t instanceof Promise||!(null===t||!O(t)&&"object"!=typeof t||!O(t.then))}function S(t,e){const[i,s]=[[],[]];for(const n of t)e(n)?i.push(n):s.push(n);return[i,s]}function x(t,e){return l(t.states,(t,i)=>{if(!t)return;const s=($(e)?void 0:e[i])||(t?t.current:void 0);return s?{current:s,states:x(t,s)}:void 0})}function b(e,i,s){return e?s.reduce((e,s)=>{const{assignment:n}=s;let o={};if(O(n))o=n(e,i||{type:t.Init});else for(const t of r(n)){const s=n[t];o[t]=O(s)?s(e,i):s}return Object.assign({},e,o)},e):e}function E(t,e){const{exec:i}=t;return Object.assign({},t,{exec:void 0!==i?()=>i(e.context,e.event,{action:t,state:e}):void 0})}function N(t){return Array.isArray(t)}function O(t){return"function"==typeof t}function $(t){return"string"==typeof t}function _(t,e){if(t)return $(t)?{type:n,name:t,predicate:e?e[t]:void 0}:O(t)?{type:n,name:t.name,predicate:t}:t}function j(t){try{return"subscribe"in t&&O(t.subscribe)}catch(t){return!1}}function k(t){try{return"__xstatenode"in t}catch(t){return!1}}const T=(()=>{let t=0;return()=>(++t).toString(16)})();function V(t,e){let i;for(const s of r(t))a(s,e)&&(!i||e.length>i.length)&&(i=s);return t[i]}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&&(i[s[n]]=t[s[n]])}return i}class I{constructor(t){this.actions=[],this.activities=s,this.meta={},this.events=[],this.value=t.value,this.context=t.context,this.event=t.event,this.historyValue=t.historyValue,this.history=t.history,this.actions=t.actions||[],this.activities=t.activities||s,this.meta=t.meta||{},this.events=t.events||[],Object.defineProperty(this,"tree",{value:t.tree,enumerable:!1}),this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this)}static from(e,i){if(e instanceof I)return e.context!==i?new I({value:e.value,context:i,event:e.event,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],tree:e.tree}):e;const s={type:t.Init};return new I({value:e,context:i,event:s,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[]})}static create(t){return new I(t)}static inert(e,i){if(e instanceof I){if(!e.actions.length)return e;const s={type:t.Init};return new I({value:e.value,context:i,event:s,historyValue:e.historyValue,history:e.history,activities:e.activities,tree:e.tree})}return I.from(e,i)}get inert(){return I.inert(this,this.context)}get nextEvents(){return this.tree?this.tree.nextEvents:[]}toStrings(t=this.value,e="."){if($(t))return[t];const i=r(t);return i.concat(...i.map(i=>this.toStrings(t[i]).map(t=>i+e+t)))}matches(t){return a(t,this.value)}}const L=t.Start,D=t.Stop,C=t.Raise,M=t.Send,R=t.Cancel,z=t.NullEvent,A=t.Assign,F=(t.After,t.DoneState,t.Log),U=t.Init,B=t.Invoke,J=(t.ErrorExecution,t.ErrorPlatform),q=t.Update,X={type:U};function G(t,e){if($(t)||"number"==typeof t){const i={type:t};return e&&Object.assign(i,e),i}return t}function H(t,e){return e&&e[t]||void 0}function K(t,e){let i;if($(t)||"number"==typeof t){const s=H(t,e);i=O(s)?{type:t,exec:s}:s||{type:t,exec:void 0}}else if(O(t))i={type:t.name||t.toString(),exec:t};else{const s=H(t.type,e);if(O(s))i=Object.assign({},t,{exec:s});else if(s){const{type:e}=t,n=P(t,["type"]);i=Object.assign({type:e},s,n)}else i=t}return Object.defineProperty(i,"toString",{value:()=>i.type,enumerable:!1,configurable:!0}),i}const Q=(t,e)=>{if(!t)return[];return(N(t)?t:[t]).map(t=>K(t,e))};function W(t){const e=K(t);return Object.assign({id:$(t)?t:e.id},e,{type:e.type})}function Y(t){return{type:C,event:t}}function Z(t,e){return{to:e?e.to:void 0,type:M,event:O(t)?t:G(t),delay:e?e.delay:void 0,id:e&&void 0!==e.id?e.id:O(t)?t.name:h(t)}}function tt(t,i){return Z(t,Object.assign({},i,{to:e.Parent}))}const et=t=>({type:R,sendId:t});function it(e){const i=W(e);return{type:t.Start,activity:i,exec:void 0}}function st(e){const i=W(e);return{type:t.Stop,activity:i,exec:void 0}}const nt=t=>({type:A,assignment:t});function ot(e,i){const s=i?`#${i}`:"";return`${t.After}(${e})${s}`}function rt(e,i){const s=`${t.DoneState}.${e}`,n={type:s,data:i,toString:()=>s};return n}function at(e,i){const s=`${t.DoneInvoke}.${e}`,n={type:s,data:i,toString:()=>s};return n}function ht(e,i){const s=`${t.ErrorPlatform}.${e}`,n={type:s,data:i,toString:()=>s};return n}const ct={resolved:!1};class dt{constructor(t,e,i=ct,s){this.stateNode=t,this.stateValue=e,this.parent=s,this.reentryNodes=new Set,this.root=this.parent?this.parent.root:this,this.nodes=e?$(e)?{[e]:new dt(t.getStateNode(e),void 0,void 0,this)}:l(e,(e,i)=>new dt(t.getStateNode(i),e,void 0,this)):{};const n=Object.assign({},ct,i);this.isResolved=n.resolved}get done(){switch(this.stateNode.type){case"final":return!0;case"compound":return"final"===this.nodes[r(this.nodes)[0]].stateNode.type;case"parallel":return r(this.nodes).every(t=>this.nodes[t].done);default:return!1}}getDoneData(t,e){if(this.done&&"compound"===this.stateNode.type){const i=this.nodes[r(this.nodes)[0]];if(!i.stateNode.data)return;return m(i.stateNode.data,t,e)}}get atomicNodes(){return"atomic"===this.stateNode.type||"final"===this.stateNode.type?[this.stateNode]:y(r(this.value).map(t=>this.value[t].atomicNodes))}getDoneEvents(t){if(!t||!t.size)return[];if(t.has(this.stateNode)&&"final"===this.stateNode.type)return[rt(this.stateNode.id,this.stateNode.data)];const e=y(r(this.nodes).map(e=>this.nodes[e].getDoneEvents(t)));if("parallel"===this.stateNode.type){const t=r(this.nodes).every(t=>this.nodes[t].done);return e&&t?e.concat(rt(this.stateNode.id)):e}if(!this.done||!e.length)return e;const i=1===e.length?e[0].data:void 0;return e.concat(rt(this.stateNode.id,i))}get resolved(){const t=new dt(this.stateNode,this.stateNode.resolve(this.value),{resolved:!0});return t.reentryNodes=this.reentryNodes,t}get paths(){return v(this.value)}get absolute(){const{stateValue:t}=this,e={};let i=e;for(let e=0;e<this.stateNode.path.length;e++){const s=this.stateNode.path[e];e===this.stateNode.path.length-1?i[s]=t:(i[s]={},i=i[s])}const s=new dt(this.stateNode.machine,e);return s.reentryNodes=this.reentryNodes,s}get nextEvents(){const t=this.stateNode.ownEvents,e=y(r(this.nodes).map(t=>{return this.nodes[t].nextEvents}));return[...new Set(e.concat(t))]}clone(){return new dt(this.stateNode,this.value,void 0,this.parent)}combine(t){if(t.stateNode!==this.stateNode)throw new Error("Cannot combine distinct trees");const e=this.clone();if(t.root.reentryNodes.forEach(t=>{e.root.addReentryNode(t)}),"compound"===this.stateNode.type){let i;if(r(this.nodes).length&&r(t.nodes).length){const s=r(this.nodes)[0];return i={[s]:this.nodes[s].combine(t.nodes[s])},e.nodes=i,e}return i=Object.assign({},this.nodes,t.nodes),e.nodes=i,e}if("parallel"===this.stateNode.type){const i=new Set([...r(this.nodes),...r(t.nodes)]),s={};for(const e of i)this.nodes[e]&&t.nodes[e]?s[e]=this.nodes[e].combine(t.nodes[e]):s[e]=this.nodes[e]||t.nodes[e];return e.nodes=s,e}return this}get value(){if("atomic"===this.stateNode.type||"final"===this.stateNode.type)return{};if("parallel"===this.stateNode.type)return l(this.nodes,t=>t.value);if("compound"===this.stateNode.type){if(0===r(this.nodes).length)return{};const t=this.nodes[r(this.nodes)[0]].stateNode;return"atomic"===t.type||"final"===t.type?t.key:l(this.nodes,t=>t.value)}return{}}matches(t){return a(t,this.value)}getEntryExitStates(t){const e=this.root.reentryNodes;if(!t)return{exit:[],entry:[...e]};if(t.stateNode!==this.stateNode)throw new Error("Cannot compare distinct trees");switch(this.stateNode.type){case"compound":let i={exit:[],entry:[]};const s=r(this.nodes)[0],n=r(t.nodes)[0];return s!==n?(i.exit=t.nodes[n].getExitStates(),i.entry=this.nodes[s].getEntryStates()):i=this.nodes[s].getEntryExitStates(t.nodes[n]),e&&e.has(this.stateNode)&&(i.exit.push(this.stateNode),i.entry.unshift(this.stateNode)),i;case"parallel":const o=r(this.nodes).map(e=>this.nodes[e].getEntryExitStates(t.nodes[e])),a={exit:[],entry:[]};for(const t of o)a.exit=[...a.exit,...t.exit],a.entry=[...a.entry,...t.entry];return e&&e.has(this.stateNode)&&(a.exit.push(this.stateNode),a.entry.unshift(this.stateNode)),a;case"atomic":default:return e&&e.has(this.stateNode)?{exit:[this.stateNode],entry:[this.stateNode]}:{exit:[],entry:[]}}}getEntryStates(){return this.nodes?[this.stateNode].concat(y(r(this.nodes).map(t=>this.nodes[t].getEntryStates()))):[this.stateNode]}getExitStates(){return this.nodes?y(r(this.nodes).map(t=>this.nodes[t].getExitStates())).concat(this.stateNode):[this.stateNode]}addReentryNode(t){this.root.reentryNodes.add(t)}}function ut(t){return r(t.states).map(e=>t.states[e])}function lt(t,e){const i=ft(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=ft(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 ut(t))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));return s}function ft(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 pt(t,e){return function t(e,i){const s={},n=i.get(e);if(!n)return{};if("compound"===e.type){if(!n[0])return{};if("atomic"===n[0].type)return n[0].key}return n.forEach(e=>{s[e.key]=t(e,i)}),s}(t,ft(lt([t],e)))}const vt=".",yt="",gt="#",mt="",wt={},St=t=>t[0]===gt,xt=()=>({actions:{},guards:{},services:{},activities:{},delays:{},updater:b});class bt{constructor(t,e,i){this.context=i,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,transitions:void 0},this.idMap={};const{parent:s}=t,n=P(t,["parent"]);this.config=n,this.parent=s,this.options=Object.assign({},xt(),e),this.key=t.key||t.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=t.delimiter||(this.parent?this.parent.delimiter:vt),this.id=t.id||(this.machine?[this.machine.key,...this.path].join(this.delimiter):this.key),this.version=this.parent?this.parent.version:t.version,this.type=t.type||(t.parallel?"parallel":t.states&&r(t.states).length?"compound":t.history?"history":"atomic"),this.initial=t.initial,this.order=t.order||-1,this.states=t.states?l(t.states,(t,e,i,s)=>{const n=new bt(Object.assign({},t,{key:e,order:void 0===t.order?s:t.order,parent:this}));return Object.assign(this.idMap,Object.assign({[n.id]:n},n.idMap)),n}):wt,this.history=!0===t.history?"shallow":t.history||!1,this._transient=!(!t.on||!t.on[yt]),this.strict=!!t.strict,this.onEntry=g(t.entry||t.onEntry).map(t=>K(t)),this.onExit=g(t.exit||t.onExit).map(t=>K(t)),this.meta=t.meta,this.data="final"===this.type?t.data:void 0,this.invoke=g(t.invoke).map((t,e)=>{if(k(t))return(this.parent||this).options.services=Object.assign({[t.id]:t},(this.parent||this).options.services),{type:B,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({type:B,id:i},t,{src:i})}return Object.assign({},t,{type:B,id:t.id||t.src,src:t.src})}),this.activities=g(t.activities).concat(this.invoke).map(t=>W(t)),this.after=this.getDelayedTransitions()}withConfig(t,e=this.context){const{actions:i,activities:s,guards:n,services:o,delays:r}=this.options;return new bt(this.config,{actions:Object.assign({},i,t.actions),activities:Object.assign({},s,t.activities),guards:Object.assign({},n,t.guards),services:Object.assign({},o,t.services),delays:Object.assign({},r,t.delays)},e)}withContext(t){return new bt(this.config,this.options,t)}get definition(){return{id:this.id,key:this.key,version:this.version,type:this.type,initial:this.initial,history:this.history,states:l(this.states,t=>t.definition),on:this.on,onEntry:this.onEntry,onExit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.data,invoke:this.invoke}}toJSON(){return this.definition}get on(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)}get transitions(){return y(r(this.on).map(t=>this.on[t]))}getDelayedTransitions(){if(this.after)return this.after;const t=this.config.after,{guards:e}=this.machine.options;if(!t)return[];if(N(t))return t.map((t,i)=>{const{delay:s,target:n}=t;let o;O(s)?(o=`${this.id}:delay[${i}]`,this.options.delays[o]=s):o=s;const r=ot(o,this.id);return this.onEntry.push(Z(r,{delay:s})),this.onExit.push(et(r)),Object.assign({event:r},t,{source:this,target:void 0===n?void 0:g(n),cond:_(t.cond,e),actions:g(t.actions).map(t=>K(t))})});const i=y(r(t).map(i=>{const s=t[i],n=isNaN(+i)?i:+i,o=ot(n,this.id);return this.onEntry.push(Z(o,{delay:n})),this.onExit.push(et(o)),$(s)?[{source:this,target:[s],delay:n,event:o,actions:[]}]:g(s).map(t=>Object.assign({event:o,delay:n},t,{source:this,target:void 0===t.target?t.target:g(t.target),cond:_(t.cond,e),actions:g(t.actions).map(t=>K(t))}))}));return i.sort((t,e)=>$(t)||$(e)?0:+t.delay-+e.delay),i}getStateNodes(t){if(!t)return[];const e=t instanceof I?t.value:d(t,this.delimiter);if($(e)){const t=this.getStateNode(e).initial;return void 0!==t?this.getStateNodes({[e]:t}):[this.states[e]]}const i=r(e);return i.map(t=>this.getStateNode(t)).concat(i.reduce((t,i)=>{const s=this.getStateNode(i).getStateNodes(e[i]);return t.concat(s)},[]))}handles(t){const e=h(t);return-1!==this.events.indexOf(e)}resolveState(t){return new I(Object.assign({},t,{value:this.resolve(t.value),tree:this.getStateTree(t.value)}))}transitionLeafNode(t,e,i){const s=this.getStateNode(t).next(e,i);if(!s.tree){const{actions:t,tree:s,transitions:n,configuration:o}=this.next(e,i);return{tree:s,transitions:n,configuration:o,source:e,actions:t}}return s}transitionCompoundNode(t,e,i){const s=r(t),n=this.getStateNode(s[0])._transition(t[s[0]],e,i);if(!n.tree){const{actions:t,tree:s,transitions:n,configuration:o}=this.next(e,i);return{tree:s,transitions:n,configuration:o,source:e,actions:t}}return n}transitionParallelNode(t,e,i){const s={};for(const n of r(t)){const o=t[n];if(!o)continue;const r=this.getStateNode(n)._transition(o,e,i);r.tree,s[n]=r}const n=r(s).map(t=>s[t]),o=y(n.map(t=>t.transitions));if(!n.some(t=>void 0!==t.tree)){const{actions:t,tree:s,transitions:n,configuration:o}=this.next(e,i);return{tree:s,transitions:n,configuration:o,source:e,actions:t}}const h=y(n.map(t=>t.configuration)),c=this.getStateNodes(t),u=pt(this.machine,lt(c,h)),l=new dt(this.machine,u),f=l.paths,p=y(r(s).map(t=>s[t].configuration));return 1!==f.length||a(d(this.path,this.delimiter),l.value),{tree:l,transitions:o,configuration:p,source:e,actions:y(r(s).map(t=>s[t].actions))}}_transition(t,e,i){return $(t)?this.transitionLeafNode(t,e,i):1===r(t).length?this.transitionCompoundNode(t,e,i):this.transitionParallelNode(t,e,i)}next(t,e){const i=e.type,s=this.on[i];if(!s||!s.length)return{tree:void 0,transitions:[],configuration:[],source:t,actions:[]};const n=this._transient?[{type:z}]:[];let o,r=[];for(const h of s){const{cond:s,in:c}=h,u=t.context,l=!c||($(c)&&St(c)?t.matches(d(this.getStateNodeById(c).path,this.delimiter)):a(d(c,this.delimiter),p(this.path.slice(0,-2))(t.value)));let f=!1;try{f=!s||this.evaluateGuard(s,u,e,t)}catch(t){throw new Error(`Unable to evaluate guard '${s.name||s.type}' in transition for event '${i}' in state node '${this.id}':\n${t.message}`)}if(f&&l){void 0!==h.target&&(r=h.target),n.push(...g(h.actions)),o=h;break}}if(!r.length)return{tree:o&&t.value?new dt(this,p(this.path)(t.value)).absolute:void 0,transitions:[o],configuration:o&&t.value?[this]:[],source:t,actions:n};const h=y(r.map(e=>e instanceof bt?e:this.getRelativeStateNodes(e,t.historyValue))),c=!!o.internal?[]:y(h.map(t=>this.nodesFromChild(t))),u=h.map(t=>t.tree).reduce((t,e)=>t.combine(e));return c.forEach(t=>u.addReentryNode(t)),{tree:u,transitions:[o],configuration:h,source:t,actions:n}}get tree(){const t=d(this.path,this.delimiter);return new dt(this.machine,t)}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}getStateTree(t){return new dt(this,t)}escapes(t){if(this===t)return!1;let e=this.parent;for(;e;){if(e===t)return!1;e=e.parent}return!0}evaluateGuard(t,e,i,s){let o;const{guards:r}=this.machine.options,a={state:s,cond:t};if(t.type===n)return t.predicate(e,i,a);if(!r[t.type])throw new Error(`Guard '${t.type}' is not implemented on machine '${this.machine.id}'.`);return(o=r[t.type])(e,i,a)}getActions(t,e){const i=t.tree?t.tree.resolved.getEntryExitStates(e?this.getStateTree(e.value):void 0):{entry:[],exit:[]},s=t.tree?t.tree.getDoneEvents(new Set(i.entry)):[];t.source||(i.exit=[],i.entry.unshift(this));const n=new Set(i.entry),o=new Set(i.exit),[r,a]=[y(Array.from(n).map(t=>[...t.activities.map(t=>it(t)),...t.onEntry])).concat(s.map(Y)),y(Array.from(o).map(t=>[...t.onExit,...t.activities.map(t=>st(t))]))];return Q(a.concat(t.actions).concat(r),this.machine.options.actions)}transition(e,i,s){let n;if(e instanceof I)n=void 0===s?e:this.resolveState(I.from(e,s));else{const t=$(e)?this.resolve(u(this.getResolvedPath(e))):this.resolve(e),i=s||this.machine.context;n=this.resolveState(I.from(t,i))}const o=G(i),r=o.type;if(this.strict&&-1===this.events.indexOf(r)&&!function(e){return 0===e.indexOf(t.DoneState)||0===e.indexOf(t.DoneInvoke)||e===t.ErrorCommunication||e===t.ErrorExecution||0===e.indexOf(t.ErrorPlatform)}(r))throw new Error(`Machine '${this.id}' does not accept event '${r}'`);const a=this._transition(n.value,n,o);return a.tree&&(a.tree=a.tree.resolved),this.resolveTransition(a,n,o)}resolveTransition(e,i,s){const n=e.tree?e.tree.value:void 0,o=i?i.historyValue?i.historyValue:e.source?this.machine.historyValue(i.value):void 0:void 0,a=i?i.context:e.context||this.machine.context,h=s||{type:t.Init},c=this.getActions(e,i),d=i?Object.assign({},i.activities):{};for(const t of c)t.type===L?d[t.activity.type]=t:t.type===D&&(d[t.activity.type]=!1);const[u,l]=S(c,t=>t.type===C||t.type===z),[f,p]=S(l,t=>t.type===A),v=f.length?this.options.updater(a,h,f):a,g=y(p.map(e=>{if(e.type===M){const i=function(t,e,i){const s=O(t.event)?G(t.event(e,i)):G(t.event),n=O(t.delay)?t.delay(e,i):t.delay,o=O(t.to)?t.to(e,i):t.to;return Object.assign({},t,{to:o,event:s,delay:n})}(e,v,h||{type:t.Init});if($(i.delay)){if(!this.machine.options.delays||void 0===this.machine.options.delays[i.delay])return i;const e=this.machine.options.delays[i.delay];i.delay="number"==typeof e?e:e(v,h||{type:t.Init})}return i}return e.type===t.Pure?e.get(v,h)||[]:K(e,this.options.actions)})),m=n?this.getStateNodes(n):[];m.some(t=>t._transient)&&u.push({type:z});const w=[this,...m].reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{}),b=new I({value:n||i.value,context:v,event:h||X,historyValue:n?o?(E=o,N=n,{current:N,states:x(E,N)}):void 0:i?i.historyValue:void 0,history:!n||e.source?i:void 0,actions:n?g:[],activities:n?d:i?i.activities:{},meta:n?w:i?i.meta:void 0,events:n?u:[],tree:n?e.tree:i?i.tree:void 0});var E,N;b.changed=h.type===q||!!f.length;const{history:_}=b;if(_&&delete _.history,!n)return b;let j=b;for(;u.length;){const t=j.actions,e=u.shift();(j=this.transition(j,e.type===z?yt:e.event,j.context)).event=h,j.actions.unshift(...t)}const k=j.changed||(_?!!j.actions.length||!!f.length||typeof _.value!=typeof j.value||!function t(e,i){if(e===i)return!0;if(void 0===e||void 0===i)return!1;if($(e)||$(i))return e===i;const s=r(e),n=r(i);return s.length===n.length&&s.every(s=>t(e[s],i[s]))}(j.value,_.value):void 0);return j.changed=k,j.historyValue=b.historyValue,j.history=_,j}ensureValidPaths(t){}getStateNode(t){if(St(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=St(t)?t.slice(gt.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&&St(t))try{return this.getStateNodeById(t.slice(1))}catch(t){}const e=c(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||wt;switch(this.type){case"parallel":return l(this.initialStateValue,(e,i)=>e?this.getStateNode(i).resolve(t[i]||e):wt);case"compound":if($(t)){const e=this.getStateNode(t);return"parallel"===e.type||"compound"===e.type?{[t]:e.initialStateValue}:t}return r(t).length?l(t,(t,e)=>t?this.getStateNode(e).resolve(t):wt):this.initialStateValue||{};default:return t||wt}}get resolvedStateValue(){const{key:t}=this;if("parallel"===this.type)return{[t]:f(this.states,t=>t.resolvedStateValue[t.key],t=>!("history"===t.type))};if(void 0===this.initial)return t;if(!this.states[this.initial])throw new Error(`Initial state '${this.initial}' not found on '${t}'`);return{[t]:this.states[this.initial].resolvedStateValue}}getResolvedPath(t){if(St(t)){const e=this.machine.idMap[t.slice(gt.length)];if(!e)throw new Error(`Unable to find state node '${t}'`);return e.path}return c(t,this.delimiter)}get initialStateValue(){if(this.__cache.initialStateValue)return this.__cache.initialStateValue;const t="parallel"===this.type?f(this.states,t=>t.initialStateValue||wt,t=>!("history"===t.type)):$(this.resolvedStateValue)?void 0:this.resolvedStateValue[this.key];return this.__cache.initialStateValue=t,this.__cache.initialStateValue}getInitialState(t,e=this.machine.context){const i=this.getStateTree(t),s=this.getStateNodes(t);return s.forEach(t=>{i.addReentryNode(t)}),this.resolveTransition({tree:i,configuration:s,transitions:[],source:void 0,actions:[],context:e})}get initialState(){if(this.__cache.initialState)return this.__cache.initialState;const{initialStateValue:t}=this;if(!t)throw new Error(`Cannot retrieve initial state from simple state '${this.id}'.`);return this.__cache.initialState=this.getInitialState(t),this.__cache.initialState}get target(){let t;if("history"===this.type){const e=this.config;t=e.target&&$(e.target)&&St(e.target)?u(this.machine.getStateNodeById(e.target).path.slice(this.path.length-1)):e.target}return t}getStates(t){if($(t))return[this.states[t]];const e=[];for(const i of r(t))e.push(...this.states[i].getStates(t[i]));return e}getRelativeStateNodes(t,e,i=!0){if($(t)&&St(t)){const s=this.getStateNodeById(t);return i?"history"===s.type?s.resolveHistory(e):s.initialStateNodes:[s]}const s=c(t,this.delimiter),n=(this.parent||this).getFromRelativePath(s,e);return i?y(n.map(t=>t.initialStateNodes)):n}get initialStateNodes(){if("atomic"===this.type||"final"===this.type)return[this];if("compound"===this.type&&!this.initial)return[this];return y(v(this.initialStateValue).map(t=>this.getFromRelativePath(t)))}getFromRelativePath(t,e){if(!t.length)return[this];const[i,...s]=t;if(!this.states)throw new Error(`Cannot retrieve subPath '${i}' from node with no states`);const n=this.getStateNode(i);if("history"===n.type)return n.resolveHistory(e);if(!this.states[i])throw new Error(`Child state '${i}' does not exist on '${this.id}'`);return this.states[i].getFromRelativePath(s,e)}historyValue(t){if(r(this.states).length)return{current:t||this.initialStateValue,states:f(this.states,(e,i)=>{if(!t)return e.historyValue();const 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)return this.target?y(v(this.target).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 $(i)?[e.getStateNode(i)]:y(v(i).map(t=>"deep"===this.history?e.getFromRelativePath(t):[e.states[t[0]]]))}get stateIds(){const t=y(r(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,e=new Set(this.ownEvents);if(t)for(const i of r(t)){const s=t[i];if(s.states)for(const t of s.events)e.add(`${t}`)}return this.__cache.events=Array.from(e)}get ownEvents(){const t=new Set(r(this.on).filter(t=>{return this.on[t].some(t=>!(!t.target&&!t.actions.length&&t.internal))}));return Array.from(t)}formatTransition(t,e,i){let s=e?e.internal:void 0;const n=g(t),{guards:o}=this.machine.options,r=n.map(t=>{if(!$(t))return`#${t.id}`;const e=t[0]===this.delimiter;if(s=void 0===s?e:s,e&&!this.parent)return`#${this.getStateNodeByPath(t.slice(1)).id}`;const n=e?this.key+t:`${t}`;if(!this.parent)return`#${this.getStateNodeByPath(n).id}`;try{return`#${this.parent.getStateNodeByPath(n).id}`}catch(t){throw new Error(`Invalid transition for state node '${this.id}' on event '${i}':\n${t.message}`)}});if(void 0===e)return{target:void 0===t?void 0:r,source:this,actions:[],internal:void 0===t||s,event:i};const a=void 0===t||t===mt;return Object.assign({},e,{actions:Q(g(e.actions)),cond:_(e.cond,o),target:a?void 0:r,source:this,internal:a&&void 0===s||s,event:i})}formatTransitions(){const t=this.config.on||wt,e=this.config.onDone?{[`${rt(this.id)}`]:this.config.onDone}:void 0,i=this.invoke.reduce((t,e)=>(e.onDone&&(t[at(e.id)]=e.onDone),e.onError&&(t[ht(e.id)]=e.onError),t),{}),s=this.after,n=l(Object.assign({},t,e,i),(t,e)=>void 0===t?[{target:void 0,event:e,actions:[],internal:!0}]:N(t)?t.map(t=>this.formatTransition(t.target,t,e)):$(t)||k(t)?[this.formatTransition([t],void 0,e)]:[this.formatTransition(t.target,t,e)]);for(const t of s)n[t.event]=n[t.event]||[],n[t.event].push(t);return n}}function Et(t,e,i=t.context){return new bt(t,e,i)}const Nt={deferEvents:!1};class Ot{constructor(t){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=Object.assign({},Nt,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)}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.queue=[],t}finally{this.processingEvent=!1}}}const $t={sync:!1,autoForward:!1},_t=(()=>{const t=[];return(e,i)=>{e&&t.push(e);const s=i(e||t[t.length-1]);return e&&t.pop(),s}})();class jt{constructor(t,i=jt.defaultOptions){this.machine=t,this.scheduler=new Ot,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.children=new Map,this.forwardTo=new Set,this.init=this.start,this.send=((t,e)=>{if(N(t))return this.batch(t),this.state;const i=G(t,e);if(!this.initialized&&this.options.deferEvents);else if(!this.initialized)throw new Error(`Event "${i.type}" 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)}`);return this.scheduler.schedule(()=>{const t=this.nextState(i);this.update(t,i),this.forward(i)}),this.state}),this.sendTo=((t,i)=>{const s=i===e.Parent,n=s?this.parent:function(t){try{return"function"==typeof t.send}catch(t){return!1}}(i)?i:this.children.get(i);if(n)n.send(t);else if(!s)throw new Error(`Unable to send event to child '${i}' from service '${this.id}'.`)});const s=Object.assign({},jt.defaultOptions,i),{clock:n,logger:o,parent:r,id:a}=s,h=void 0!==a?a:t.id;this.id=h,this.logger=o,this.clock=n,this.parent=r,this.options=s,this.scheduler=new Ot({deferEvents:this.options.deferEvents}),this.initialState=this.state=_t(this,()=>this.machine.initialState)}execute(t,e){for(const i of t.actions)this.exec(i,t.context,t.event,e)}update(t,e){if(this.state=t,this.options.execute&&this.execute(this.state),this.devTools&&this.devTools.send(e,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);if(this.state.tree&&this.state.tree.done){const t=this.state.tree.getDoneData(this.state.context,G(e));for(const e of this.doneListeners)e(at(this.id,t));this.stop()}}onTransition(t){return this.listeners.add(t),this}subscribe(t,e,i){return t&&this.onTransition(t),i&&this.onDone(i),{unsubscribe:()=>{t&&this.listeners.delete(t),i&&this.doneListeners.delete(i)}}}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.initialized)return this;this.initialized=!0;const e=_t(this,()=>void 0===t?this.machine.initialState:t instanceof I?this.machine.resolveState(t):this.machine.resolveState(I.from(t)));return this.options.devTools&&this.attachDev(),this.scheduler.initialize(()=>{this.update(e,{type:U})}),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=>{O(t.stop)&&t.stop()});for(const t of r(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.initialized=!1,this}batch(t){if(!this.initialized&&this.options.deferEvents);else if(!this.initialized)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;for(const i of t){const{changed:t}=e,s=G(i),n=e.actions.map(t=>E(t,e));(e=this.machine.transition(e,s)).actions.unshift(...n),e.changed=e.changed||!!t,this.forward(s)}this.update(e,G(t[t.length-1]))})}sender(t){return this.send.bind(this,t)}nextState(t){const e=G(t);if(0===e.type.indexOf(J)&&!this.state.nextEvents.some(t=>0===t.indexOf(J)))throw e.data;return _t(this,()=>this.machine.transition(this.state,e,this.state.context))}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){let{delay:e}=t;if($(e)){if(!this.machine.options.delays||void 0===this.machine.options.delays[e])return;{const t=this.machine.options.delays[e];e="number"==typeof t?t:t(this.state.context,this.state.event)}}this.delayedEventsMap[t.id]=this.clock.setTimeout(()=>{t.to?this.sendTo(t.event,t.to):this.send(t.event)},e||0)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}exec(e,i,s,n){const o=H(e.type,n)||e.exec,r=O(o)?o:o?o.exec:e.exec;if(r)return r(i,s,{action:e,state:this.state});switch(e.type){case M:const n=e;if(n.delay)return void this.defer(n);n.to?this.sendTo(n.event,n.to):this.send(n.event);break;case R:this.cancel(e.sendId);break;case L:{const n=e.activity;if(!this.state.activities[n.type])break;if(n.type===t.Invoke){const t=this.machine.options.services?this.machine.options.services[n.src]:void 0,{id:e,data:o}=n,r="autoForward"in n?n.autoForward:!!n.forward;if(!t)return;const a=O(t)?t(i,s):t;w(a)?this.spawnPromise(Promise.resolve(a),e):O(a)?this.spawnCallback(a,e):j(a)?this.spawnObservable(a,e):k(a)&&this.spawnMachine(o?a.withContext(m(o,i,s)):a,{id:e,autoForward:r})}else this.spawnActivity(n);break}case D:this.stopChild(e.activity.id);break;case F:const o=e.expr?e.expr(i,s):void 0;e.label?this.logger(e.label,o):this.logger(o)}}stopChild(t){const e=this.children.get(t);e&&(this.children.delete(t),this.forwardTo.delete(t),O(e.stop)&&e.stop())}spawn(t,e,i){if(w(t))return this.spawnPromise(Promise.resolve(t),e);if(O(t))return this.spawnCallback(t,e);if(j(t))return this.spawnObservable(t,e);if(k(t))return this.spawnMachine(t,Object.assign({},i,{id:e}));throw new Error(`Unable to spawn entity "${e}" of type "${typeof t}".`)}spawnMachine(t,e={}){const i=new jt(t,Object.assign({},this.options,{parent:this,id:e.id||t.id})),s=Object.assign({},$t,e);s.sync&&i.onTransition(t=>{this.send(q,{state:t,id:i.id})}),i.onDone(t=>{this.send(t)}).start();const n=i;return this.children.set(i.id,n),s.autoForward&&this.forwardTo.add(i.id),n}spawnPromise(t,e){let i=!1;t.then(t=>{i||this.send(at(e,t))},t=>{if(!i){const i=ht(e,t);try{this.send(i)}catch(s){this.reportUnhandledExceptionOnInvocation(t,s,e),this.devTools&&this.devTools.send(i,this.state),this.machine.strict&&this.stop()}}});const s={id:e,send:()=>void 0,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=t=>{i||this.send(t)},n=new Set;let o;try{o=t(s,t=>{n.add(t)})}catch(t){this.send(ht(e,t))}if(w(o))return this.spawnPromise(o,e);const r={id:e,send:t=>n.forEach(e=>e(t)),subscribe:t=>(n.add(t),{unsubscribe:()=>{n.delete(t)}}),stop:()=>{i=!0,O(o)&&o()},toJSON:()=>({id:e})};return this.children.set(e,r),r}spawnObservable(t,e){const i=t.subscribe(t=>{this.send(t)},t=>{this.send(ht(e,t))},()=>{this.send(at(e))}),s={id:e,send:()=>void 0,subscribe:(e,i,s)=>t.subscribe(e,i,s),stop:()=>i.unsubscribe(),toJSON:()=>({id:e})};return this.children.set(e,s),s}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:()=>void 0,subscribe:()=>({unsubscribe:()=>void 0}),stop:e||void 0,toJSON:()=>({id:t})})}reportUnhandledExceptionOnInvocation(t,e,i){}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({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.devTools.init(this.state)}}toJSON(){return{id:this.id}}}jt.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),jt.interpret=Pt;const kt=(t="null")=>({id:t,send:()=>void 0,subscribe:()=>({unsubscribe:()=>{}}),toJSON:()=>({id:t})}),Tt=t=>$(t)?Object.assign({},$t,{name:t}):Object.assign({},$t,{name:T()},t);function Vt(t,e){const i=Tt(e);return _t(void 0,e=>e?e.spawn(t,i.name,i):kt(i.name))}function Pt(t,e){return new jt(t,e)}function It(t,e,i){const s=I.from(t,t instanceof I?t.context:void 0);for(const[t,i]of e)if(s.matches(t))return i(s);return i(s)}const Lt={raise:Y,send:Z,sendParent:tt,log:function(t=((t,e)=>({context:t,event:e})),e){return{type:F,label:e,expr:t}},cancel:et,start:it,stop:st,assign:nt,after:ot,done:rt};export{Et as Machine,bt as StateNode,I as State,a as matchesState,V as mapState,Lt as actions,nt as assign,Z as send,tt as sendParent,Pt as interpret,jt as Interpreter,It as matchState,Vt as spawn,t as ActionTypes,e as SpecialTargets};