-
Notifications
You must be signed in to change notification settings - Fork 10
/
SCxml.ugly.js
6 lines (5 loc) · 52.6 KB
/
SCxml.ugly.js
1
2
3
4
5
6
// JSSCxml version 0.9.1 (without Debug)
// Copyright David Junger & JSSCxml contributors © 2012-2015
// http://jsscxml.org/
function XHR(target,caller,callback,postData,onerror){this.target=target;this.callback=callback;this.caller=caller;this.onerror=onerror;with(this.req=new XMLHttpRequest){open(postData?"POST":"GET",target,true);onreadystatechange=XHR.handler(this);overrideMimeType("application/scxml+xml");send(postData||null)}}XHR.handler=function(xhr){function f(){if(xhr.req.readyState<4)return;if(xhr.req.status==200)xhr.callback.call(xhr.caller,xhr);else if(xhr.onerror)xhr.onerror.call(xhr.caller,xhr);else throw"HTTP error "+xhr.req.status+" : "+xhr.req.statusText}return f};function Set(){this.items={};this.length=0;if(arguments.length)this.add.apply(this,arguments)}Set.prototype.add=function(){for(var i=0;i<arguments.length;i++){var s=arguments[i];if(s in this.items)continue;this.items[s]=true;this.length++}return this.length};Set.prototype.remove=function(){for(var i=0;i<arguments.length;i++){var s=arguments[i];if(!(s in this.items))continue;delete this.items[s];this.length--}return this.length};function CompiledPath(path){this.parent=path[0].parentNode;this.path=path;this.end=path[path.length-1];this.atomic=this.end.tagName!="parallel"}CompiledPath.prototype.toString=function(){return this.path.map(function(s){return s.getAttribute("id")}).join(" → ")+(this.atomic?"":" ⇉ ")};function CompiledTree(root,children){this.parallels={};if(!root.atomic)this.parallels[root.end.getAttribute("id")]=this;this.root=root;this.children=[]}CompiledTree.prototype.toString=function(){return this.root+(this.root.atomic?"":"("+this.children.join(" ∥ ")+")")};CompiledTree.prototype.appendChild=function(subTree){for(var id in subTree.parallels)this.parallels[id]=subTree.parallels[id];this.children.push(subTree)};CompiledTree.prototype.attach=function(subTree){var id;if(!((id=subTree.root.parent.getAttribute("id"))in this.parallels))return false;var p=this.parallels[id].children;for(var i=0,c;c=p[i];i++)if(c.root.path[0]==subTree.root.path[0]){for(id in c.parallels)delete this.parallels[id];break}for(id in subTree.parallels)this.parallels[id]=subTree.parallels[id];p[i]=subTree;return true};CompiledTree.prototype.inEntryOrder=function(){return this.root.path.concat(this.root.atomic?[]:this.children.map(function(c){return c.inEntryOrder()}).reduce(function(a,b){return a.concat(b)})).filter(function(c){return!c.CA})};CompiledTree.prototype.atoms=function(){return this.root.atomic?[this.root.end]:this.children.map(function(c){return c.atoms()}).reduce(function(a,b){return a.concat(b)})};CompiledTree.prototype.select=function(test){var enabled=[];var allChildrenEnabled=true;var enabledTargetedTransition=false;if(!this.root.atomic){var childSelection;for(var i=0;i<this.children.length;i++){childSelection=this.children[i].select(test);if(!childSelection.enabled.length){allChildrenEnabled=false;continue}enabled=enabled.concat(childSelection.enabled);enabledTargetedTransition|=childSelection.hasTargets}}else allChildrenEnabled=false;if(!allChildrenEnabled){var t;for(var p=this.root.path,i=p.length-1;i>=0;i--)if(t=test(p[i])){if(!t.targets)enabled.push(t);else{if(enabledTargetedTransition)break;enabled.push(t);enabledTargetedTransition=true}break}}return{hasTargets:enabledTargetedTransition,enabled:enabled}};function Delay(delay,startNow,sc,proc,e,target,element){this.executed=false;this.time=delay;this.event=e;this.target=target;this.proc=proc;this.sc=sc;this.element=element;if(startNow)this.start();else this.sc.timeouts.push(this)}function Timeout(args,startNow,sc){this.executed=false;this.time=args[1];this.f=args[0];this.args=[];this.sc=sc;for(var i=2;args[i];i++)this.args.push(args[i]);if(startNow)this.start();else this.sc.timeouts.push(this)}Delay.timesUp=function(t){t.timesUp()};Delay.prototype.start=Timeout.prototype.start=function(){if(!this.timer&&!this.executed){this.timer=setTimeout(Delay.timesUp,this.time,this);this.started=+new Date}};Delay.prototype.cancel=Timeout.prototype.cancel=function(){if(this.timer&&!this.executed){clearTimeout(this.timer);delete this.timer}};Delay.prototype.stop=Timeout.prototype.stop=function(){if(this.timer&&!this.executed&&this.sc.running){this.time-=new Date-this.started;if(this.time<15)return false;clearTimeout(this.timer);delete this.timer;this.sc.timeouts.push(this);return true}return false};Delay.prototype.timesUp=function(){this.executed=true;with(this)proc.send(event,target,element,sc)};Timeout.prototype.timesUp=function(){this.executed=true;try{if(typeof this.f=="function")sc.datamodel.call(f,this.args);else sc.datamodel.expr(f,f)}catch(err){}};function SCxml(source,htmlContext,data,interpretASAP){this.dom=null;this.interpretASAP=interpretASAP;this.autoPauseBefore=SCxml.NO_PAUSE;this.nextPauseBefore=SCxml.NO_PAUSE;this.internalQueue=[];this.externalQueue=[];this.configuration={};this.transitionsToTake=null;this.statesToEnter=null;this.invoked={};this.toInvoke=new Set;this.lastEvent=undefined;this.sid=SCxml.sessions.length;SCxml.sessions.push(this);this.html=htmlContext&&htmlContext instanceof Element?htmlContext:document.head.appendChild(document.createElement("scxml"));this.html.interpreter=this;this.delays={};this.timeouts=[];this.intervals=[];this.initIframe(data);this.running=false;this.stable=false;this.paused=false;this.readyState=SCxml.LOADING;if(SCxml.mutations)this.initObservers();this.name="session "+this.sid;if(source instanceof Document)setTimeout(function(sc,dom){sc.interpret(dom)},0,this,source);else if("File"in window&&source instanceof File){this.name=source.name;var f=new FileReader;f.sc=this;f.onload=SCxml.fileLoaded;f.onerror=SCxml.fileFailed;f.readAsText(source,"utf-8")}else if(/^\s*</.test(source)){var d=(new DOMParser).parseFromString(source,"application/xml");setTimeout(function(sc,dom){sc.interpret(dom)},0,this,d)}else{this.name=source.match(/[^\/]+\.(?:sc)?xml/)[0];new XHR(source,this,this.xhrResponse,null,this.xhrFailed)}}SCxml.sessions=[null];function getId(element){return element.getAttribute("id")}SCxml.parseSCXMLTags=function(){var tags=document.getElementsByTagName("scxml");for(var i=0;i<tags.length;i++)tags[i].interpreter=new SCxml(tags[i].getAttribute("src"),tags[i],null,true)};SCxml.fileLoaded=function(e){var sc=this.sc;delete this.sc;var d=(new DOMParser).parseFromString(this.result,"application/xml");sc.interpret(d)};SCxml.fileFailed=function(e){delete this.sc};SCxml.prototype={timeout:function(args){return new Timeout(args,!this.paused,this)},interval:function(args){return new Interval(args,!this.paused,this)},clean:function(){if(this.readyState==SCxml.RUNNING)this.terminate();delete this.html.interpreter;if(this.html&&this.html.tagName=="scxml")this.html.parentNode.removeChild(this.html);delete this.html;delete this.datamodel;delete this.JSSCID;document.body.removeChild(this._iframe_);delete this._iframe_;SCxml.sessions[this.sid]=null;delete this.invoked},terminate:function(){if(this.readyState<SCxml.RUNNNIG)return;var s=this.dom.createNodeIterator(this.dom.documentElement,NodeFilter.SHOW_ELEMENT,SCxml.activeStateFilter);var rev=[],v;while(v=s.nextNode())rev.push(v);rev.reverse();if(this.readyState<SCxml.FINISHED)this.sendNoMore=true;this.html.dispatchEvent(new CustomEvent("exit",{detail:{list:rev.filter(this.exitState,this).map(getId)}}));this.running=false;if(this.readyState>=SCxml.FINISHED&&this.parent)this.parent.fireEvent(new SCxml.ExternalEvent("done.invoke."+this.iid,"#_"+this.iid,"scxml",this.iid,this.donedata));delete this.donedata;this.sendNoMore=true},restart:function(){if(this.readyState<SCxml.RUNNING)return;if(this.readyState>SCxml.RUNNING)this.terminate();if(!this._iframe_)throw new Error("Cannot restart a cleaned-up session.");var s=this.dom.createNodeIterator(this.dom.documentElement,NodeFilter.SHOW_ELEMENT,SCxml.stateFilter);var v;while(v=s.nextNode()){v.removeAttribute("active");v.removeAttribute("willExit")}var histories=this.dom.querySelectorAll("history");for(var i=0,h;h=histories[i];i++)delete h.record;this.internalQueue=[];this.externalQueue=[];this.configuration={};this.statesToEnter=null;this.invoked={};this.toInvoke=new Set;this.lastEvent=undefined;this.sendNoMore=false;this.delays={};this.timeouts=[];this.intervals=[];document.body.removeChild(this._iframe_);delete this._iframe_;delete this.datamodel;this.initIframe();this.running=false;this.stable=false;this.paused=false;this.readyState=SCxml.LOADING;setTimeout(function(sc){sc.interpret(false)},0,this)},toString:function(){return"SCxml("+this.name+")"},constructor:SCxml,invokedReady:function(){if(!this.parent)return;this.parent.invoked[this.iid]=this;if(this.iid in this.parent.toInvoke.items)this.parent.toInvoke.remove(this.iid)},xhrResponse:function(xhr){this.interpret(xhr.req.responseXML)},xhrFailed:function(xhr){this.invokedReady()},checkTargets:function(target,element){element.targets=new Set;for(var i=0,t,r,ts=target.split(/\s+/);t=ts[i];i++){if(r=this.dom.getElementById(t)){element.targets.add(r._JSSCID);if(t in this.targets)this.targets[t].add(element._JSSCID);else this.targets[t]=new Set(element._JSSCID)}else{if(t in this.missingTargets)this.missingTargets[t].add(element._JSSCID);else this.missingTargets[t]=new Set(element._JSSCID)}}if(!element.targets.length)element.targets=""},validate:function(){if(!this.dom)throw"Failed to load SCXML because of malformed XML.";with(this.dom.documentElement){if(tagName!="scxml")throw this.dom.documentURI+" is not an SCXML document";if(namespaceURI!="http://www.w3.org/2005/07/scxml")console.warn(this.dom.documentURI+" is not a valid SCXML document (missing or incorrect xmlns)");if(hasAttribute("datamodel")&&getAttribute("datamodel")!="ecmascript")throw"'"+getAttribute("datamodel")+"' datamodel in "+this.dom.documentURI+" is not supported by JSSCxml";if(hasAttribute("binding")&&getAttribute("binding")!="early"&&getAttribute("binding")!="late")console.warn("binding='"+getAttribute("binding")+"' in"+this.dom.documentURI+" is not valid");this.lateBinding=getAttribute("binding")=="late";if(hasAttribute("name"))this.name=getAttribute("name")}this.missingTargets={};this.targets={};this.JSSCID={};this.lastJSSCID=1;with(this.dom){var s=createNodeIterator(documentElement,NodeFilter.SHOW_ELEMENT,SCxml.guiFilter);while(v=s.nextNode())this.JSSCID[v._JSSCID=this.lastJSSCID++]=v;s.detach();getElementById=function(id){var r=querySelectorAll("state[id='"+id+"'], final[id='"+id+"'], history[id='"+id+"'], parallel[id='"+id+"']");for(var i=0,s;s=r[i];i++){for(var c=s.parentElement;c&&c.tagName!="content";c=c.parentElement);if(!c)return s}return null};if(documentElement.hasAttribute("initial"))this.checkTargets(documentElement.getAttribute("initial"),documentElement);var states=querySelectorAll("state, final, parallel, history");for(var i=0,state;state=states[i];i++){if(!state.hasAttribute("id"))state.setAttribute("id",this.uniqId());if(!this.inInvoke(state)){state.executeAfterEntry=[];if(state.tagName=="parallel")state.initial=[];else if(state.hasAttribute("initial"))this.checkTargets(state.getAttribute("initial"),state);if(this.obs&&state.localName in this.obs)this.obs[state.localName].observe(state,SCxml.observerOptions[state.localName])}}var invs=querySelectorAll("invoke");for(var i=0,inv;inv=invs[i];i++)if(!inv.hasAttribute("id"))inv.setAttribute("id",this.invokeId(inv.parentNode.getAttribute("id")));var trans=querySelectorAll("transition");for(var i=0,tr;tr=trans[i];i++)if(!this.inInvoke(tr)){if(tr.hasAttribute("target"))this.checkTargets(tr.getAttribute("target"),tr);else tr.targets="";if(this.obs)this.obs.transition.observe(tr,SCxml.observerOptions.transition)}}},inInvoke:function(element){for(var c=element.parentElement;c!=this.dom.documentElement;c=c.parentElement)if(c.tagName=="content")return true;return false},uniqId:function(){var id;do{id="__generated_id_"+Math.floor(Math.random()*1e6)}while(this.dom.getElementById(id));return id},invokeId:function(stateId){var id;do{id=stateId+".inv"+Math.floor(Math.random()*1e6)}while(this.dom.querySelector("invoke[id='"+id+"']"));return id},getById:function(id){var s=this.dom.getElementById(id);if(!s)throw this.name+": transition target "+id+" not found";return s},interpret:function(dom){if(dom===false)dom=this.dom;else{this.dom=dom;try{this.validate()}catch(err){this.invokedReady();throw err}this.html.dispatchEvent(new Event("validated"))}var d=dom.querySelector("scxml > datamodel");if(d)try{this.execute(d)}catch(err){}if(this.sharedData){for(var i in this.sharedData)if(this.sharedData.hasOwnProperty(i)){if(i in this.datamodel._jsscxml_predefined_)this.datamodel._jsscxml_predefined_[i]=this.sharedData[i];else if(i in this.datamodel)this.datamodel[i]=this.sharedData[i];else delete this.sharedData[i]}}d=dom.querySelectorAll("scxml > script");for(i=0;i<d.length;i++)if(!this.inInvoke(d[i]))try{this.wrapScript(d[i].textContent,d[i])}catch(err){}d=dom.querySelectorAll("scxml > * datamodel");for(i=0;i<d.length;i++)if(!this.inInvoke(d[i])){if(this.lateBinding)try{d[i].unbound=true;this.declare(d[i])}catch(err){}else try{this.execute(d[i])}catch(err){}}this.running=true;this.readyState=SCxml.READY;this.html.dispatchEvent(new Event("ready"));this.invokedReady();if(this.interpretASAP)this.start()},start:function(){if(this.readyState<SCxml.READY)throw this.name+" is not ready yet.";if(this.readyState>SCxml.READY)throw this.name+" has already started.";var s=this.firstState(this.dom.documentElement);if(!s)throw this.name+" has no suitable initial state.";this.addStatesToEnter(s);this.readyState=SCxml.RUNNING;this.html.dispatchEvent(new CustomEvent("enter",{detail:{list:this.statesToEnter.inEntryOrder().filter(this.enterState,this).map(getId)}}));if(this.stable)this.terminate();else this.mainEventLoop()},resolve:function(a){if(a instanceof Set){var b=[];for(var i in a.items)b.push(this.JSSCID[i]);return b}else return this.JSSCID[a]},firstState:function(parent){if(parent.tagName!="state"&&parent.tagName!="scxml")return null;if(parent.targets)return this.rememberHistory(this.resolve(parent.targets));if(parent.tagName=="state"&&(state=SCxml.childOfType(parent,"initial"))){var trans=state.firstElementChild;while(trans&&trans.tagName!="transition")trans=trans.nextElementSibling;if(!trans)throw this.name+": <initial> requires a <transition>.";parent.executeAfterEntry=[trans];if(trans.hasAttribute("targetexpr"))this.checkTargets(this.expr(trans.getAttribute("targetexpr"),trans),trans);return this.rememberHistory(this.resolve(trans.targets))}var state=parent.firstElementChild;while(state&&!(state.tagName in SCxml.STATE_ELEMENTS))state=state.nextElementSibling;return state?[state]:null},rememberHistory:function(states){var remembered=[];for(var i=0,state;state=states[i];i++){if(state.tagName=="history"){if("record"in state)remembered=remembered.concat(state.record);else{var trans=state.firstElementChild;while(trans&&trans.tagName!="transition")trans=trans.nextElementSibling;if(!trans)throw this.name+": <history> requires a default <transition>.";state.parentNode.executeAfterEntry.push(trans);remembered=remembered.concat(this.rememberHistory(this.resolve(trans.targets)))}}else remembered.push(state)}return remembered},addStatesToEnter:function(states,lcca){states=this.rememberHistory(states);for(var i=0,state;state=states[i];i++){state.CA=false;this.statesToEnter=this.walkToEnter(state,this.statesToEnter,lcca)}},reduceConfiguration:function(states){var reduced=[];there:for(var i=0,state;state=states[i];i++){for(var j=0,child;child=states[j];j++)if(state!=child&&state.contains(child))continue there;for(var j=0,other;other=reduced[j];j++)if(state==other)continue there;reduced.push(state)}return reduced},walkUpFromCP:function(initials,path){var top=path[path.length-1];var CP=null;var initial=initials[0];if(initial==top)return top;var up=initial;while((up=up.parentNode)&&up!=top)if(up.tagName=="parallel")CP=up;if(CP&&CP!=initial)CP.initial=initials;var rpath=[up=CP||initial];while((up=up.parentNode)&&up!=top){rpath.push(up);up.CA=false}return path.concat(rpath.reverse())},walkToEnter:function(state,tree,lcca){var path=[state];var id=getId(state);if(state.initial&&state.initial.length)state.initial=[];if(state.parentNode.initial&&state.parentNode.initial.length){var initials=state.parentNode.initial.filter(state.contains,state);if(initials){path=this.walkUpFromCP(initials,path)}}var down=path[path.length-1],up=state;while(down=this.firstState(down)){if(down.length>1||down[0].parentNode!=path[path.length-1]){path=this.walkUpFromCP(this.reduceConfiguration(down),path);down=path[path.length-1];continue}down=down[0];path.push(down);down.CA=false}while((up=up.parentNode).tagName=="state"&&up!=lcca){path.unshift(up);up.CA=state.CA}if(up.tagName=="state"){do{path.unshift(up);up.CA=true}while((up=up.parentNode).tagName=="state");up.CA=true}else up.CA=up==lcca;var ct=new CompiledTree(new CompiledPath(path));if(!ct.root.atomic){var c=ct.root.end.firstElementChild;while(c){if(c.tagName in SCxml.STATE_ELEMENTS){if(tree&&tree.root.path[0]==c)ct.appendChild(tree);else if(!state.CA)this.walkToEnter(c,ct,lcca);else{for(var i=0,c2;c2=tree.children[i];i++)if(c2.root.path[0]==c)break;if(!c2)this.walkToEnter(c,ct,lcca)}}c=c.nextElementSibling}}if(tree&&tree.attach(ct))return tree;while(ct.root.parent.tagName!="scxml")ct=this.walkToEnter(ct.root.parent,ct,lcca);return ct},enterState:function(state){var id=getId(state);if(id in this.configuration){state.executeAfterEntry=[];return}this.configuration[id]=state;state.setAttribute("active",true);var dm;if(this.lateBinding&&(dm=SCxml.childOfType(state,"datamodel"))&&"unbound"in dm){delete dm.unbound;try{this.execute(dm)}catch(err){}}var onentry=SCxml.childrenOfType(state,"onentry");for(var i=0,ex;ex=onentry[i]||state.executeAfterEntry.shift();i++)try{this.execute(ex)}catch(err){}state.fin=false;if(state.tagName=="final"){var c=SCxml.childOfType(state,"donedata");if(c)try{state.parentNode.donedata=this.readParams(c,{},true)}catch(err){state.parentNode.donedata=null}return this.finalState(state.parentNode)}return true},finalState:function(state){if(state.tagName=="scxml"){this.running=false;this.stable=true;this.readyState=SCxml.FINISHED;this.html.dispatchEvent(new CustomEvent("finished",{detail:state.donetata}));return true}if(state.tagName=="parallel")for(var c=state.firstElementChild;c;c=c.nextElementSibling)if(c.tagName in SCxml.STATE_ELEMENTS&&!c.fin)return;state.fin=true;var id=getId(state);var doneEv=new SCxml.Event("done.state."+id);doneEv.data=state.tagName=="parallel"||state.donedata;delete state.donedata;this.html.dispatchEvent(new CustomEvent("queue",{detail:doneEv}));this.internalQueue.push(doneEv);if(state.parentNode.tagName=="parallel")this.finalState(state.parentNode);return true},findLCCA:function(trans){if(trans.lcca&&!trans.hasAttribute("targetexpr"))return;var source=trans.parentNode,targets=this.resolve(trans.targets);trans.internal=false;if(targets==null)return trans.lcca=null;trans.lcca=source;if(targets.every(source.contains,source)&&targets.indexOf(source)<0){if(source.tagName!="parallel"&&(trans.internal=trans.getAttribute("type")=="internal"))return}else do{trans.lcca=trans.lcca.parentNode}while(!targets.every(trans.lcca.contains,trans.lcca));if(targets.indexOf(trans.lcca)>-1)trans.lcca=trans.lcca.parentNode;if(!trans.internal&&trans.lcca==source)trans.lcca=trans.lcca.parentNode;while(trans.lcca.tagName=="parallel")trans.lcca=trans.lcca.parentNode},saveHistory:function(state){var id=getId(state);if(!(id in this.configuration))return;var histories=SCxml.childrenOfType(state,"history");for(var i=0,h;h=histories[i];i++)h.record=this.activeChildren(state,h.getAttribute("type")=="deep")},exitState:function(state){var id=getId(state);if(!(id in this.configuration))return;state.removeAttribute("willExit");var onexit=SCxml.childrenOfType(state,"onexit");for(var i=0;i<onexit.length;i++)try{this.execute(onexit[i])}catch(err){}var invoked=SCxml.childrenOfType(state,"invoke");for(i=0;i<invoked.length;i++)this.cancelInvoke(getId(invoked[i]));delete this.configuration[id];state.removeAttribute("active");return true},expr:function(s,el){if(/^function/.test(s))s="_x.__left__="+s;return this.datamodel.expr(s,el)},log:function(s){console.log(s)},error:function(name,src,err,doNotShow){var e=new SCxml.Error("error."+name,src,err);this.html.dispatchEvent(new CustomEvent("queue",{detail:e}));this.internalQueue.push(e);if(!doNotShow)console.error(err+"\nin SCXML "+this.name+" :",src);throw err},selectTransitions:function(event){var sc=this;function test(s){for(var t=s.firstElementChild;t;t=t.nextElementSibling){if(t.nodeType!=1||t.tagName!="transition"||(event?!(t.hasAttribute("event")&&event.match(t)):t.hasAttribute("event")))continue;var cond=false;try{cond=!t.hasAttribute("cond")||sc.expr(t.getAttribute("cond"),t)}catch(err){}if(!cond)continue;if(t.hasAttribute("targetexpr")){try{var targets=String(sc.expr(t.getAttribute("targetexpr"),t));if(!targets)t.targets=null;else this.checkTargets(targets,t)}catch(err){t.targets=null}}return t}return false}return this.statesToEnter.select(test).enabled},mainEventLoop:function(){while(this.running&&!this.stable){this.macrostep();if(!this.running)return this.terminate();if(this.invokeAll()&&this.internalQueue.length)continue;this.stable=true;this.extEventLoop();if(!this.running)return this.terminate()}},normalizeEmptyData:function(event){if(!event)return event;if(event.data===null)event.data=undefined;if("object"!=typeof event.data)return event;var def=false;for(var i in event.data)if(event.data.hasOwnProperty(i)){def=true;break}if(!def)event.data=undefined;return event},macrostep:function(){while(this.running){var trans=this.selectTransitions(null);if(!trans.length){var event;while(event=this.normalizeEmptyData(this.internalQueue.shift())){this.lastEvent=event;this.html.dispatchEvent(new CustomEvent("consume",{detail:"internal"}));trans=this.selectTransitions(event);if(trans.length)break}}if(trans.length)this.preTransitions(trans);else break}},extEventLoop:function(){this.stable=false;var event,trans;while(event=this.normalizeEmptyData(this.externalQueue.shift())){this.lastEvent=event;if(event.invokeid&&event.invokeid in this.invoked){var f=this.dom.querySelector("[id='"+event.invokeid+"'] > finalize");if(f){if(f.firstElementChild)this.execute(f);else this.emptyFinalize(event)}}this.html.dispatchEvent(new CustomEvent("consume",{detail:"external"}));for(var i in this.invoked)if(this.invoked[i].af)this.invoked[i].fireEvent(event);trans=this.selectTransitions(event);if(trans.length)return this.preTransitions(trans)}this.stable=true;this.html.dispatchEvent(new Event("waiting"))},preTransitions:function(trans){for(var i=0,t;t=trans[i];i++){if(t.parentElement.getAttribute("willExit")&&t.targets.length){trans.splice(i--,1);continue}this.findLCCA(t);if(!t.targets.length)continue;var s=this.dom.createNodeIterator(t.lcca,NodeFilter.SHOW_ELEMENT,SCxml.activeStateFilter);var v=s.nextNode();if(v&&v!=t.lcca)v.setAttribute("willExit",true);while(v=s.nextNode())v.setAttribute("willExit",true);s.detach()}this.transitionsToTake=trans;this.html.dispatchEvent(new Event("step"));this.takeTransitions()},takeTransitions:function(){var toExit=this.dom.querySelectorAll("[willExit]");var rev=[],t,i;if(toExit.length){for(i=toExit.length-1;i>=0;i--)rev.push(toExit[i]);rev.forEach(this.saveHistory,this);this.html.dispatchEvent(new CustomEvent("exit",{detail:{list:rev.filter(this.exitState,this).map(getId)}}))}for(i=0;t=this.transitionsToTake[i];i++){try{this.execute(t)}catch(err){}}var currentConf=this.statesToEnter;this.statesToEnter=null;for(i=0;t=this.transitionsToTake[i];i++)if(t.targets.length)this.addStatesToEnter(this.resolve(t.targets),t.lcca);if(this.statesToEnter)this.html.dispatchEvent(new CustomEvent("enter",{detail:{list:this.statesToEnter.inEntryOrder().filter(this.enterState,this).map(getId)}}));else this.statesToEnter=currentConf},activeChildren:function(state,deep){var active=[];var c=this.dom.createTreeWalker(state||this.dom.documentElement,NodeFilter.SHOW_ELEMENT,SCxml.activeStateFilter);if(!c.firstChild())return active;while(1){if(deep)while(c.firstChild());active.push(c.currentNode);if(!(deep?c.nextNode():c.nextSibling()))break}return active},onEvent:function(event){if(!this.running){console.warn(this.name+" has terminated and cannot process more events");return}if(event instanceof Event)event=SCxml.ExternalEvent.fromDOMEvent(event);else if(typeof event=="string")event=new SCxml.ExternalEvent(event,null,undefined,null,arguments[1]);this.html.dispatchEvent(new CustomEvent("queue",{detail:event}));this.externalQueue.push(event);if(this.stable&&!this.paused){this.extEventLoop();if(!this.running)return this.terminate();if(!this.stable)this.mainEventLoop()}}};SCxml.prototype.fireEvent=SCxml.prototype.onEvent;SCxml.NO_PAUSE=0;SCxml.EXT_EVENTS=1;SCxml.ALL_EVENTS=2;SCxml.LOADING=0;SCxml.READY=1;SCxml.RUNNING=2;SCxml.FINISHED=3;SCxml.STATE_ELEMENTS={state:"state",parallel:"parallel","final":"final"};SCxml.IN_GUI={scxml:{parents:[]},state:{parents:["state","parallel","scxml"],idType:"state"},parallel:{parents:["state","parallel","scxml"],idType:"state"},"final":{parents:["state","parallel","scxml"],idType:"state"},history:{parents:["state","parallel"],idType:"state"},initial:{parents:["state","parallel"]},transition:{parents:["state","parallel","initial","history"]},invoke:{parents:["state","parallel"],idType:"invoke"},finalize:{parents:["invoke"]},onentry:{parents:["state","parallel","final"]},onexit:{parents:["state","parallel","final"]},script:{parents:["scxml"]},datamodel:{parents:["state","parallel","scxml","final"]},donedata:{parents:["final"]}};SCxml.stateFilter={acceptNode:function(node){return 2-(node.tagName in SCxml.STATE_ELEMENTS)}};SCxml.guiFilter={acceptNode:function(node){return 2-(node.tagName in SCxml.IN_GUI)}};SCxml.tagNameFilter=function(tagName){return{acceptNode:function(node){if(node.tagName==tagName)return 1;return 2}}};SCxml.activeStateFilter={acceptNode:function(node){if(!(node.tagName in SCxml.STATE_ELEMENTS&&node.getAttribute("active")))return 2;return 1}};SCxml.subStates=function(s){for(var ss=[],c=s.firstElementChild;c;c=c.nextElementSibling)if(c.localName in SCxml.STATE_ELEMENTS)ss.push(c);return ss};SCxml.childOfType=function(s,name){for(var c=s.firstElementChild;c;c=c.nextElementSibling)if(c.localName==name)return c;return null};SCxml.childrenOfType=function(s,name){for(var ct=[],c=s.firstElementChild;c;c=c.nextElementSibling)if(c.localName==name)ct.push(c);return ct};SCxml.prototype.mutationRequiresRestart=function(){};SCxml.prototype.initObservers=function(){this.obs={};for(var i in SCxml.mutations){this.obs[i]=new MutationObserver(SCxml.mutations[i]),this.obs[i].sc=this}};SCxml.mutations={scxml:function(mutations,obs){for(var i in mutations){var e=mutations[i].target;if(mutations[i].type=="attributes")switch(mutations[i].attributeName){case"initial":obs.sc.checkTargets(e.getAttribute("initial"),e);break;case"name":obs.sc.name=e.getAttribute("name")||obs.sc.iid||"session"+obs.sc.sid;break;case"binding":with(mutations[i].target){if(hasAttribute("binding")&&getAttribute("binding")!="early"&&getAttribute("binding")!="late")console.warn("binding='"+getAttribute("binding")+"' in"+obs.sc.name+" is not valid");obs.sc.lateBinding=getAttribute("binding")=="late"}obs.sc.mutationRequiresRestart()}else if(mutations[i].addedNodes.length){var newChild=mutations[i].addedNodes[0];newChild._JSSCID=obs.sc.lastJSSCID++;obs.sc.JSSCID[newChild._JSSCID]=newChild;switch(newChild.localName){case"state":case"parallel":case"final":obs.sc.newTarget(newChild);break}}}},state:function(mutations,obs){for(var i in mutations){var e=mutations[i].target;if(mutations[i].type=="attributes")switch(mutations[i].attributeName){case"initial":obs.sc.checkTargets(e.getAttribute("initial"),e);obs.sc.view.drawTransition(e.ui);break;case"id":obs.sc.renameTarget(mutations[i].oldValue,e)}else if(mutations[i].addedNodes.length){var newChild=mutations[i].addedNodes[0];newChild._JSSCID=obs.sc.lastJSSCID++;obs.sc.JSSCID[newChild._JSSCID]=newChild;switch(newChild.localName){case"state":case"parallel":case"final":obs.sc.newTarget(newChild);if(e.getAttribute("active")&&SCxml.subStates(e).length==1){obs.sc.addStatesToEnter(newChild,newChild.parentNode);obs.sc.html.dispatchEvent(new CustomEvent("enter",{detail:{list:obs.sc.statesToEnter.inEntryOrder().filter(obs.sc.enterState,obs.sc).map(getId)}}))}break;case"history":obs.sc.newTarget(newChild);break;case"transition":break}}}},parallel:function(mutations,obs){for(var i in mutations){var e=mutations[i].target;if(mutations[i].type=="attributes"&&mutations[i].attributeName=="id"){obs.sc.renameTarget(mutations[i].oldValue,e)}else if(mutations[i].addedNodes.length){var newChild=mutations[i].addedNodes[0];newChild._JSSCID=obs.sc.lastJSSCID++;obs.sc.JSSCID[newChild._JSSCID]=newChild;switch(newChild.localName){case"state":case"parallel":case"final":obs.sc.newTarget(newChild);if(e.getAttribute("active")){obs.sc.addStatesToEnter(newChild,newChild.parentNode);obs.sc.html.dispatchEvent(new CustomEvent("enter",{detail:{list:obs.sc.statesToEnter.inEntryOrder().filter(obs.sc.enterState,obs.sc).map(getId)}}))}break;case"history":obs.sc.newTarget(newChild);break;case"transition":break}}}},transition:function(mutations,obs){for(var i in mutations){var e=mutations[i].target;switch(mutations[i].attributeName){case"event":case"cond":case"type":break;case"target":case"targetexpr":var oldTargets;if(oldTargets=e.targets&&obs.sc.resolve(e.targets))for(var j=0,t;t=oldTargets[j];j++)obs.sc.targets[t.getAttribute("id")].remove(e._JSSCID);var expr=false;if(!e.getAttribute("target")){e.targets="";if(e.ui)obs.sc.view.clearArrows(e.ui);expr=!!e.getAttribute("targetexpr")}else{obs.sc.checkTargets(e.getAttribute("target"),e);if(e.ui)obs.sc.view.drawTransition(e.ui)}}}}};SCxml.prototype.newTarget=function(s){var newId=s.getAttribute("id");s.executeAfterEntry=[];if(s.tagName=="parallel")s.initial=[];else if(s.hasAttribute("initial"))this.checkTargets(s.getAttribute("initial"),s);if(this.obs&&s.localName in this.obs)this.obs[s.localName].observe(s,SCxml.observerOptions[s.localName]);if(this.view)s.parentNode.ui.appendChild(this.view.convertNode(s));if(newId in this.missingTargets){for(var t in this.missingTargets[newId].items){this.JSSCID[t].targets.add(s._JSSCID);if(this.JSSCID[t].ui)this.view.drawTransition(this.JSSCID[t].ui)}this.targets[newId]=this.missingTargets[newId];delete this.missingTargets[newId]}};SCxml.prototype.renameTarget=function(oldId,s){var newId=s.getAttribute("id");if(s.ui)s.ui.setAttribute("scid",newId);if(oldId in this.targets){for(var t in this.targets[oldId].items){this.JSSCID[t].targets.remove(s._JSSCID);if(this.JSSCID[t].ui)this.view.drawTransition(this.JSSCID[t].ui)}this.missingTargets[oldId]=this.targets[oldId];delete this.targets[oldId]}if(newId in this.missingTargets){for(t in this.missingTargets[newId].items){this.JSSCID[t].targets.add(s._JSSCID);if(this.JSSCID[t].ui)this.view.drawTransition(this.JSSCID[t].ui)}this.targets[newId]=this.missingTargets[newId];delete this.missingTargets[newId]}};SCxml.observerOptions={scxml:{childList:true,attributes:true,attributeFilter:["initial","name","binding"]},state:{childList:true,attributes:true,attributeFilter:["id","initial"],attributeOldValue:true},parallel:{childList:true,attributes:true,attributeFilter:["id"],attributeOldValue:true},transition:{attributes:true,attributeFilter:["event","cond","target","targetexpr","type"]},initial:{childList:true},"final":{childList:true,attributes:true,attributeFilter:["id"],attributeOldValue:true},onentry:{childList:true},onexit:{childList:true},donedata:{childList:true},history:{childList:true,attributes:true,attributeFilter:["id","type"],attributeOldValue:true},datamodel:{childList:true},script:{childList:true,attributes:true,attributeFilter:["src"]},invoke:{childList:true,attributes:true,attributeFilter:["id","idlocation","type","typeexpr","src","srcexpr","autoforward"]},finalize:{childList:true}};SCxml.EventProcessors={SCXML:{name:"http://www.w3.org/TR/scxml/#SCXMLEventProcessor",createEvent:function(name,sc,data){return new SCxml.ExternalEvent(name,"#_scxml_"+sc.sid,SCxml.EventProcessors.SCXML.name,undefined,data)
},send:function(event,target,element,sc){if(sc.sendNoMore)return;target=target||"#_scxml_"+sc.sid;var sid;if((sid=target.match(/^#_scxml_(.+)$/))&&(sid=sid[1])){if(sid in SCxml.sessions&&SCxml.sessions[sid])SCxml.sessions[sid].onEvent(event);else sc.error("communication",element,new Error('target session "'+target+'" does not exist'))}else if(target.match(/^#_parent$/)){if(sc.parent){event.invokeid=sc.iid;sc.parent.onEvent(event)}else sc.error("communication",element,new Error("this session has no #_parent"))}else if((sid=target.match(/^#_(.+)$/))&&(sid=sid[1])){if(sid in sc.invoked)sc.invoked[sid].onEvent(event);else sc.error("communication",element,new Error('invoked target "'+target+'" does not exist'))}else{sc.error("execution",element,new Error('unsupported target "'+target+'" for SCXML events'))}}},DOM:{name:"http://www.w3.org/TR/scxml/#DOMEventProcessor",createEvent:function(name,sc,data){var e=document.createEvent("CustomEvent");e.initCustomEvent(name,true,false,data);return e},send:function(event,target,element,sc){if(sc.sendNoMore)return;var obj;if(!target)obj=sc.html;if(!obj)try{if(target[0]=="/")obj=document.evaluate(target,sc.html,null,9,null).singleNodeValue;if(target[0]=="#")obj=document.querySelector(target)}catch(err){sc.error("execution.DOM",element,err)}if(!obj)try{obj=document.evaluate(target,sc.html,null,9,null).singleNodeValue}catch(err){}if(!obj)try{obj=document.querySelector(target)}catch(err){}if(!obj)sc.error("execution.DOM",element,new Error('Failed to evaluate "'+target+'" to an existing element'));obj.dispatchEvent(event)}}};SCxml.prototype.initIframe=function(data){if(this.datamodel)return;with(this._iframe_=document.createElement("iframe")){className="scxml_script_frame";style.display="none"}document.body.appendChild(this._iframe_);this.datamodel=this._iframe_.contentWindow;with(this.datamodel.document){open();write("<script>\n"+"function expr(s,el)\n{\n"+" try{ with(_jsscxml_predefined_){ return eval(s) } }\n"+' catch(e){ _sc.error("execution",el,e) }\n'+"}\n"+"function syntexpr(s,el)\n{\n"+" try{ with(_jsscxml_predefined_){ return eval(s) } }\n"+" catch(e){ if(e instanceof SyntaxError) return e\n"+' else _sc.error("execution",el,e) }\n'+"}\n"+"function call(f, args)\n{\n"+" try{ with(_jsscxml_predefined_){ return f.call(null, args) } }\n"+' catch(e){ _sc.error("execution",f,e) }\n'+"}\n"+"\n</script>\n")}this.datamodel._sc=this;this.datamodel._jsscxml_predefined_={};for(var i in this.datamodel)if(this.datamodel.hasOwnProperty(i))this.datamodel._jsscxml_predefined_[i]=undefined;with(this){datamodel.__defineGetter__("_sessionid",function(){return sid});datamodel.__defineSetter__("_sessionid",function(){return sid});datamodel.__defineGetter__("_event",function(){return lastEvent});datamodel.__defineSetter__("_event",function(){return lastEvent});datamodel.__defineGetter__("_name",function(){return name});datamodel.__defineSetter__("_name",function(){return name})}this.datamodel.__defineGetter__("_ioprocessors",function(){return SCxml.EventProcessors});this.datamodel.__defineSetter__("_ioprocessors",function(){return SCxml.EventProcessors});this.datamodel._x={voices:"speechSynthesis"in window&&speechSynthesis.getVoices()};if(data)for(i in data)if(data.hasOwnProperty(i)){if(this.datamodel.hasOwnProperty(i))this.datamodel._jsscxml_predefined_[i]=data[i];else this.datamodel[i]=data[i]}this.datamodel.document.write("<script>\n"+"function In(state){ return state in _sc.configuration }\n"+"function setTimeout(){\n"+" return _sc.timeout(arguments)\n}\n"+"function setInterval(){\n"+" return _sc.interval(arguments)\n}\n"+"function clearTimeout(t){\n"+" return t.cancel()\n}\n"+"function clearInterval(t){\n"+" return t.cancel()\n}\n"+"</script>\n");delete this.datamodel._jsscxml_predefined_.setTimeout;delete this.datamodel._jsscxml_predefined_.setInterval;delete this.datamodel._jsscxml_predefined_.clearTimeout;delete this.datamodel._jsscxml_predefined_.clearInterval};SCxml.prototype.wrapScript=function(script,element){this.datamodel._element=element;this.datamodel.document.write("<script>\n"+"try{ with(_jsscxml_predefined_){\n"+script+'\n}} catch(err){_sc.error("execution", _element, err)}\n</script>')};SCxml.Event=function SCxmlEvent(name,type){this.name=String(name);this.timestamp=(new Date).getTime();this.type=type||"platform"};SCxml.Event.prototype={constructor:SCxml.Event,toString:function(){return"SCxmlEvent("+this.name+")"},origin:undefined,origintype:undefined,sendid:undefined,invokeid:undefined,data:undefined,match:function(t){var patterns=t.getAttribute("event").split(/\s+/);var event=this.name.split(".");overPatterns:for(var i=0,p;p=patterns[i];i++){if((p=p.split(".")).length>event.length)continue;for(var j=0;j<p.length;j++)if(p[j]!="*"&&p[j]!=event[j])continue overPatterns;return true}return false}};SCxml.InternalEvent=function(name,src){SCxml.Event.call(this,name,"internal");this.srcElement=src||null};SCxml.InternalEvent.prototype=new SCxml.Event;SCxml.InternalEvent.prototype.constructor=SCxml.InternalEvent;SCxml.Error=function(name,src,err){SCxml.Event.call(this,name);this.srcElement=src||null;this.err=err;if(src&&src.tagName=="send")this.sendid=src.getAttribute("id")};SCxml.Error.prototype=new SCxml.Event;SCxml.Error.prototype.constructor=SCxml.Error;SCxml.ExternalEvent=function(name,origin,origintype,invokeid,data){SCxml.Event.call(this,name,"external");this.origin=origin;this.origintype=origintype;this.invokeid=invokeid;this.data=data};SCxml.ExternalEvent.prototype=new SCxml.Event;SCxml.ExternalEvent.prototype.constructor=SCxml.ExternalEvent;SCxml.ExternalEvent.DOMRefCount=1;SCxml.ExternalEvent.targetOfElement=function(e){if(e instanceof Element)return'//*[@scxmlref="'+(e.getAttribute("scxmlref")||(e.setAttribute("scxmlref",SCxml.ExternalEvent.DOMRefCount),SCxml.ExternalEvent.DOMRefCount++))+'"]';return e};SCxml.ExternalEvent.fromDOMEvent=function(de){var e=new SCxml.ExternalEvent(de.type,SCxml.ExternalEvent.targetOfElement(de.srcElement),SCxml.EventProcessors.DOM.name);e.timeStamp=de.timeStamp;if(de instanceof CustomEvent)e.data=de.detail;else for(var prop in de)if(de.hasOwnProperty(prop))e.data[prop]=SCxml.ExternalEvent.targetOfElement(de[prop]);return e};SCxml.prototype.declare=function(element){var c=element.firstElementChild;if(element.tagName=="data"){var id=element.getAttribute("id");if(id in this.datamodel._jsscxml_predefined_)console.warn("Variable '"+id+"' is shadowing a predefined"+"window variable: please never delete it.\nin",element);else this.datamodel[id]=undefined}else while(c){this.declare(c);c=c.nextElementSibling}};SCxml.prototype.assign=function(left,right){if(left in this.datamodel._jsscxml_predefined_)this.datamodel._jsscxml_predefined_[left]=right;else this.datamodel[left]=right};SCxml.prototype.assign2=function(left,right,element){this.datamodel._x.__assignRight__=right;this.expr(left+" = _x.__assignRight__",element);delete this.datamodel._x.__assignRight__};SCxml.prototype.readParams=function(element,data,alsoContent){for(var c=element.firstElementChild;c;c=c.nextElementSibling){if(c.tagName=="param"){var name=c.getAttribute("name");var value=c.getAttribute("expr")||c.getAttribute("location");if(data.hasOwnProperty(name)){if(data[name]instanceof Array)data[name].push(this.expr(value,c));else data[name]=[data[name],this.expr(value,c)]}else data[name]=this.expr(value,c)}else if(alsoContent&&c.tagName=="content")return data=this.readContent(c)}return data};SCxml.prototype.readContent=function(c){if(c.hasAttribute("expr"))return this.expr(c.getAttribute("expr"),c);var value;if(value=c.firstElementChild){if(value==c.lastElementChild){var tmp=sc.dom.implementation.createDocument(value.namespaceURI,value.localName);for(var c=value.firstChild;c;c=c.nextSibling)tmp.documentElement.appendChild(tmp.importNode(c,true));return tmp}value=this.dom.createDocumentFragment();for(var c=element.firstChild;c;c=c.nextSibling)value.appendChild(c.cloneNode(true));return value}if(value=c.textContent){try{return JSON.parse(value)}catch(err){return value.replace(/^\s*|\s*$/g,"").replace(/\s+/g," ")}}};SCxml.parseTime=function(s){s=/^((?:\d*\.)?\d+)(m?s)$/.exec(s);if(!s)return-1;var t=Number(s[1]);if(s[2]=="s")t*=1e3;return t};SCxml.prototype.execute=function(element){if(element.namespaceURI==this.dom.documentElement.namespaceURI){if(element.localName in SCxml.executableContent)return SCxml.executableContent[element.localName](this,element);else if(element.localName in SCxml.executableContentNS.tolerate){console.warn("executable element <"+element.tagName+"> should not use default namespace");return SCxml.executableContentNS.tolerate[element.localName](this,element)}else{var c=element.firstElementChild;while(c){this.execute(c);c=c.nextElementSibling}}}else{if(element.namespaceURI in SCxml.executableContentNS){if(element.localName in SCxml.executableContentNS[element.namespaceURI])return SCxml.executableContentNS[element.namespaceURI][element.localName](this,element);else console.warn("executable element <"+element.tagName+"> is not defined in namespace "+element.namespaceURI)}else if(element.localName in SCxml.executableContentNS.tolerate){console.warn("executable element <"+element.tagName+"> should use its own namespace");return SCxml.executableContentNS.tolerate[element.localName](this,element)}else console.warn("missing executable content extension for namespace "+element.namespaceURI+" used with element <"+element.tagName+">")}};SCxml.executableContentNS={tolerate:{}};SCxml.executableContent={raise:function(sc,element){var event=element.getAttribute("event")||sc.expr(element.getAttribute("eventexpr"));event=new SCxml.InternalEvent(event,element);sc.html.dispatchEvent(new CustomEvent("queue",{detail:event}));sc.internalQueue.push(event)},send:function(sc,element){if(sc.sendNoMore)return;var target=element.getAttribute("target")||sc.expr(element.getAttribute("targetexpr"),element);var event=element.getAttribute("event")||sc.expr(element.getAttribute("eventexpr"),element);if(!element.hasAttribute("id"))element.setAttribute("id",sc.uniqId());var id=element.getAttribute("id"),loc;if(loc=element.getAttribute("idlocation"))sc.expr(loc+'="'+id+'"');var proc=element.getAttribute("type")||sc.expr(element.getAttribute("typeexpr"),element)||"SCXML";var delay=SCxml.parseTime(element.getAttribute("delay")||sc.expr(element.getAttribute("delayexpr"),element));if(target=="#_internal"){var e=new SCxml.InternalEvent(event,element);sc.html.dispatchEvent(new CustomEvent("queue",{detail:e}));sc.internalQueue.push(e);return}if(proc in SCxml.EventProcessors)proc=SCxml.EventProcessors[proc];else for(var st in SCxml.EventProcessors)if(SCxml.EventProcessors[st].name==proc)proc=SCxml.EventProcessors[st];if("object"!=typeof proc)sc.error("execution",element,new Error('unsupported IO processor "'+proc+'"'));var namelist=element.getAttribute("namelist");var data={};if(namelist){namelist=namelist.split(" ");for(var i=0,name;name=namelist[i];i++)data[name]=sc.expr(name)}data=sc.readParams(element,data,true);var e=proc.createEvent(event,sc,data,element);if(delay>-1)(element.sent||(element.sent=[])).push(new Delay(delay,!sc.paused,sc,proc,e,target,element));else proc.send(e,target,element,sc)},cancel:function(sc,element){var id=element.getAttribute("sendid")||sc.expr(element.getAttribute("sendidexpr"));for(var timer,sent=sc.dom.querySelector("send[id="+id+"]").sent;timer=sent.pop();timer.cancel());},log:function(sc,element){var value=element.getAttribute("expr");sc.log(element.getAttribute("label")+" = "+sc.expr(value,element))},data:function(sc,element){var id=element.getAttribute("id");if(id in sc.datamodel._jsscxml_predefined_)console.warn("Variable '"+id+"' is shadowing a predefined"+"window variable: please never delete it.\nin",element);else sc.datamodel[id]=undefined;if(element.hasAttribute("src"))console.warn("You should use <fetch> instead of <data src>, which may render the interpreter unresponsive.");else sc.assign(id,sc.readContent(element))},assign:function(sc,element){var loc=element.getAttribute("location");if(!loc)sc.error("syntax",element,new Error("'location' attribute required"));value=sc.readContent(element);sc.assign2(loc,value);if(sc.expr(loc,element)!=value)sc.error("execution",element,new Error("cannot assign to read-only property"))},"if":function(sc,element){var cond=sc.expr(element.getAttribute("cond"));var c=element.firstElementChild;while(!cond&&c){if(c.tagName=="else")cond=true;if(c.tagName=="elseif")cond=sc.expr(c.getAttribute("cond"));c=c.nextElementSibling}while(c){if(c.tagName=="else"||c.tagName=="elseif")break;sc.execute(c);c=c.nextElementSibling}},foreach:function(sc,element){var a=sc.expr(element.getAttribute("array"));var v=element.getAttribute("item");var i=element.getAttribute("index");if("object"!=typeof a&&"string"!=typeof a)sc.error("execution",element,new TypeError("Invalid array"));if(i&&!/^(\$|[^\W\d])[\w$]*$/.test(i))sc.error("execution",element,new SyntaxError("Invalid index"));if(v&&!/^(\$|[^\W\d])[\w$]*$/.test(v))sc.error("execution",element,new SyntaxError("Invalid item"));for(var k in a){if(i)sc.assign(i,k);if(v)sc.assign(v,a[k]);for(var c=element.firstElementChild;c;c=c.nextElementSibling)sc.execute(c)}},script:function(sc,element){sc.wrapScript(element.textContent,element)}};SCxml.invokeTypes={scxml:{name:"http://www.w3.org/TR/scxml",instantiate:function(src,data,id,psc){var sc=new SCxml(src,null,null,true);sc.iid=id;sc.name=id;sc.parent=psc;sc.sharedData=data;return sc}}};SCxml.prototype.invokeAll=function(){var invs=this.dom.querySelectorAll("*[active] > invoke");for(var i=0;i<invs.length;i++){try{this.invoke(invs[i])}catch(err){}}return this.toInvoke.length};SCxml.prototype.cancelInvoke=function(inv){if(!(inv in this.invoked))return false;try{this.invoked[inv].clean()}catch(err){}};SCxml.prototype.invoke=function(inv){var id=getId(inv),loc;if(id in this.invoked||id in this.toInvoke.items)return;if(loc=inv.getAttribute("idlocation"))this.expr(loc+'="'+id+'"');var type=inv.getAttribute("type")||this.expr(inv.getAttribute("typeexpr"),inv)||"scxml";if(!(type in SCxml.invokeTypes)){type=type.replace(/\/$/,"");for(var st in SCxml.invokeTypes)if(SCxml.invokeTypes[st].name==type){type=st;break}}if(!(type in SCxml.invokeTypes))this.error("execution",inv,new Error('unsupported invoke type "'+type+'"'));var namelist=inv.getAttribute("namelist");var data={};if(namelist){namelist=namelist.split(" ");for(var i=0,name;name=namelist[i];i++)data[name]=this.expr(name)}if("open"in SCxml.invokeTypes[type]){var src=inv.getAttribute("target")||this.expr(inv.getAttribute("targetexpr"),inv);if(!src)this.error("execution",inv,new Error("target required"));data=this.readParams(inv,data,true)}else{var src=inv.getAttribute("src")||this.expr(inv.getAttribute("srcexpr"),inv);var c=this.dom.querySelector("[id='"+id+"'] > content");if(c){if(c.hasAttribute("expr"))src=this.expr(c.getAttribute("expr"),c);else if(!c.firstElementChild)src=c.textContent;else src=(new XMLSerializer).serializeToString(c.firstElementChild)}data=this.readParams(inv,data);this.toInvoke.add(id)}var invoked=SCxml.invokeTypes[type]["open"in SCxml.invokeTypes[type]?"open":"instantiate"](src,data,id,this);invoked.af=inv.hasAttribute("autoforward")};SCxml.prototype.emptyFinalize=function(event){var inv=this.invoked[event.invokeid];if(!inv.sharedData||!event.data)return;for(var i in inv.sharedData)if(i in event.data)this.assign(i,event.data[i])};if(!("http://www.jsscxml.org"in SCxml.executableContentNS))SCxml.executableContentNS["http://www.jsscxml.org"]={};with({exc:SCxml.executableContentNS["http://www.jsscxml.org"]}){exc._support_={xmls:function(o,element){if(o instanceof Element||o instanceof Document)return(new XMLSerializer).serializeToString(o);sc.error("execution",element,new TypeError('"xml" type requires a Document or Element.'))},urls:function(o,element){if(typeof o!="object")sc.error("execution",element,new TypeError('"url" type requires an object with enumerable properties.'));var s=[];for(k in o)if(o.hasOwnProperty(k))s.push(k+"="+encodeURIComponent(o[k]));return s.join("&")},mime:{json:"application/json",xml:"application/xml",url:"application/x-www-form-urlencoded",text:"text/plain"},Request:function(target,caller,callback,headers,postData){this.target=target;this.callback=callback;this.caller=caller;var xhr=this;with(this.req=new XMLHttpRequest){open(postData?"POST":"GET",target,true);onload=function(){xhr.caller.fireEvent(new SCxml.ExternalEvent(xhr.callback+".done",xhr.target,"http",null,xhr.req))};onerror=function(e){if(xhr.bad)return;xhr.caller.fireEvent(new SCxml.ExternalEvent(xhr.callback+".failed",xhr.target,"http",null,xhr.req))};for(var h in headers)setRequestHeader(h,headers[h]);try{send(postData||null)}catch(err){this.bad=true;caller.error("communication."+callback,target,err,true)}}}};exc._support_.types={json:JSON.stringify,xml:exc._support_.xmls,url:exc._support_.urls,text:String};SCxml.prototype.readHeaders=function(element,headers){for(var c=element.firstElementChild;c;c=c.nextElementSibling)if(c.localName=="header"){var name=c.getAttribute("name");var value=c.getAttribute("value")||this.expr(c.getAttribute("expr"),c);if(name&&value)headers[name]=value}};exc.fetch=function(sc,element){var target=element.getAttribute("target")||sc.expr(element.getAttribute("targetexpr"),element);var event=element.getAttribute("callback")||sc.expr(element.getAttribute("callbackexpr"),element);var type=element.getAttribute("type")||element.getAttribute("enctype")||sc.expr(element.getAttribute("typeexpr"),element)||sc.expr(element.getAttribute("enctypeexpr"),element)||"text";var proc;if(type in exc._support_.types)proc=exc._support_.types[type];if("function"!=typeof proc)sc.error("execution",element,new Error('unsupported fetch enctype "'+type+'"'));var namelist=element.getAttribute("namelist");var data={};if(namelist){namelist=namelist.split(/\s+/);for(var i=0,name;name=namelist[i];i++)data[name]=sc.expr(name)}data=sc.readParams(element,data,true);var headers={"Content-Type":exc._support_.mime[type]};sc.readHeaders(element,headers);if("object"==typeof data){var def=false;for(var i in data)if(data.hasOwnProperty(i)){def=true;break}if(!def)data=""}new exc._support_.Request(target,sc,event,headers,proc(data))};SCxml.executableContentNS.tolerate.fetch=exc.fetch}SCxml.invokeTypes["event-stream"]={name:"http://www.jsscxml.org/event-stream/",open:function(target,data,id,psc){try{var stream=new EventSource(target)}catch(err){psc.error("communication."+id,this,err)}stream.iid=id;psc.invoked[id]=stream;stream.parent=psc;stream.sharedData=data;stream.onmessage=SCxml.invokeTypes["event-stream"].onmessage;stream.onerror=SCxml.invokeTypes["event-stream"].onerror;stream.clean=SCxml.invokeTypes["event-stream"].clean;stream.fireEvent=SCxml.invokeTypes["event-stream"].noSend;return stream},noSend:function(){this.parent.error("communication."+this.iid,this,new Error("Cannot send events over this connection"))},onmessage:function(message){var name=message.data.match(/^\s*(\w+(?:\.\w+)?)/);name=name?name[1]:"message."+this.iid;var data=message.data.replace(/^.*\n/,"");if(data)try{data=JSON.parse(data)}catch(err){}else data=undefined;var e=new SCxml.ExternalEvent(name,"#_"+this.iid,"event-stream",this.iid,data);e.timeStamp=message.timeStamp;if(/^done\b/.test(name))this.sendNoMore=true;this.parent.fireEvent(e);if(/^done\b/.test(name))this.clean()},onerror:function(){if(this.readyState==EventSource.CLOSED){this.parent.error("communication."+this.iid,this,new Error("Cannot establish event-stream connection to "+this.url),true);this.clean()}},clean:function(){this.sendNoMore=true;this.close();delete this.parent.invoked[this.iid];delete this.parent}};if("speechSynthesis"in window){if(!("http://www.jsscxml.org"in SCxml.executableContentNS))SCxml.executableContentNS["http://www.jsscxml.org"]={_support_:{}};with({exc:SCxml.executableContentNS["http://www.jsscxml.org"]}){exc._support_.speakEvent=function(de,sc){var e=new SCxml.ExternalEvent("speak."+de.type,de.target,SCxml.EventProcessors.DOM.name,null,{elapsedTime:de.elapsedTime,charIndex:de.charIndex,name:de.name});e.timeStamp=de.timeStamp;sc.fireEvent(e)};exc.speak=function(sc,element){var stop=element.hasAttribute("interrupt")||element.hasAttribute("nomore");var text=element.getAttribute("text")||sc.expr(element.getAttribute("expr"),element);if(text){var s=new SpeechSynthesisUtterance(text);s.lang=element.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")||element.getAttribute("lang")||sc.expr(element.getAttribute("langexpr"),element)||sc.dom.documentElement.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")||sc.dom.documentElement.getAttribute("lang");if((s.voice=sc.expr(element.getAttribute("voice"),element))&&"voiceURI"in s.voice)s.voiceURI=s.voice.voiceURI;s.rate=+sc.expr(element.getAttribute("rate"),element)||1;s.pitch=+sc.expr(element.getAttribute("pitch"),element)||1;s.volume=+sc.expr(element.getAttribute("volume"),element)||1;s.onstart=function(e){exc._support_.speakEvent(e,sc)};s.onend=function(e){exc._support_.speakEvent(e,sc)};s.onmark=function(e){exc._support_.speakEvent(e,sc)};s.onboundary=function(e){exc._support_.speakEvent(e,sc)};s.onerror=function(e){exc._support_.speakEvent(e,sc)};if(stop)speechSynthesis.cancel();speechSynthesis.speak(s)}else if(stop)speechSynthesis.cancel();else sc.error("execution",element,new Error("cannot speak an empty string"))};SCxml.executableContentNS.tolerate.speak=exc.speak}}else{console.warn("This browser does not implement SpeechSynthesis.")}