UNPKG

kingly

Version:

State machine library (Extended Hierarchical State Transducer)

3 lines (2 loc) 35.9 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.Kingly={})}(this,function(t){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function a(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&s(t,e)}function o(t){return(o=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function s(t,e){return(s=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(t,e,n){return(c=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}()?Reflect.construct:function(t,e,n){var r=[null];r.push.apply(r,e);var a=new(Function.bind.apply(t,r));return n&&s(a,n.prototype),a}).apply(null,arguments)}function u(t){var e="function"==typeof Map?new Map:void 0;return(u=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return c(t,arguments,o(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),s(r,t)})(t)}function f(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function l(t,e){return!e||"object"!=typeof e&&"function"!=typeof e?f(t):e}function d(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=[],r=!0,a=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(r=(o=s.next()).done)&&(n.push(o.value),!e||n.length!==e);r=!0);}catch(t){a=!0,i=t}finally{try{r||null==s.return||s.return()}finally{if(a)throw i}}return n}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}var h=".",p="--\x3e",v=":",m="H",g="history.",y="nok",b="init",T="auto",S="State",w=[],O=[],E=function(){return{outputs:O,updates:w}},j="shallow",k="deep",A="The machine received an event which does not have the proper format. Expecting an object whose unique key is the event name, and value is the event data.",C="CONTRACTS_EVAL",N="OUTPUTS_MSG",F="INPUT_MSG",M="WARN_MSG",_="MACHINE_CREATION_ERROR_MSG",x="ERROR_MSG",I="INTERNAL_INPUT_MSG",P="INTERNAL_OUTPUTS_MSG",R="DEBUG_MSG",D="INIT_INPUT_MSG";const L=[0],H="PRE_ORDER";function B(t){return void 0===t?void 0:JSON.parse(JSON.stringify(t))}function U(t,e){return Object.assign({},t,e)}function V(t,e,n){n.forEach((n,r)=>{const a=t.get(e),i=t.get(n),o=i&&i.path;t.set(n,U(i,{isAdded:!0,isVisited:!1,path:o||a.path.concat(r)}))})}function G(t,e){t.set(e,U(t.get(e),{isVisited:!0}))}function W(t,e){const{store:n,lenses:r,traverse:a}=t,{empty:i,add:o,takeAndRemoveOne:s,isEmpty:c}=n,{getChildren:u}=r,{visit:f,seed:l}=a,d=new Map,h="function"==typeof l?new(l()):B(l);let p="function"==typeof i?new(i()):B(i),v=h;for(o([e],p),d.set(e,{isAdded:!0,isVisited:!1,path:L});!c(p);){const t=s(p),e=u(d,t);o(e,p),V(d,t,e),v=f(v,d,t),G(d,t)}return d.clear(),v}function J(t,e,n){const{getChildren:r}=t;return W({store:{empty:[],takeAndRemoveOne:t=>t.shift(),isEmpty:t=>0===t.length,add:(t,e)=>e.push.apply(e,t)},lenses:{getChildren:(t,e)=>r(e)},traverse:e},n)}function K(t,e,n){const{getChildren:r}=t;return W({store:{empty:[],takeAndRemoveOne:t=>t.shift(),isEmpty:t=>0===t.length,add:(t,e)=>e.unshift(...t)},lenses:{getChildren:(t,e)=>r(e)},traverse:e},n)}function q(t,e,n){const{getChildren:r}=t,{seed:a,visit:i}=e,o=(t,e)=>e.get(t).isVisited||((t,e)=>0===r(t,e).length)(t,e);return W({store:{empty:[],takeAndRemoveOne:t=>t.shift(),isEmpty:t=>0===t.length,add:(t,e)=>e.unshift(...t)},lenses:{getChildren:(t,e)=>o(e,t)?[]:r(e,t).concat([e])},traverse:{seed:a,visit:(t,e,n)=>o(n,e)?i(t,e,n):t}},n)}const Y={isLeafLabel:function(t){return 0===Y.getChildren(t).length},getLabel:t=>{if("object"!=typeof t||Array.isArray(t)||1!==Object.keys(t).length)throw"getLabel > unexpected object tree value";return t},getChildren:t=>{if("object"!=typeof t||Array.isArray(t)||1!==Object.keys(t).length)throw"getChildren > unexpected value";{let e=Object.values(t)[0];return e&&"object"==typeof e&&!Array.isArray(e)?Object.keys(e).map(t=>({[t]:e[t]})):[]}},constructTree:(t,e)=>{const n=t&&Object.keys(t)&&Object.keys(t)[0];return 0===e.length?t:{[n]:Object.assign.apply(null,e)}}};function X(t,e){const n={root:e},{strategy:r,seed:a,visit:i}=t;return({BFS:J,PRE_ORDER:K,POST_ORDER:q}[r]||K)(Y,{seed:a,visit:function(t,e,n){const{path:r}=e.get(n);return JSON.stringify(r)===JSON.stringify(L)?t:i(t,e,n)}},n)}const z={getLabel:t=>Array.isArray(t)?t[0]:t,getChildren:t=>Array.isArray(t)?t[1]:[],constructTree:(t,e)=>e&&Array.isArray(e)&&e.length>0?[t,e]:t};var $=function(){},Q={log:$,warn:$,info:$,debug:$,error:$,trace:$,group:$,groupEnd:$},Z=$;function tt(t){return t&&"string"==typeof t||pt(t)}function et(t){return void 0===t||"string"==typeof t}function nt(t){return t&&"function"==typeof t}function rt(t){return["-",t,"-"].join("")}function at(t,e){return Array.apply(null,{length:e}).map(Number.call,Number).map(t)}function it(t){return t.to.startsWith(g)}function ot(t){return t.event===b}function st(t){return function(e){return e.from===t}}function ct(t){return function(e){return function(t,e){return e.substring(g.length)===t}(t,e.to)}}function ut(t,e,n){var r=t||"";return e&&n?"".concat(r," [").concat(e.name,"] / ").concat(n.name):e?"".concat(r," [").concat(e.name,"]}"):n?"".concat(r," / ").concat(n.name):"".concat(r)}function ft(t){var e=t.from,n=t.to;return"".concat(e,".").concat(n.substring(g.length),".").concat(m)}function lt(t){var e=t.from,n=t.event,r=t.guards;return r?r.map(function(t){var r=t.predicate,a=t.to,i=t.action;return{from:e,event:n,predicate:r,to:a,action:i}}):[t]}function dt(t){if(0===Object.keys(t).length)throw"computeHistoryMaps : passed empty control states parameter?";var e=Y.getLabel,n=X({strategy:H,seed:{stateList:[],stateAncestors:{}},visit:function(t,n,r){var a=e(r),i=Object.keys(a)[0];t.stateList=t.stateList.concat(i);var o=n.get(r).path;n.set(JSON.stringify(o),i);var s=o.slice(0,-1);if(1===s.length)n.set(JSON.stringify(s),y);else{var c=n.get(JSON.stringify(s));t.stateAncestors[i]=[c];var u=o.reduce(function(t,e){var r=t.path.slice(0,-1);if(t.path=r,r.length>1){var a=n.get(JSON.stringify(r));t.ancestors=t.ancestors.concat(a)}return t},{ancestors:[],path:o}).ancestors;t.stateAncestors[i]=u}return t}},t);return{stateList:n.stateList,stateAncestors:n.stateAncestors}}function ht(t,e,n){return n.reduce(function(e,n,r){var a=n.from,i=n.event,o=n.to,s=n.gen,c=n.action,u=n.guards;return u||(u=s?[{to:o,action:c,gen:s,predicate:void 0}]:[{to:o,action:c,predicate:void 0}]),u.reduce(function(e,n,o){var s=n.to,c=n.action,u=n.gen,f=n.predicate;return t(e,u?{from:a,event:i,to:s,action:c,predicate:f,gen:u}:{from:a,event:i,to:s,action:c,predicate:f},o,r)},e)},e)}function pt(t){return"object"===e(t)&&(k in t||j in t)}function vt(t){return t[function(t){return t[k]?k:j}(t)]}function mt(t){var e,n=function(){return t.reduce(function(t,e){return t[e]="",t},{})};return a(e={},k,n()),a(e,j,n()),e}function gt(t){return t.find(function(t){return t.from===y&&t.event===b})}function yt(t,e){var n=t.name||"",r=t.apply(null,e);return!0===r?void 0:function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(t){return Object.getOwnPropertyDescriptor(n,t).enumerable}))),r.forEach(function(e){a(t,e,n[e])})}return t}({},r,{when:"Checking contract",message:[r.message,"failed contract ".concat(n)].join("\n"),info:r.info})}function bt(t){var n;return t&&"object"===e(t)?Object.keys(t).length>1?(n=new Error(A)).info={event:t,cause:"Event objects must have only one key which is the event name!"}:n=!0:(n=new Error(A)).info={event:t,cause:"not an object!"},n}function Tt(t){var e=Object.keys(t)[0];return{eventName:e,eventData:t[e]}}var St=function(t){function e(t,r,a){var i;n(this,e),(i=l(this,o(e).call(this,t&&t.message||""))).name="KinglyError",i.stack=t&&t.stack||i.stack,i.errors=t;var s=t||{},c=s.when,u=s.location,f=s.info,d=s.message,h=["At ".concat(u,": ").concat(c," => ").concat(d),f?"See extra info in console":""].join("\n");return r&&r.error(h),f&&r&&r.info(f),i}return i(e,u(Error)),e}();function wt(t){var e=t.from,n=t.event,r=t.guards,a=t.to,i=t.action;return typeof r==="".concat(void 0)&&a&&tt(e)&&et(n)&&tt(a)&&nt(i)}function Ot(t){var e=t.to,n=t.predicate,r=t.action;return e&&tt(e)&&"function"==typeof n&&nt(r)}function Et(t){var e=t.from,n=t.event,r=t.guards,a=t.to;return r&&Array.isArray(r)&&r.length>0&&!a&&tt(e)&&et(n)&&r.every(Ot)}var jt={injected:function(t,e){return{statesType:(r=t.states,a=Y.getLabel,i=Y.isLeafLabel,X({strategy:H,seed:{},visit:function(t,e,n){var r=a(n),o=Object.keys(r)[0];return i(r)?(t[o]=!1,t):(t[o]=!0,t)}},r)),initTransition:gt(t.transitions),statesTransitionsMap:(n=t.transitions,n.reduce(function(t,e){var n=e.from,r=e.event;return pt(n)?t:(t[n]=t[n]||{},t[n][r]=e,t)},{})||{}),stateEventTransitionsMaps:function(t){return t.reduce(function(t,e){var n=e.from,r=e.event;return pt(n)?t:(t[n]=t[n]||{},t[n][r]=t[n][r]?t[n][r].concat(e):[e],t)},{})||{}}(t.transitions),eventTransitionsMaps:function(t){return t.reduce(function(t,e){var n=e.from,r=e.event;return pt(n)?t:(t[r]=t[r]||{},t[r][n]=t[r][n]?t[r][n].concat(e):[e],t)},{})||{}}(t.transitions),ancestorMap:function(t){var e=Y.getLabel,n=Y.getChildren;return X({strategy:H,seed:{},visit:function(t,r,a){var i=e(a),o=Object.keys(i)[0];return n(a).map(function(t){return Object.keys(e(t))[0]}).forEach(function(e){t[e]=t[e]||[],t[e]=t[e].concat(o)}),t}},t)}(t.states),statesPath:function(t){var e=Y.getLabel;return X({strategy:H,seed:{},visit:function(t,n,r){var a=n.get(r).path.join("."),i=e(r);return t[Object.keys(i)[0]]=a,t}},t)}(t.states),historyStatesMap:function(t){return ht(function(t,e,n,r){var a=e.from,i=(e.event,e.to);if(e.action,e.predicate,e.gen,pt(a)){var o=vt(a);t.set(o,(t.get(o)||[]).concat([e]))}else if(pt(i)){var s=vt(i);t.set(s,(t.get(s)||[]).concat([e]))}return t},new Map,t)||{}}(t.transitions),targetStatesMap:function(t){return ht(function(t,e,n,r){var a=e.to;return t.set(a,(t.get(a)||[]).concat([e])),t},new Map,t)||{}}(t.transitions)};var n,r,a,i},description:"FSM structure",contracts:[{name:"isValidFsmDef",shouldThrow:!1,predicate:function(t,n){var r=t.transitions,a=t.states,i=t.events,o=(t.initialExtendedState,r&&Array.isArray(r)),s=a&&"object"===e(a),c=i&&Array.isArray(i);return o?s?c?{isFulfilled:!0,blame:void 0}:{isFulfilled:!1,blame:{message:"The events property for a machine definition must be an array!",info:{events:i}}}:{isFulfilled:!1,blame:{message:"The states property for a machine definition must be an object!",info:{states:a}}}:{isFulfilled:!1,blame:{message:"The transitions property for a machine definition must be an array!",info:{transitions:r}}}}},{name:"isValidSettings",shouldThrow:!1,predicate:function(t){return{isFulfilled:!0,blame:void 0}}},{name:"isInitialControlStateDeclared",shouldThrow:!1,predicate:function(t,e,n){n.initTransition;var r=n.statesType,a=t.initialControlState,i=(t.transitions,Object.keys(r));return a?{isFulfilled:i.indexOf(a)>-1,blame:{message:"Configured initial control state must be a declared state. Cf. log",info:{initialControlState:a,declaredStates:i}}}:{isFulfilled:!0,blame:void 0}}},{name:"isInitialStateOriginState",shouldThrow:!1,predicate:function(t,e,n){var r=n.targetStatesMap;return Array.from(r.keys()).indexOf(y)>-1?{isFulfilled:!1,blame:{message:"Found at least one transition with the initial state as target state! CF. log",info:{targetStates:Array.from(r.keys()),transitions:t.transitions}}}:{isFulfilled:!0,blame:void 0}}},{name:"eventsAreStrings",shouldThrow:!1,predicate:function(t,e){return{isFulfilled:t.events.every(function(t){return"string"==typeof t}),blame:{message:"Events must be an array of strings!",info:{events:t.events}}}}},{name:"haveTransitionsValidTypes",shouldThrow:!1,predicate:function(t,e){var n=t.transitions,r=n.map(function(t,e){return!wt(t)&&!Et(t)&&{transition:t,index:e}}).filter(Boolean),a=Object.keys(r).length;return{isFulfilled:0===a,blame:{message:"Found ".concat(a," transitions with invalid format! Check logs for more details."),info:{wrongTransitions:r,transitions:n}}}}},{name:"noDuplicatedStates",shouldThrow:!1,predicate:function(t,e){var n=Y.getLabel,r=X({strategy:H,seed:{duplicatedStates:[],statesHashMap:{}},visit:function(t,e,r){var a=t.duplicatedStates,i=t.statesHashMap,o=n(r),s=Object.keys(o)[0];return s in i?{duplicatedStates:a.concat(s),statesHashMap:i}:{duplicatedStates:a,statesHashMap:(i[s]="",i)}}},t.states).duplicatedStates;return{isFulfilled:0===r.length,blame:{message:"State names must be unique! Found duplicated state names. Cf. log",info:{duplicatedStates:r}}}}},{name:"noReservedStates",shouldThrow:!1,predicate:function(t,e,n){var r=n.statesType;return{isFulfilled:-1===Object.keys(r).indexOf(y),blame:{message:"You cannot use a reserved control state name for any of the configured control states for the machine! Cf. log",info:{reservedStates:[y],statesType:r}}}}},{name:"atLeastOneState",shouldThrow:!1,predicate:function(t,e,n){var r=n.statesType;return{isFulfilled:Object.keys(r).length>0,blame:{message:"Machine configuration must define at least one control state! Cf. log",info:{statesType:r}}}}},{name:"areEventsDeclared",shouldThrow:!1,predicate:function(t,e,n){var r=n.eventTransitionsMaps,a=Object.keys(r),i=t.events,o=i.map(function(t){return-1===a.indexOf(t)&&t}).filter(Boolean),s=a.map(function(t){return-1===i.indexOf(t)&&t}).filter(Boolean).filter(function(t){return t!==b&&"undefined"!==t});return{isFulfilled:0===o.length&&0===s.length,blame:{message:"All declared events must be used in transitions. All events used in transition must be declared! Cf. log",info:{eventsDeclaredButNotTriggeringTransitions:o,eventsNotDeclaredButTriggeringTransitions:s}}}}},{name:"areStatesDeclared",shouldThrow:!1,predicate:function(t,n,r){var a=r.stateEventTransitionsMaps,i=r.targetStatesMap,o=r.statesType,s=r.ancestorMap,c=Object.keys(a),u=Array.from(i.keys()).filter(function(t){return"object"!==e(t)}),f=Object.keys([c,u].reduce(function(t,e){return e.forEach(function(e){return t[e]=!0}),t},{})),l=Object.keys(o),d=l.map(function(t){return-1===f.indexOf(t)&&t}).filter(Boolean).filter(function(t){return!s[t]||0===s[t].length}),h=f.map(function(t){return t!==y&&-1===l.indexOf(t)&&t}).filter(Boolean);return{isFulfilled:0===d.length&&0===h.length,blame:{message:"All declared states must be used in transitions. All states used in transition must be declared! Cf. log",info:{statesDeclaredButNotTriggeringTransitions:d,statesNotDeclaredButTriggeringTransitions:h}}}}},{name:"validInitialConfig",shouldThrow:!1,predicate:function(t,e,n){var r=n.initTransition,a=t.initialControlState;return r&&a?{isFulfilled:!1,blame:{message:"Invalid machine configuration : defining an initial control state and an initial transition at the same time may lead to ambiguity and is forbidden!",info:{initialControlState:a,initTransition:r}}}:r||a?{isFulfilled:!0,blame:void 0}:{isFulfilled:!1,blame:{message:"Invalid machine configuration : you must define EITHER an initial control state OR an initial transition! Else in which state is the machine supposed to start?",info:{initialControlState:a,initTransition:r}}}}},{name:"validInitialTransition",shouldThrow:!1,predicate:function(t,e,n){var r=n.initTransition,a=t.initialControlState,i=t.transitions.reduce(function(t,e){return e.from===y&&t.push(e),t},[]);return{isFulfilled:a&&!r||!a&&r&&1===i.length&&r.event===b&&(wt(r)||Et(r)),blame:{message:"Invalid configuration for initial transition! Cf. log",info:{initTransition:r,initTransitions:i,initialControlState:a}}}}},{name:"initEventOnlyInCompoundStates",shouldThrow:!1,predicate:function(t,e,n){var r=n.statesTransitionsMap,i=n.statesType,o=(n.statesPath,Object.keys(i).filter(function(t){return!i[t]}).map(function(t){return a({},t,r[t]&&r[t][b])}).filter(function(t){return Object.values(t)[0]}));return{isFulfilled:0===o.length,blame:{message:"Found at least one atomic state with an entry transition! That is forbidden! Cf. log",info:{initTransitions:o}}}}},{name:"validInitialTransitionForCompoundState",shouldThrow:!1,predicate:function(t,e,n){var r=n.statesTransitionsMap,i=n.statesType,o=n.statesPath,s=Object.keys(i).filter(function(t){return i[t]}),c=s.map(function(t){return r[t]&&r[t][b]}),u=c.every(Boolean);if(!u)return{isFulfilled:!1,blame:{message:"Found at least one compound state without an entry transition! Cf. log",info:{hasEntryTransitions:s.map(function(t){return a({},t,!(!r[t]||!r[t][b]))})}}};var f=u&&c.every(function(t){var e=t.guards,n=t.to;return e?e.map(function(t){return t.to}).every(function(t){return"string"==typeof t}):"string"==typeof n});return f?f&&c.every(function(t){var e=t.from,n=t.guards,r=t.to;return n?n.map(function(t){return t.to}).every(function(t){return e!==t&&o[t]&&o[t].startsWith(o[e])}):e!==r&&o[r]&&o[r].startsWith(o[e])})?{isFulfilled:!0,blame:void 0}:{isFulfilled:!1,blame:{message:"Found at least one compound state with an invalid entry transition! Entry transitions for compound states must have a target state which is strictly below the compound state in the state hierarchy! ",info:{states:t.states,statesPath:o,entryTransitions:c}}}:{isFulfilled:!1,blame:{message:"Found at least one compound state with an invalid entry transition! Entry transitions for compound states must have the associated target control states which are not a history pseudo-state. Cf. log",info:{entryTransitions:c}}}}},{name:"validEventLessTransitions",shouldThrow:!1,predicate:function(t,e,n){var r=n.statesTransitionsMap,i=n.statesType,o=(n.statesPath,Object.keys(i).map(function(t){return a({},t,r[t]&&"".concat(void 0)in r[t]&&1!==Object.keys(r[t]).length)}).filter(function(t){return void 0!==Object.values(t)[0]&&Object.values(t)[0]}));return{isFulfilled:0===o.length,blame:{message:"Found at least one control state without both an eventless transition and a competing transition! Cf. log",info:{failingOriginControlStates:o}}}}},{name:"isValidSelfTransition",shouldThrow:!1,predicate:function(t,e,n){var r=n.targetStatesMap,a=n.statesType,i=Array.from(r.keys()).map(function(t){return r.get(t).map(function(e){var n=e.from,r=e.event;if(t in a&&!a[t]&&n&&n===t&&!r)return{state:t,flatTransition:e}}).filter(Boolean)}).filter(function(t){return t.length>0});return{isFulfilled:0===i.length,blame:{message:"Found at least one eventless self-transition involving an atomic state! This is forbidden to avoid infinity loop! Cf. log",info:{wrongSelfTransitions:i}}}}},{name:"allStateTransitionsOnOneSingleRow",shouldThrow:!1,predicate:function(t,e,n){var r=n.stateEventTransitionsMaps,a=Object.keys(r).reduce(function(t,e){var n=Object.keys(r[e]).filter(function(t){return r[e][t].length>1});return n.length>0&&(t[e]=n),t},{});return{isFulfilled:0===Object.keys(a).length,blame:{message:"Found at least one control state and one event for which the associated transition are not condensated under a unique row! Cf. log",info:{statesTransitionsInfo:a}}}}},{name:"noConflictingTransitionsWithAncestorState",shouldThrow:!1,predicate:function(t,e,n){n.stateEventTransitionsMaps;var r=n.eventTransitionsMaps,i=n.ancestorMap,o=Object.keys(r).filter(function(t){return t!==b&&void 0!==t}).reduce(function(t,e){var n=Object.keys(r[e]),o=n.filter(function(t){return t!==y}).map(function(t){return i[t]&&a({},t,i[t].find(function(t){return n.indexOf(t)>-1}))}).filter(function(t){return t&&Object.values(t).filter(Boolean).length>0});return o.length>0&&(t[e]=o),t},{});return{isFulfilled:0===Object.keys(o).length,blame:{message:"Found two conflicting transitions! A -ev-> X, and B -ev-> Y leads to ambiguity if A < B or B < A. Cf. log",info:{eventTransitionsInfo:o}}}}},{name:"isHistoryStatesExisting",shouldThrow:!1,predicate:function(t,e,n){var r=n.historyStatesMap,a=n.statesType,i=Array.from(r.entries()).map(function(t){var e=d(t,2),n=e[0],r=e[1];return!(n in a)&&{historyState:n,flatTransitions:r}}).filter(Boolean),o=Object.keys(i).length;return{isFulfilled:0===o,blame:{message:"Found ".concat(o," history pseudo state referring to a control state that is not declared! Check the states property of the state machine definition."),info:{invalidTransitions:i,states:t.states}}}}},{name:"isHistoryStatesTargetStates",shouldThrow:!1,predicate:function(t,e,n){!function(t){if(null==t)throw new TypeError("Cannot destructure undefined")}(n);var r=t.transitions.reduce(function(t,e){return pt(e.from)?t.concat(e):t},[]);return{isFulfilled:0===Object.keys(r).length,blame:{message:"Found a history pseudo state configured as the origin control state for a transition. History pseudo states should only be target control states. Cf. log",info:{wrongHistoryStates:r}}}}},{name:"isHistoryStatesCompoundStates",shouldThrow:!1,predicate:function(t,e,n){var r=n.stateEventTransitionsMaps,a=n.statesType,i=Object.keys(r).map(function(t){return t===y?[]:Object.keys(r[t]).reduce(function(e,n){var i=r[t][n][0],o=i.guards,s=i.to;return o?o.reduce(function(t,e){var n=e.to;return pt(n)&&!a[vt(n)]?t.concat(i):t},e):pt(s)&&!a[vt(s)]?e.concat(i):e},[])}).reduce(function(t,e){return t.concat(e)},[]);return{isFulfilled:0===Object.keys(i).length,blame:{message:"Found a history pseudo state connected to an atomic state! History pseudo states only refer to compound states. Cf. log",info:{wrongHistoryStates:i,states:t.states}}}}}]};var kt=function(t,e,n){return function(t,e){var n=e&&e.debug&&e.debug.console||Q,r=e&&e.debug&&e.debug.trace||$,i=t.description;return function(){for(var e=arguments.length,o=new Array(e),s=0;s<e;s++)o[s]=arguments[s];var c=[],u=t.injected.apply(null,o),f={isFulfilled:t.contracts.reduce(function(t,e){var r=e.name,a=e.predicate,s=e.shouldThrow,f=o.concat(u),l=a.apply(null,f),d=l.isFulfilled,h=l.blame,p="".concat(i," FAILS ").concat(r,"!"),v=h||{},m=v.message,g=v.info;if(d)return t;if(c.push({name:r,message:m,info:g}),n.error(p),n.error([r,m].join(": ")),n.debug("Supporting error data:",g),s)throw new Error([p,"check console for information!"].join("\n"));return!1},!0),failingContracts:c};return r(a({},C,f)),f}}(n,e)(t,e)};function At(){return!0}function Ct(t){var n="State",r={},a={};function i(){}return t={nok:t},i.prototype={current_state_name:y},r[y]=new i,r[S]=new i,function t(i,o){var s;(s=i,Object.keys(s)).forEach(function(s){var c=i[s];if(r[s]=new o,r[s].name=s,r[s].parent_name=/^[\s\r\n]*function[\s\r\n]*([^\(\s\r\n]*?)[\s\r\n]*\([^\)\s\r\n]*\)[\s\r\n]*\{((?:[^}]*\}?)+)\}\s*$/.exec(o.toString())[1],r[s].root_name=n,"object"===e(c)){a[s]=!0;var u=function(){};u.displayName=s,u.prototype=r[s],t(c,u)}})}(t,i),{hashStates:r,isGroupState:a}}function Nt(t,e){var n=t.states,r=t.initialExtendedState,i=t.updateState,o=e||{},s=o.debug,c=o.devTool,u=s&&s.checkContracts||void 0,f=s&&s.console||Q,l=c&&c.tracer||Z,d=function(t,e){return function(n){throw new St(n,t,e)}}(f,l);if(u){var h=function(t,e,n){var r=t.fsmDef,a=t.settings,i=n.throwKinglyError,o=n.tracer;if(e){var s=kt(r,a,e).failingContracts;try{s.length>0&&i({when:"Attempting to create a Kingly machine",location:"createStateMachine",info:{fsmDef:r,settings:a,failingContracts:s},message:"I found that one or more Kingly contracts are violated!"})}catch(t){return o({type:_,trace:{info:t.errors,message:t.message,machineState:{cs:void 0,es:void 0,hs:void 0}}}),t}}}({fsmDef:t,settings:e},u,{throwKinglyError:d,tracer:l});if(h instanceof Error)return h}var p=function(t,e){var n=e.throwKinglyError;return e.tracer,function(e,r){var a=t.name||"";try{return t(e,r)}catch(t){n({when:"Executing updateState function ".concat(a),location:"createStateMachine > wrappedUpdateState",info:{extendedState:e,updates:r},message:t.message,stack:t.stack})}}}(i,{throwKinglyError:d,tracer:l}),v=function(t){var e=t.initialControlState,n=t.transitions,r=gt(n);return e?n.concat([{from:y,event:b,to:e,action:E}]):r?n:void 0}(t),m=Ct(n),g={},S={},w=m.isGroupState,A=m.hashStates;v.forEach(function(t){var n=t.from,r=t.to,i=t.action,o=t.event,c=t.guards;c||(c=[{predicate:void 0,to:r,action:i}]),o===b&&(g[n]=!0);var u=A[n];o||(o=T,S[n]=!0),w[n]&&g[n]&&(S[n]=!0),u[o]=c.reduce(function(t,r,i){var c=r.action||E,u=c.name||c.displayName||"",h=function(t,e){var r=function(r,h,v){n=v||n;var m,b=t.predicate||At,T=b.name||b.displayName||"<anonymous>",S=t.to,w=function(e,r,a){try{return b(e,r,a)}catch(s){d({when:"Executing predicate function ".concat(T),location:"createStateMachine > event handler > condition_checking_fn > shouldTransitionBeTaken",info:{extendedState:e,event:o,event_data:r,settings:a,guard:t,from:n,to:S,index:i},message:["Error occurred while processing event ".concat(o," with target state ").concat(S),s.message].join("\n"),stack:s.stack})}}(r,h,e);if("boolean"!=typeof w&&d({when:"Executing predicate function ".concat(T),location:"createStateMachine > event handler > condition_checking_fn > throwIfInvalidGuardResult",info:{event:o,guard:t,from:n,to:S,index:i,shouldTransitionBeTaken:w},message:"Guard index ".concat(i," with name ").concat(T," did not return a boolean!")}),w){f.info("IN STATE ",rt(n)),t.predicate?(l({type:R,trace:{message:"The guard ".concat(T," is fulfilled"),info:{eventData:h,from:n,action:u,to:S},machineState:{cs:v,es:r,hs:B}}}),f.info("CASE: guard ".concat(b.name," for transition is fulfilled"))):(l({type:R,trace:{message:"Evaluating transition with no guards",info:{eventData:h,from:n,action:u,to:S},machineState:{cs:v,es:U,hs:B}}}),f.info("CASE: unguarded transition")),f.info("THEN: we execute the action "+u);var O=function(e,r,a){try{return c(e,r,a)}catch(r){d({when:"Executing action factory ".concat(u),location:"createStateMachine > event handler > condition_checking_fn",info:{extendedState:e,event:o,event_data:h,settings:a,guard:t,from:n,to:S,index:i,action:c},message:r.message,stack:r.stack})}}(r,h,e);(m=O)&&"updates"in m&&"outputs"in m&&Array.isArray(m.outputs)||d({when:"Executing action factory ".concat(u),location:"createStateMachine > event handler > condition_checking_fn",info:{extendedState:U,event:o,event_data:h,settings:e,guard:t,from:n,to:S,index:i,action:c,actionResult:O},message:"Action factory returned a value that does not have the expected shape!"});var E=O.updates,C=O.outputs;return function(t,e,n){B=function(t,e,n){var r,i=(a(r={},k,Object.assign({},t[k])),a(r,j,Object.assign({},t[j])),r);return n===y?i:((e[n]||[]).reduce(function(t,e){return i[k][e]=n,i[j][e]=t,e},n),i)}(B,H,n[t].name),f.info("LEAVE STATE",rt(t))}(n,0,A),U=p(r,E),function(t,e,n){var r;if(pt(t)){var a=t[k]?k:t[j]?j:void 0,i=t[a];if(!g[i]){var o="Configured a history state unrelated to a compound state! The behaviour of the machine is thus unspecified. Please review your machine configuration";s&&f&&f.error(o),d({message:o})}r=B[a][i]||i}else t?r=n[t].name:d({message:"enter_state : unknown case! Not a state name, and not a history state to enter!"});V=r,l({type:R,trace:{message:pt(t)?"Entering history state for ".concat(t[t.deep?k:t.shallow?j:void 0]):"Entering state ".concat(t),machineState:{cs:V,es:U,hs:B}}}),s&&f.info("AND TRANSITION TO STATE",rt(r))}(S,0,A),f.info("ENTER NEXT STATE: ",rt(V)),f.info("with extended state: ",U),{stop:!0,outputs:C}}return l({type:R,trace:{message:t.predicate?"The guard ".concat(T," is not fulfilled!"):"Evaluated and skipped transition",info:{eventData:h,settings:e,guard:t,from:n,to:S,index:i,action:u},machineState:{cs:v,es:U,hs:B}}}),{stop:!1,outputs:null}};return r.displayName=n+"",r}(r,e);return function(e,n,r){var a=t(e,n,r);return a.stop?a:h(e,n,r)}},function(){return{stop:!1,outputs:null}})});var C=dt(n),L=C.stateList,H=C.stateAncestors,B=mt(L),U=r,V=y;try{J()}catch(h){return l({type:_,trace:{message:h.message,info:{fsmDef:t,settings:e,error:h},machineState:{cs:y,es:U,hs:B}}}),f&&f.error("An error occurred when starting the machine",h),h}var G={withProtectedState:function(t){try{var e=Tt(t),n=e.eventName,r=e.eventData;l({type:F,trace:{info:{eventName:n,eventData:r},machineState:{cs:V,es:U,hs:B}}});var a=W(t,!1);return s&&f.info("OUTPUTS:",a),l({type:N,trace:{outputs:a,machineState:{cs:V,es:U,hs:B}}}),a}catch(t){if(t instanceof St)return l({type:x,trace:{error:t,message:"An error ocurred while running an input through the machine!",machineState:{cs:V,es:U,hs:B}}}),t;throw l({type:x,trace:{error:t,message:"An unknown error ocurred while running an input through the machine!",machineState:{cs:V,es:U,hs:B}}}),f.error("withProtectedState > unexpected error!",t),t}},withPureInterface:function(t,e){if(void 0===e);else if(null===e)V=y,U=r,B=mt(L),J();else{var n=e.cs,a=e.hs,i=e.es;U=i,B=a,V=n}return{outputs:G.withProtectedState(t),fsmState:{cs:V,hs:B,es:U}}}};return G;function W(t,e){var n=yt(bt,[t]);u&&n&&d(n);var r=Tt(t),i=r.eventName,o=r.eventData;if(f.group("send event "+i||""),f.log(t),!e&&i===b&&V!==y)return l({type:M,trace:{info:{eventName:i,eventData:o},message:"The external event INIT_EVENT can only be sent when starting the machine!",machineState:{cs:V,es:U,hs:B}}}),f.warn("The external event INIT_EVENT can only be sent when starting the machine!"),f.groupEnd(),null;var c=function(t,e,n,r){var i=V,o=t[i][e];if(!o)return f.warn("There is no transition associated to the event |".concat(e,"| in state |").concat(V,"|!")),l({type:M,trace:{info:{received:a({},e,n)},message:"There is no transition associated to the event |".concat(e,"| in state |").concat(V,"|!"),machineState:{cs:V,es:r,hs:B}}}),null;f.log("found event handler!"),f.info("WHEN EVENT ",e,n);var c=o(r,n,i),u=c.stop,d=c.outputs,h=V;s&&!u&&f.warn("No guards have been fulfilled! We recommend to configure guards explicitly to cover the full state space!");var p=(y=d)===O?O:Array.isArray(y)?y:[y];if(!S[h])return p;if(h!==i){var v=g[h]?b:T;l({type:I,trace:{info:{eventName:v,eventData:n},event:a({},v,n),machineState:{cs:V,es:r,hs:B}}});var m=W(a({},v,n),!0);return l({type:P,trace:{outputs:m,machineState:{cs:V,es:r,hs:B}}}),[].concat(p).concat(m)}f.error("Eventless transitions (event |".concat(e,"| in state |").concat(V,"|) cannot return to the same control state!! This is forbidden to avoid possible infinite loops.")),l({type:x,trace:{info:{received:a({},e,n)},message:"Eventless transitions (event |".concat(e,"| in state |").concat(V,"|) cannot return to the same control state!! This is forbidden to avoid possible infinite loops."),machineState:{cs:V,es:r,hs:B}}});var y}(m.hashStates,i,o,U);return f.groupEnd(),c}function J(){return l({type:D,trace:{info:{eventName:b,eventData:r},event:a({},b,r),machineState:{cs:V,es:U,hs:B}}}),W(a({},b,r),!0)}}function Ft(t,e){return e?'state "'.concat(e,'" as ').concat(t," <<NoContent>>"):'state "'.concat((n=t,n.replace(/_/g," ")),'" as ').concat(t," <<NoContent>>");var n}t.createStateMachine=function(t,e){var n=Nt(t,e);return n instanceof Error?n:n.withProtectedState},t.createPureStateMachine=function(t,e){var n=Nt(t,e);return n instanceof Error?n:n.withPureInterface},t.makeWebComponentFromFsm=function(t){var e=t.name,a=t.eventHandler,s=t.fsm,c=t.commandHandlers,d=t.effectHandlers,h=t.options,p=function(t){function p(){var t;if(n(this,p),e.split("-").length<=1)throw"makeWebComponentFromFsm : web component's name MUST include a dash! Please review the name property passed as parameter to the function!";var r=f(t=l(this,o(p).call(this)));t.eventSubject=a,t.options=Object.assign({},h);var i=t.options.NO_ACTION||null;return t.eventSubject.subscribe({next:function(e){var n=s(e);if(n instanceof Error)console&&console.log(n);else{if(n===i)return;n.forEach(function(e){if(e!==i){var n=e.command,a=e.params;c[n](t.eventSubject.next,a,d,r)}})}}}),t}var v,m,g;return i(p,u(HTMLElement)),v=p,g=[{key:"observedAttributes",get:function(){return[]}}],(m=[{key:"connectedCallback",value:function(){this.options.initialEvent&&this.eventSubject.next(this.options.initialEvent)}},{key:"disconnectedCallback",value:function(){this.options.terminalEvent&&this.eventSubject.next(this.options.terminalEvent),this.eventSubject.complete()}},{key:"attributeChangedCallback",value:function(t,e,n){}}])&&r(v.prototype,m),g&&r(v,g),p}();return customElements.define(e,p)},t.historyState=function(t,e){return a({},t,e)},t.ACTION_IDENTITY=E,t.INIT_EVENT=b,t.INIT_STATE=y,t.SHALLOW=j,t.DEEP=k,t.NO_STATE_UPDATE=w,t.NO_OUTPUT=O,t.computeHistoryMaps=dt,t.initHistoryDataStructure=mt,t.fsmContracts=jt,t.toPlantUml=function(t,e){var n=t.states,r=t.transitions,i=Y.getChildren,o=Y.getLabel,s=function(t){return t.join(h)},c=q(Y,{seed:function(){return Map},visit:function(t,e,n){var a=e.get(n).path,c=o(n),u=function(t,e,n){return["".concat(Ft(t,"")," {"),e.join("\n"),function(t,e){var n=e.reduce(function(e,n){var r=lt(n);return r.filter(it).filter(ct(t)).reduce(function(t,e){return t[ft(e)]=void 0,t},e)},{});return Object.keys(n).map(function(t){return"".concat(Ft(t,m))}).join("\n")}(t,n),function(t,e){return e.reduce(function(e,n){var r=lt(n);return r.filter(ot).filter(st(t)).reduce(function(t,e){e.from;var n=e.to,r=e.predicate,a=e.action;return t.push("[*] ".concat(p," ").concat(n," ").concat(v," ").concat(ut("",r,a))),t},e)},[]).join("\n")}(t,n),"}",function(t,e){var n=function(t,e){return e.map(function(e){var n=lt(e);return n.filter(st(t)).filter(it).map(function(t){var e=t.from,n=t.event,r=t.predicate,a=t.to,i=t.action;return[e,p,ft({from:e,to:a}),v,ut(n,r,i)].join(" ")}).join("\n")}).filter(Boolean).join("\n")}(t,e),r=function(t,e){return t===y?"":e.map(function(e){var n=lt(e);return n.filter(st(t)).filter(function(t){return!ot(t)}).filter(function(t){return!it(t)}).map(function(t){var e=t.from,n=t.event,r=t.predicate,a=t.to,i=t.action;return[e,p,a,v,ut(n,r,i)].join(" ")}).join("\n")}).filter(Boolean).join("\n")}(t,e);return[n,r].filter(Boolean).join("\n")}(t,n)].filter(function(t){return"\n"!==t&&""!==t}).join("\n")}(Object.keys(c)[0],at(function(e){return t.get(s(a.concat(e)))},function(t,e){return i(t,e).length}(n,e)),r);return t.set(s(a),u),t}},a({},y,n)),u=c.get("0");return c.clear(),u},t.toDagreVisualizerFormat=function(t){var e=t.states,n=t.transitions,r=Y.getLabel,i=Y.getChildren,o=z.constructTree,s=function(t){return t.join(h)},c=q(Y,{seed:function(){return Map},visit:function(t,e,n){var a=e.get(n).path,c=r(n),u=Object.keys(c)[0],f=at(function(e){return t.get(s(a.concat(e)))},function(t,e){return i(t,e).length}(n,e));return t.set(s(a),o(u,f)),t}},a({},y,e)).get("0"),u=n.map(function(t){var e=t.from,n=t.to,r=t.event,a=t.guards,i=t.action;return a?{from:e,event:r,guards:a.map(function(t){var e=t.predicate,n=t.to,r=t.action;return{predicate:e.name,to:n,action:r.name}})}:{from:e,to:n,event:r,action:i.name||"no action name?"}});return JSON.stringify({states:c,transitions:u})},Object.defineProperty(t,"__esModule",{value:!0})}); //# sourceMappingURL=kingly.umd.min.js.map