Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Rev'd latest build.

  • Loading branch information...
commit 61c365ef6a078131ec9be6c5f268ad06b8675604 1 parent 3a8a4f6
@jbeard4 authored
Showing with 551 additions and 435 deletions.
  1. +1 −1  builds/latest/scion-min.js
  2. +550 −434 builds/latest/scion.js
View
2  builds/latest/scion-min.js
@@ -1 +1 @@
-(function(){if(!this.require){var a={},b={},c=function(f,g){var h=d(g,f),i=b[h],j;if(i)return i.exports;if(!(j=a[h]||a[h=d(h,"./index")]))throw"module '"+f+"' not found";i={id:h,exports:{}};try{return b[h]=i,j(i.exports,function(a){return c(a,e(h))},i),i.exports}catch(k){throw delete b[h],k}},d=function(a,b){var c=[],d,e;/^\.\.?(\/|$)/.test(b)?d=[a,b].join("/").split("/"):d=b.split("/");for(var f=0,g=d.length;f<g;f++)e=d[f],e==".."?c.pop():e!="."&&e!=""&&c.push(e);return c.join("/")},e=function(a){return a.split("/").slice(0,-1).join("/")};this.require=function(a){return c(a,"")},this.require.define=function(b){for(var c in b)a[c]=b[c]}}return this.require.define}).call(this)({"browser/browser-listener-client":function(a,b,c){},"browser/dom":function(a,b,c){"use strict";function e(a,b){return"item"in a?a.item(b):a[b]}var d=b("../embedded/dom"),f=Object.create(d);f.hasAttribute=function(a,b){return a.hasAttribute?a.hasAttribute(b):a.getAttribute(b)},f.localName=function(a){return a.localName||a.tagName},f.createElementNS=function(a,b,c){return a.createElementNS?a.createElementNS(b,c):a.createElement(c)},f.getChildren=function(a){var b=[];for(var c=0;c<a.childNodes.length;c++)b.push(e(a.childNodes,c));return b},c.exports=f},"browser/platform":function(a,b,c){"use strict";var d=b("../core/util/util"),e=b("../embedded/platform").platform;a.platform=d.merge(Object.create(e),{ajax:window.jQuery,getDocumentFromUrl:function(a,b){this.ajax.get(a,function(a){b(null,a)},"xml").error(function(a){b(a)})},parseDocumentFromString:function(a){return(new window.DOMParser).parseFromString(a,"application/xml")},getDocumentFromFilesystem:function(a,b){this.getDocumentFromUrl(a,b)},getResourceFromUrl:function(a,b){this.ajax.get(a,function(a){b(null,a)}).error(function(a){b(a)})},postDataToUrl:function(a,b,c){this.ajax.post(a,b,function(a){c(null,a)}).error(function(a){c(a)})},setTimeout:function(a,b){return window.setTimeout(a,b)},clearTimeout:function(a){window.clearTimeout(a)},log:window.console.log.bind(console),url:b("./url"),dom:b("./dom")})},"browser/url":function(a,b,c){"use strict";function d(a){var b=document.createElement("a");return b.href=a,b}c.exports={getPathFromUrl:function(a){var b=d(a);return b.pathname},changeUrlPath:function(a,b){var c=d(a);return c.protocol+"//"+c.hostname+":"+c.port+b}}},"core/constants":function(a,b,c){"use strict";c.exports={SCXML_NS:"http://www.w3.org/2005/07/scxml"}},"core/scxml/SCXML":function(a,b,c){"use strict";function i(a){return function(a){var b=a[0],c=a[1];return b.source.depth<c.source.depth?c:c.source.depth<b.source.depth?b:b.documentOrder<c.documentOrder?b:c}}function k(a,b){this.model=a,this.opts=b,this.opts.log=this.opts.log||h.platform.log,this.opts.StateIdSet=this.opts.StateIdSet||d,this.opts.EventSet=this.opts.EventSet||d,this.opts.TransitionPairSet=this.opts.TransitionPairSet||d,this.opts.priorityComparisonFn=this.opts.priorityComparisonFn||i(this.opts.model),this._configuration=new this.opts.BasicStateSet,this._historyValue={},this._innerEventQueue=[],this._isInFinalState=!1,this._timeoutMap={},this._listeners=[]}function l(a,b){b=b||{},f(b),this._isStepping=!1,this._send=b.send||this._send,this._cancel=b.cancel||this._cancel,k.call(this,a,b)}var d=b("./set/ArraySet"),e=b("./state-kinds-enum"),f=b("./setup-default-opts"),g=b("./scxml-dynamic-name-match-transition-selector"),h=b("../../platform"),j=!1;k.prototype={start:function(){j&&h.platform.log("performing initial big step"),this._configuration.add(this.model.root.initial);var a=this.opts.require||c.parent&&c.parent.parent&&c.parent.parent.require&&c.parent.parent.require.bind(c.parent.parent)||b.main&&b.main.require&&b.main.require.bind(b.main)||b,d=this.model.actionFactory(this.opts.log,this._cancel.bind(this),this._send.bind(this),this.opts.origin,this.isIn.bind(this),a);return this._actions=d.actions,this._datamodel=d.datamodel,this._performBigStep(),this.getConfiguration()},_getOrSetData:function(a,b,c){var d=this._datamodel[b];if(!d)throw new Error("Variable "+b+" not declared in datamodel.");return d[a](c)},_getData:function(a){return this._getOrSetData("get",a)},_setData:function(a,b){return this._getOrSetData("set",a,b)},getConfiguration:function(){return this._configuration.iter().map(function(a){return a.id})},getFullConfiguration:function(){return this._configuration.iter().map(function(a){return[a].concat(this.opts.model.getAncestors(a))},this).reduce(function(a,b){return a.concat(b)},[]).map(function(a){return a.id}).reduce(function(a,b){return a.indexOf(b)>-1?a:a.concat(b)},[])},isIn:function(a){return this.getFullConfiguration().indexOf(a)>-1},_performBigStep:function(a){a&&this._innerEventQueue.push(new this.opts.EventSet([a]));var b=!0;while(b){var c=this._innerEventQueue.length?this._innerEventQueue.shift():new this.opts.EventSet,d={},f=this._performSmallStep(c,d);b=!f.isEmpty()}this._isInFinalState=this._configuration.iter().every(function(a){return a.kind===e.FINAL})},_performSmallStep:function(a,b){j&&h.platform.log("selecting transitions with eventSet: ",a);var c=this._selectTransitions(a,b);j&&h.platform.log("selected transitions: ",c);if(!c.isEmpty()){j&&h.platform.log("sorted transitions: ",c);var d=new this.opts.TransitionSet(c.iter().filter(function(a){return a.targets})),f=this._getStatesExited(d),g=f[0],i=f[1],k=this._getStatesEntered(d),l=k[0],m=k[1];j&&h.platform.log("basicStatesExited ",g),j&&h.platform.log("basicStatesEntered ",l),j&&h.platform.log("statesExited ",i),j&&h.platform.log("statesEntered ",m);var n=new this.opts.EventSet;j&&h.platform.log("executing state exit actions"),i.forEach(function(c){(j||this.opts.logStatesEnteredAndExited)&&h.platform.log("exiting ",c.id),this._listeners.forEach(function(a){a.onExit&&a.onExit(c.id)}),c.onexit!==undefined&&this._evaluateAction(c.onexit,a,b,n);var d;c.history&&(c.history.isDeep?d=function(a){return a.kind===e.BASIC&&c.descendants.indexOf(a)>-1}:d=function(a){return a.parent===c},this._historyValue[c.history.id]=i.filter(d))},this);var o=c.iter().sort(function(a,b){return a.documentOrder-b.documentOrder});j&&h.platform.log("executing transitition actions"),o.forEach(function(c){var d=c.targets&&c.targets.map(function(a){return a.id});this._listeners.forEach(function(a){a.onTransition&&a.onTransition(c.source.id,d)}),c.actions!==undefined&&this._evaluateAction(c.actions,a,b,n)},this),j&&h.platform.log("executing state enter actions"),m.forEach(function(c){(j||this.opts.logStatesEnteredAndExited)&&h.platform.log("entering",c.id),this._listeners.forEach(function(a){a.onEntry&&a.onEntry(c.id)}),c.onentry!==undefined&&this._evaluateAction(c.onentry,a,b,n)},this),j&&h.platform.log("updating configuration "),j&&h.platform.log("old configuration ",this._configuration),this._configuration.difference(g),this._configuration.union(l),j&&h.platform.log("new configuration ",this._configuration),n.isEmpty()||(j&&h.platform.log("adding triggered events to inner queue ",n),this._innerEventQueue.push(n)),j&&h.platform.log("updating datamodel for next small step :");for(var p in b)this._setData(p,b[p])}return c},_evaluateAction:function(a,b,c,d){function e(a){d.add({name:a,data:{}})}var f=this._getScriptingInterface(c,b,!0);return this._actions[a].call(this.opts.evaluationContext,f.getData,f.setData,f.events,e)},_getScriptingInterface:function(a,b,c){return{setData:c?function(b,c){return a[b]=c}:function(){},getData:this._getData.bind(this),events:b.iter()}},_getStatesExited:function(a){var b=new this.opts.StateSet,c=new this.opts.BasicStateSet;a.iter().forEach(function(a){var d=a.lca,e=d.descendants;this._configuration.iter().forEach(function(a){e.indexOf(a)>-1&&(c.add(a),b.add(a),this.opts.model.getAncestors(a,d).forEach(function(a){b.add(a)}))},this)},this);var d=b.iter().sort(function(a,b){return b.depth-a.depth});return[c,d]},_getStatesEntered:function(a){var b=new this.opts.StateSet,c=new this.opts.BasicStateSet,d=new this.opts.StateSet,f=[],g=function(a,c){h(c);var f=this.opts.model.getLCA(a,c);this.opts.model.getAncestors(c,f).forEach(function(a){a.kind===e.COMPOSITE?(b.add(a),d.add(a)):h(a)})}.bind(this),h=function(a){if(d.contains(a))return;a.kind===e.HISTORY?a.id in this._historyValue?this._historyValue[a.id].forEach(function(b){g(a,b)}):(b.add(a),c.add(a)):(b.add(a),a.kind===e.PARALLEL?f.push.apply(f,a.children.filter(function(a){return a.kind!==e.HISTORY})):a.kind===e.COMPOSITE?f.push(a.initial):(a.kind===e.INITIAL||a.kind===e.BASIC||a.kind===e.FINAL)&&c.add(a)),d.add(a)}.bind(this);a.iter().forEach(function(a){a.targets.forEach(function(b){g(a.source,b)})});var i;while(i=f.pop())h(i);var j=b.iter().sort(function(a,b){return a.depth-b.depth});return[c,j]},_selectTransitions:function(a,b){if(this.opts.onlySelectFromBasicStates)var c=this._configuration.iter();else{var d=new this.opts.StateSet;this._configuration.iter().forEach(function(a){d.add(a),this.opts.model.getAncestors(a).forEach(function(a){d.add(a)})},this),c=d.iter()}var e=this._getScriptingInterface(b,a),f=function(a){return this._actions[a.conditionActionRef].call(this.opts.evaluationContext,e.getData,e.setData,e.events)}.bind(this),i=a.iter().map(function(a){return a.name}),k=i.filter(function(a){return a.search(".")}).length,l=k?g:this.opts.transitionSelector,m=new this.opts.TransitionSet;c.forEach(function(a){l(a,i,f).forEach(function(a){m.add(a)})});var n=this._selectPriorityEnabledTransitions(m);return j&&h.platform.log("priorityEnabledTransitions",n),n},_selectPriorityEnabledTransitions:function(a){var b=new this.opts.TransitionSet,c=this._getInconsistentTransitions(a),d=c[0],e=c[1];b.union(d),j&&h.platform.log("enabledTransitions",a),j&&h.platform.log("consistentTransitions",d),j&&h.platform.log("inconsistentTransitionsPairs",e),j&&h.platform.log("priorityEnabledTransitions",b);while(!e.isEmpty())a=new this.opts.TransitionSet(e.iter().map(function(a){return this.opts.priorityComparisonFn(a)},this)),c=this._getInconsistentTransitions(a),d=c[0],e=c[1],b.union(d),j&&h.platform.log("enabledTransitions",a),j&&h.platform.log("consistentTransitions",d),j&&h.platform.log("inconsistentTransitionsPairs",e),j&&h.platform.log("priorityEnabledTransitions",b);return b},_getInconsistentTransitions:function(a){var b=new this.opts.TransitionSet,c=new this.opts.TransitionPairSet,d=a.iter();j&&h.platform.log("transitions",d);for(var e=0;e<d.length;e++)for(var f=e+1;f<d.length;f++){var g=d[e],i=d[f];this._conflicts(g,i)&&(b.add(g),b.add(i),c.add([g,i]))}var k=a.difference(b);return[k,c]},_conflicts:function(a,b){return!this._isArenaOrthogonal(a,b)},_isArenaOrthogonal:function(a,b){var c=a.targets?a.lca:a.source,d=b.targets?b.lca:b.source,e=this.opts.model.isOrthogonalTo(c,d);return j&&(h.platform.log("transition LCAs",c.id,d.id),h.platform.log("transition LCAs are orthogonal?",e)),e},registerListener:function(a){return this._listeners.push(a)},unregisterListener:function(a){return this._listeners.splice(this._listeners.indexOf(a),1)}},l.prototype=Object.create(k.prototype),l.prototype.gen=function(a,b){var c;switch(typeof a){case"string":c={name:a,data:b};break;case"object":if(typeof a.name!="string")throw new Error('Event object must have "name" property of type string.');c=a;break;default:throw new Error("First argument to gen must be a string or object.")}if(this._isStepping)throw new Error("gen called before previous call to gen could complete. If executed in single-threaded environment, this means it was called recursively, which is illegal, as it would break SCION step semantics.");return this._isStepping=!0,this._performBigStep(c),this._isStepping=!1,this.getConfiguration()},l.prototype._send=function(a,b){var c,d,e=this;if(!h.platform.setTimeout)throw new Error("setTimeout function not set");j&&h.platform.log("sending event",a.name,"with content",a.data,"after delay",b.delay),c=function(){return e.gen(a)},d=h.platform.setTimeout(c,b.delay);if(b.sendid)return this._timeoutMap[b.sendid]=d},l.prototype._cancel=function(a){if(!h.platform.clearTimeout)throw new Error("clearTimeout function not set");if(a in this._timeoutMap)return j&&h.platform.log("cancelling ",a," with timeout id ",this._timeoutMap[a]),h.platform.clearTimeout(this._timeoutMap[a])},c.exports={SCXMLInterpreter:k,SimpleInterpreter:l}},"core/scxml/default-transition-selector":function(a,b,c){"use strict";c.exports=function(a,b,c){return a.transitions.filter(function(a){return!a.event||b.indexOf(a.event)>-1&&(!a.cond||c(a))})}},"core/scxml/json2model":function(a,b,c){"use strict";function f(a){function b(a,b){return d.push(e.gen.util.wrapFunctionBodyInDeclaration(a,b))-1}function c(a){return f[a]}var d=[],f={};a.states.forEach(function(a){f[a.id]=a}),a.transitions.forEach(function(a){a.cond&&(a.conditionActionRef=b(a.cond,!0))}),a.states.forEach(function(d){d.transitions=d.transitions.map(function(b){return a.transitions[b]});var e=[];d.onentry&&(d.onentry=b(d.onentry)),d.onexit&&(d.onexit=b(d.onexit)),d.transitions.forEach(function(a){a.actions&&(a.actions=b(a.actions)),a.lca&&(a.lca=f[a.lca])}),d.initial=f[d.initial],d.history=f[d.history],d.children=d.children.map(c),d.parent=f[d.parent],d.ancestors&&(d.ancestors=d.ancestors.map(c)),d.descendants&&(d.descendants=d.descendants.map(c)),d.transitions.forEach(function(a){a.source=f[a.source],a.targets=a.targets&&a.targets.map(c)})}),a.root=f[a.root];var g=e.gen.util.makeActionFactory(a.scripts,d,a.datamodel);return g}function g(a,b){var c=f(a);try{a.actionFactory=d.platform.eval(c,b)}catch(e){throw d.platform.log("Failed to evaluate action factory."),d.platform.log("Generated js code to evaluate\n",c),e}}var d=b("../../platform"),e=b("../util/code-gen");c.exports=function(a,b){return g(a,b),a};if(b.main===c){var h=process.argv[2],i=function(a,b){if(a)throw a;process.stdout.write(f(JSON.parse(b)))};if(h==="-"){var j="";process.stdin.resume(),process.stdin.on("data",function(a){j+=a}),process.stdin.on("end",function(a){i(null,j)})}else{var k=b("fs");k.readFile(h,"utf8",i)}}},"core/scxml/model":function(a,b,c){"use strict";var d=b("./state-kinds-enum"),e={getAncestors:function(a,b){var c,d,e;return d=a.ancestors.indexOf(b),d>-1?a.ancestors.slice(0,d):a.ancestors},getAncestorsOrSelf:function(a,b){return[a].concat(this.getAncestors(a,b))},getDescendantsOrSelf:function(a){return[a].concat(a.descendants)},isOrthogonalTo:function(a,b){return!this.isAncestrallyRelatedTo(a,b)&&this.getLCA(a,b).kind===d.PARALLEL},isAncestrallyRelatedTo:function(a,b){return this.getAncestorsOrSelf(b).indexOf(a)>-1||this.getAncestorsOrSelf(a).indexOf(b)>-1},getLCA:function(a,b){var c=this.getAncestors(a).filter(function(a){return a.descendants.indexOf(b)>-1},this);return c[0]}};c.exports=e},"core/scxml/scxml-dynamic-name-match-transition-selector":function(a,b,c){"use strict";function e(a){return new RegExp("^"+a.replace(/\./g,"\\.")+"(\\.[0-9a-zA-Z]+)*$")}function f(a){return d[a]?d[a]:d[a]=e(a)}function g(a,b){var c=a.events,d=c.indexOf("*")>-1?function(){return!0}:function(a){return c.filter(function(b){return f(b).test(a)}).length};return b.filter(d).length}var d={};c.exports=function(a,b,c){return a.transitions.filter(function(a){return(!a.events||g(a,b))&&(!a.cond||c(a))})}},"core/scxml/set/ArraySet":function(a,b,c){"use strict";function d(a){a=a||[],this.o=[],a.forEach(function(a){this.add(a)},this)}d.prototype={add:function(a){if(!this.contains(a))return this.o.push(a)},remove:function(a){var b=this.o.indexOf(a);return b===-1?!1:(this.o.splice(b,1),!0)},union:function(a){return a=a.iter?a.iter():a,a.forEach(function(a){this.add(a)},this),this},difference:function(a){return a=a.iter?a.iter():a,a.forEach(function(a){this.remove(a)},this),this},contains:function(a){return this.o.indexOf(a)>-1},iter:function(){return this.o},isEmpty:function(){return!this.o.length},equals:function(a){var b=a.iter(),c=this.o;return c.every(function(a){return b.indexOf(a)>-1})&&b.every(function(a){return c.indexOf(a)>-1})},toString:function(){return"Set("+this.o.toString()+")"}},c.exports=d},"core/scxml/setup-default-opts":function(a,b,c){"use strict";var d=b("./scxml-dynamic-name-match-transition-selector"),e=b("./set/ArraySet"),f=b("./model");c.exports=function(a){return a=a||{},a.TransitionSet=a.TransitionSet||e,a.StateSet=a.StateSet||e,a.BasicStateSet=a.BasicStateSet||e,a.transitionSelector=a.transitionSelector||d,a.model=a.model||f,a}},"core/scxml/state-kinds-enum":function(a,b,c){"use strict";c.exports={BASIC:0,COMPOSITE:1,PARALLEL:2,HISTORY:3,INITIAL:4,FINAL:5}},"core/util/annotate-scxml-json":function(a,b,c){"use strict";function t(a){return f.platform.dom.getChildren(a).filter(function(a){return f.platform.dom.localName(a)==="script"}).map(function(a){return a.textContent})}function u(a){var b,c,d;c=0,d={};for(b in a)d[b]={name:b,documentOrder:c++};return d}function w(a,b){if(f.platform.dom.hasAttribute(a,"event")){var c,e=f.platform.dom.getAttribute(a,"event");e==="*"?c=[e]:c=e.trim().split(/\s+/).map(function(a){var b=a.match(v);if(b){var c=b[1];if(!b||!c)throw new Error("Unable to parse event: "+a);return c}}),c.filter(function(a){return a!=="*"}).forEach(function(a){l[a]=!0});if(c.indexOf(undefined)>-1)throw new Error("Error parsing event attribute attributes.event")}var g={documentOrder:m.length,id:m.length,source:b.id,cond:f.platform.dom.getAttribute(a,"cond"),events:c,targets:f.platform.dom.hasAttribute(a,"target")?f.platform.dom.getAttribute(a,"target").trim().split(/\s+/):null};return f.platform.dom.getElementChildren(a).length&&(g.actions=d.gen.parentToFnBody(a)),m.push(g),g}function x(a,b){f.platform.dom.getChildren(a).filter(function(a){return f.platform.dom.localName(a)==="data"}).forEach(function(a){f.platform.dom.hasAttribute(a,"id")&&(p[f.platform.dom.getAttribute(a,"id")]=f.platform.dom.hasAttribute(a,"expr")?f.platform.dom.getAttribute(a,"expr"):null)})}function y(a,b){var c=f.platform.dom.hasAttribute(a,"id")?f.platform.dom.getAttribute(a,"id"):B(f.platform.dom.localName(a)),l;switch(f.platform.dom.localName(a)){case"state":f.platform.dom.getChildren(a).filter(function(a){return i.indexOf(f.platform.dom.localName(a))>-1}).length?l=g.COMPOSITE:l=g.BASIC;break;case"scxml":l=g.COMPOSITE;break;case"initial":l=g.INITIAL;break;case"parallel":l=g.PARALLEL;break;case"final":l=g.FINAL;break;case"history":l=g.HISTORY;break;default:}var m={id:c,kind:l,descendants:[]};n[c]=m,b.length&&(m.parent=b[b.length-1]),l===g.HISTORY&&(m.isDeep=f.platform.dom.getAttribute(a,"type")==="deep"?!0:!1),m.documentOrder=j.length,j.push(m);if(l===g.BASIC||l===g.INITIAL||l===g.HISTORY)m.basicDocumentOrder=k.length,k.push(m);m.depth=b.length,m.ancestors=b.slice(),b.forEach(function(a){n[a].descendants.push(m.id)});var o,p,r=[],s=[],t=b.concat(m.id),u=!1,v=null,z=function(a){var b=y(a,t);return m.initial=b.id,s.push(b),u=!0};f.platform.dom.getElementChildren(a).forEach(function(a){switch(f.platform.dom.localName(a)){case"transition":r.push(w(a,m));break;case"onentry":p=d.gen.parentToFnBody(a);break;case"onexit":o=d.gen.parentToFnBody(a);break;case"initial":if(!!u)throw new Error("Encountered duplicate initial states in state "+m.id);z(a);break;case"history":var b=y(a,t);m.history=b.id,s.push(b);break;case"datamodel":x(a,t);break;default:if(h.indexOf(f.platform.dom.localName(a))>-1){var c=y(a,t);v===null&&(v=c),s.push(c)}}});if(!u&&f.platform.dom.localName(a)!=="parallel"){var A=f.platform.dom.hasAttribute(a,"initial"),C=function(a){var b=f.platform.dom.createElementNS(q,e.SCXML_NS,"initial"),c=f.platform.dom.createElementNS(q,e.SCXML_NS,"transition");return f.platform.dom.setAttribute(c,"target",a),f.platform.dom.appendChild(b,c),z(b)};A?C(f.platform.dom.getAttribute(a,"initial")):v&&C(v.id)}return m.onexit=o,m.onentry=p,m.transitions=r.map(function(a){return a.documentOrder}),m.children=s.map(function(a){return a.id}),m}function B(a){return A[a]=A[a]||0,""+z+"-"+a+"-"+A[a]++}function C(a,b){var c,d,e,f,g,h,i;e=[],a.ancestors.forEach(function(a){d=n[a],d.descendants.indexOf(b.id)>-1&&e.push(a)});if(!e.length)throw new Error("Could not find LCA for states.");return e[0]}var d=b("./code-gen"),e=b("../constants"),f=b("../../platform"),g=b("../scxml/state-kinds-enum"),h=["state","parallel","history","final","initial"],i=h.concat("scxml"),j,k,l,m,n,o,p,q,r=a.transformAndSerialize=r=function(a){return JSON.stringify(s(a))},s=a.transform=function(a){q=a;var b=q.documentElement;j=[],k=[],l={},m=[],n={},o=[],p={};var c=y(b,[]);return j.forEach(function(a){a.ancestors.reverse()}),j.forEach(function(a){a.descendants.reverse()}),m.filter(function(a){return a.targets}).forEach(function(a){var b=n[a.source],c=a.targets.map(function(a){var b=n[a];if(!b)throw new Error("Transition targets state id '"+a+"' but state does not exist.");return b});a.lca=C(b,c[0])}),{states:j,transitions:m,root:c.id,events:u(l),scripts:t(b),profile:f.platform.dom.getAttribute(b,"profile"),version:f.platform.dom.getAttribute(b,"version"),datamodel:p}},v=/^((([^.]+)\.)*([^.]+))(\.\*)?$/,z="$generated",A={};b.main===c&&console.log(JSON.stringify(s((new(b("xmldom").DOMParser)).parseFromString(b("fs").readFileSync(process.argv[2],"utf8"))),4,4))},"core/util/code-gen":function(a,b,c){"use strict";function f(a){return d.platform.dom.getElementChildren(a).map(g).join("\n;;\n")}function g(a){var b=h[d.platform.dom.namespaceURI(a)],c=b&&b[d.platform.dom.localName(a)];if(!b||!c)throw new Error("Element "+d.platform.dom.namespaceURI(a)+":"+d.platform.dom.localName(a)+" not yet supported");return c(a)}function i(a){return a?a.slice(-2)==="ms"?parseFloat(a.slice(0,-2)):a.slice(-1)==="s"?parseFloat(a.slice(0,-1))*1e3:parseFloat(a):0}function j(a){var b="var ",c=[];for(var d in a){var e=a[d];c.push(e?d+" = "+e:d)}return c.length?b+c.join(", ")+";":""}function k(a){var b=[];for(var c in a)b.push('"'+c+'" : {\n'+'"set" : function(v){ return '+c+" = v; },\n"+'"get" : function(){ return '+c+";}"+"\n}");return"{\n"+b.join(",\n")+"\n}"}function l(a,b){return"function(getData,setData,_events,$raise){var _event = _events[0];\n"+(b?"return":"")+" "+a+"\n}"}function m(a,b,c,d){return a+(b.length?b.join("\n"):"")+"return {\n"+"datamodel:"+c+","+"actions:[\n"+d.join(",\n")+"\n]"+"\n};"}function n(a){return"function($log,$cancel,$send,$origin,In,require){\n"+a+"\n}"}function o(a,b,c){var d=j(c),e=k(c),f=m(d,a,e,b),g=n(f);return g}function p(a){var b=d.platform.dom.hasAttribute(a,"namelist")?d.platform.dom.getAttribute(a,"namelist").trim().split(/ +/):null,c=d.platform.dom.getChildren(a).filter(function(a){return d.platform.dom.localName(a)==="param"}),e=d.platform.dom.getChildren(a).filter(function(a){return d.platform.dom.localName(a)==="content"});if(e.length)return e=e[0],d.platform.dom.getAttribute(e,"type")==="application/json"?d.platform.dom.textContent(e):JSON.stringify(d.platform.dom.textContent(e));if(d.platform.dom.hasAttribute(a,"contentexpr"))return d.platform.dom.getAttribute(a,"contentexpr");var f="{";return b&&b.forEach(function(a){f+='"'+a+'"'+":"+a+",\n"}),c.length&&c.map(function(a){return q(a)}).forEach(function(a){a.expr?f+='"'+a.name+'"'+":"+a.expr+",\n":a.location&&(f+='"'+a.name+'"'+":"+a.location+",\n")}),f+="}",f}function q(a){return{name:d.platform.dom.getAttribute(a,"name"),expr:d.platform.dom.getAttribute(a,"expr"),location:d.platform.dom.getAttribute(a,"location")}}var d=b("../../platform"),e=b("../constants"),h={"":{script:function(a){return d.platform.dom.textContent(a)},assign:function(a){return d.platform.dom.getAttribute(a,"location")+" = "+d.platform.dom.getAttribute(a,"expr")+";"},"if":function(a){var b="";b+="if("+d.platform.dom.getAttribute(a,"cond")+"){\n";var c=d.platform.dom.getElementChildren(a);for(var e=0;e<c.length;e++){var f=c[e];if(d.platform.dom.localName(f)==="elseif"||d.platform.dom.localName(f)==="else")break;b+=g(f)+"\n;;\n"}for(;e<c.length;e++){f=c[e];if(d.platform.dom.localName(f)==="elseif")b+="}else if("+d.platform.dom.getAttribute(f,"cond")+"){\n";else{if(d.platform.dom.localName(f)==="else"){b+="}";break}b+=g(f)+"\n;;\n"}}for(;e<c.length;e++)f=c[e],d.platform.dom.localName(f)==="else"?b+="else{\n":b+=g(f)+"\n;;\n";return b+="}",b},elseif:function(){throw new Error("Encountered unexpected elseif tag.")},"else":function(){throw new Error("Encountered unexpected else tag.")},log:function(a){var b=[];return d.platform.dom.hasAttribute(a,"label")&&b.push(JSON.stringify(d.platform.dom.getAttribute(a,"label"))),d.platform.dom.hasAttribute(a,"expr")&&b.push(d.platform.dom.getAttribute(a,"expr")),"$log("+b.join(",")+");"},raise:function(a){return"$raise("+JSON.stringify(d.platform.dom.getAttribute(a,"event"))+");"},cancel:function(a){return"$cancel("+JSON.stringify(d.platform.dom.getAttribute(a,"sendid"))+");"},send:function(a){return"$send({\ntarget: "+(d.platform.dom.hasAttribute(a,"targetexpr")?d.platform.dom.getAttribute(a,"targetexpr"):JSON.stringify(d.platform.dom.getAttribute(a,"target")))+",\n"+"name: "+(d.platform.dom.hasAttribute(a,"eventexpr")?d.platform.dom.getAttribute(a,"eventexpr"):JSON.stringify(d.platform.dom.getAttribute(a,"event")))+",\n"+"type: "+(d.platform.dom.hasAttribute(a,"typeexpr")?d.platform.dom.getAttribute(a,"typeexpr"):JSON.stringify(d.platform.dom.getAttribute(a,"type")))+",\n"+"data: "+p(a)+",\n"+"origin: $origin\n"+"}, {\n"+"delay: "+(d.platform.dom.hasAttribute(a,"delayexpr")?d.platform.dom.getAttribute(a,"delayexpr"):i(d.platform.dom.getAttribute(a,"delay")))+",\n"+"sendId: "+(d.platform.dom.hasAttribute(a,"idlocation")?d.platform.dom.getAttribute(a,"idlocation"):JSON.stringify(d.platform.dom.getAttribute(a,"id")))+"\n"+"});"},foreach:function(a){var b=d.platform.dom.hasAttribute(a,"index"),c=d.platform.dom.getAttribute(a,"index")||"$i",e=d.platform.dom.getAttribute(a,"item"),f=d.platform.dom.getAttribute(a,"array"),h=d.platform.dom.getElementChildren(a).map(g).join("\n;;\n");return"(function(){\nif(Array.isArray("+f+")){\n"+f+".forEach(function("+e+","+c+"){\n"+h+"\n});\n"+"}else{\n"+"Object.keys("+f+").forEach(function("+c+"){\n"+e+" = "+f+"["+c+"];\n"+h+"\n});\n"+"}\n"+"})();"}}};h[e.SCXML_NS]=h[""],c.exports={gen:{parentToFnBody:f,actionTagToFnBody:g,actionTags:h,util:{makeDatamodelDeclaration:j,makeDatamodelClosures:k,wrapFunctionBodyInDeclaration:l,makeTopLevelFunctionBody:m,wrapTopLevelFunctionBodyInDeclaration:n,makeActionFactory:o}}}},"core/util/docToModel":function(a,b,c){"use strict";function g(a,b,c){f.platform.getResourceFromUrl?i(a,b,function(d){d&&f.platform.log("Errors downloading src attributes",d),h(b,a,c)}):h(b,a,c)}function h(a,b,c){try{var f=d.transform(a),g=e(f,b);c(null,g)}catch(h){c(h)}}function i(a,b,c){function g(){var b=d.pop();if(b){var h=f.platform.dom.getAttribute(b,"src");if(a){var i=f.platform.url.getPathFromUrl(a),j=f.platform.path.dirname(i),k=f.platform.path.join(j,h);h=f.platform.url.changeUrlPath(a,k)}f.platform.getResourceFromUrl(h,function(a,c){a?(f.platform.log("Error downloading document "+h+" : "+a.message),e.push(a)):f.platform.dom.textContent(b,c),g()})}else c(e.length?e:null)}var d=[],e=[];j(b.documentElement,d),g()}function j(a,b){(f.platform.dom.localName(a)==="script"||f.platform.dom.localName(a)==="data")&&f.platform.dom.hasAttribute(a,"src")&&b.push(a),f.platform.dom.getElementChildren(a).forEach(function(a){j(a,b)})}var d=b("./annotate-scxml-json"),e=b("../scxml/json2model"),f=b("../../platform");c.exports=g},"core/util/util":function(a,b,c){"use strict";c.exports={merge:function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b];for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}return a}}},"embedded/dom":function(a,b,c){"use strict";c.exports={getChildren:function(a){return Array.prototype.slice.call(a.childNodes)},localName:function(a){return a.localName},getAttribute:function(a,b){return a.getAttribute(b)},hasAttribute:function(a,b){return a.hasAttribute(b)},namespaceURI:function(a){return a.namespaceURI},createElementNS:function(a,b,c){return a.createElementNS(b,c)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},appendChild:function(a,b){return a.appendChild(b)},textContent:function(a,b){if(b===undefined)return a.nodeType===1?a.textContent:a.nodeType===3||a.nodeType===4?a.data:"";if(a.nodeType===1)return a.textContent=b;if(a.nodeType===3)return a.data=b},getElementChildren:function(a){return this.getChildren(a).filter(function(a){return a.nodeType===1})}}},"embedded/path":function(a,b,c){"use strict";c.exports={sep:"/",join:function(a,b){return a+"/"+b},dirname:function(a){return a.split(this.sep).slice(0,-1).join(this.sep)},basename:function(a,b){var c=a.split(this.sep).slice(-1);if(b){var d=this.extname(c);d[1]===b&&(c=d[1])}return c},extname:function(a){return a.split(/\\.(?=[^\\.]+$)/)[1]}}},"embedded/platform":function(exports,require,module){"use strict";function parseDocumentFromString(a){var b=require("../../external/xmldom/dom-parser");return(new b.DOMParser).parseFromString(a)}exports.platform={parseDocumentFromString:parseDocumentFromString,eval:function(content,name){return eval("(function(){\nreturn "+content+";})()")},path:require("./path"),url:require("./url"),dom:require("./dom")}},"embedded/url":function(a,b,c){"use strict";function d(a){if(typeof Uri===undefined)throw new Error("URI parser not loaded");return new Uri(url)}c.exports={getPathFromUrl:function(a){return d(a).path()},changeUrlPath:function(a,b){return d(a).path(b).toString()}}},platform:function(a,b,c){"use strict";function d(){return typeof Packages!="undefined"}function e(){return typeof process!="undefined"&&typeof c!="undefined"}function f(){return typeof window!="undefined"&&typeof document!="undefined"}var g;f()?c.exports=b("./browser/platform"):e()?c.exports=b("./node/platform"):d()?c.exports=b("./rhino/platform"):c.exports=b("./embedded/platform")},scion:function(a,b,c){"use strict";function g(a,b){if(!d.platform.getDocumentFromUrl)throw new Error("Platform does not support getDocumentFromUrl");d.platform.getDocumentFromUrl(a,function(c,d){c?b(c,null):f(a,d,b)})}function h(a,b){if(!d.platform.getDocumentFromFilesystem)throw new Error("Platform does not support getDocumentFromFilesystem");d.platform.getDocumentFromFilesystem(a,function(c,d){c?b(c,null):f(a,d,b)})}function i(a,b){if(!d.platform.parseDocumentFromString)throw new Error("Platform does not support parseDocumentFromString");f(null,d.platform.parseDocumentFromString(a),b)}var d=b("./platform"),e=b("./core/scxml/SCXML"),f=b("./core/util/docToModel"),j=c.exports={pathToModel:h,urlToModel:g,documentStringToModel:i,documentToModel:f,SCXML:e.SimpleInterpreter,ext:{platformModule:d,actionCodeGeneratorModule:b("./core/util/code-gen")}}}});
+(function(){var a={},b={},c=function(f,g){var h=d(g,f),i=b[h],j;if(i)return i.exports;if(!(j=a[h]||a[h=d(h,"./index")]))throw"module '"+f+"' not found";i={id:h,exports:{}};try{return b[h]=i,j(i.exports,function(a){return c(a,e(h))},i),i.exports}catch(k){throw delete b[h],k}},d=function(a,b){var c=[],d,e;/^\.\.?(\/|$)/.test(b)?d=[a,b].join("/").split("/"):d=b.split("/");for(var f=0,g=d.length;f<g;f++)e=d[f],e==".."?c.pop():e!="."&&e!=""&&c.push(e);return c.join("/")},e=function(a){return a.split("/").slice(0,-1).join("/")};return function(b){for(var d in b)a[d]=b[d];typeof define=="function"&&define.amd?define([],function(){return c("scion","")}):(this.scion=c("scion",""),this.require||(this.require=function(a){return c(a,"")}))}}).call(this)({"base-platform/dom":function(a,b,c){"use strict",c.exports={getChildren:function(a){return Array.prototype.slice.call(a.childNodes)},localName:function(a){return a.localName},getAttribute:function(a,b){return a.getAttribute(b)},hasAttribute:function(a,b){return a.hasAttribute(b)},namespaceURI:function(a){return a.namespaceURI},createElementNS:function(a,b,c){return a.createElementNS(b,c)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},appendChild:function(a,b){return a.appendChild(b)},textContent:function(a,b){if(b===undefined)return a.nodeType===1?a.textContent!==undefined?a.textContent:this.getChildren(a).map(function(a){return this.textContent(a)},this).join(""):a.nodeType===3||a.nodeType===4?a.data:"";if(a.nodeType===1){if(a.textContent!==undefined)return a.textContent=b;var c=a.ownerDocument.createTextNode(b);return a.appendChild(c),b}if(a.nodeType===3)return a.data=b},getElementChildren:function(a){return this.getChildren(a).filter(function(a){return a.nodeType===1})}}},"base-platform/eval":function(exports,require,module){module.exports=function(content,name){return eval("(function(){\nreturn "+content+";})()")}},"base-platform/path":function(a,b,c){"use strict",c.exports={sep:"/",join:function(a,b){return a+"/"+b},dirname:function(a){return a.split(this.sep).slice(0,-1).join(this.sep)},basename:function(a,b){var c=a.split(this.sep).slice(-1);if(b){var d=this.extname(c);d[1]===b&&(c=d[1])}return c},extname:function(a){return a.split(/\\.(?=[^\\.]+$)/)[1]}}},"browser/browser-listener-client":function(a,b,c){},"browser/dom":function(a,b,c){function e(a,b){return"item"in a?a.item(b):a[b]}"use strict";var d=b("../base-platform/dom"),f=Object.create(d);f.hasAttribute=function(a,b){return a.hasAttribute?a.hasAttribute(b):a.getAttribute(b)},f.localName=function(a){return a.localName||a.tagName},f.createElementNS=function(a,b,c){return a.createElementNS?a.createElementNS(b,c):a.createElement(c)},f.getChildren=function(a){var b=[];for(var c=0;c<a.childNodes.length;c++)b.push(e(a.childNodes,c));return b},f.serializeToString=function(a){return a.xml||(new XMLSerializer).serializeToString(a)},c.exports=f},"browser/platform":function(a,b,c){"use strict";var d=b("../core/util/util");a.platform={ajax:window.jQuery,eval:b("../base-platform/eval"),getDocumentFromUrl:function(a,b,c){this.ajax.get(a,function(a){b(null,a)},"xml").error(function(a){b(a)})},parseDocumentFromString:function(a){return(new window.DOMParser).parseFromString(a,"application/xml")},getDocumentFromFilesystem:function(a,b,c){this.getDocumentFromUrl(a,b,c)},getResourceFromUrl:function(a,b,c){this.ajax.get(a,function(a){b(null,a)}).error(function(a){b(a)})},postDataToUrl:function(a,b,c){this.ajax.post(a,b,function(a){c(null,a)}).error(function(a){c(a)})},setTimeout:function(a,b){return window.setTimeout(a,b)},clearTimeout:function(a){window.clearTimeout(a)},log:window.console&&window.console.log&&(window.console.log.bind?window.console.log.bind(window.console):window.console.log),path:b("../base-platform/path"),url:b("./url"),dom:b("./dom")}},"browser/url":function(a,b,c){function d(a){var b=document.createElement("a");return b.href=a,b}"use strict",c.exports={getPathFromUrl:function(a){var b=d(a);return b.pathname},changeUrlPath:function(a,b){var c=d(a);return c.protocol+"//"+c.hostname+":"+c.port+b}}},"core/constants":function(a,b,c){"use strict",c.exports={SCXML_NS:"http://www.w3.org/2005/07/scxml"}},"core/scxml/SCXML":function(a,b,c){function i(a){return function(a){var b=a[0],c=a[1];return b.source.depth<c.source.depth?c:c.source.depth<b.source.depth?b:b.documentOrder<c.documentOrder?b:c}}function k(a,b){this.model=a,this.opts=b,this.opts.log=this.opts.log||h.platform.log,this.opts.StateIdSet=this.opts.StateIdSet||d,this.opts.EventSet=this.opts.EventSet||d,this.opts.TransitionPairSet=this.opts.TransitionPairSet||d,this.opts.priorityComparisonFn=this.opts.priorityComparisonFn||i(this.opts.model),this._sessionid=this.opts.sessionid||"",this._configuration=new this.opts.BasicStateSet,this._historyValue={},this._innerEventQueue=[],this._isInFinalState=!1,this._timeoutMap={},this._listeners=[]}function l(a,b){b=b||{},f(b),this._isStepping=!1,this._send=b.send||this._send,this._cancel=b.cancel||this._cancel,k.call(this,a,b)}"use strict";var d=b("./set/ArraySet"),e=b("./state-kinds-enum"),f=b("./setup-default-opts"),g=b("./scxml-dynamic-name-match-transition-selector"),h=b("../../platform"),j=!1;k.prototype={start:function(){j&&h.platform.log("performing initial big step"),this._configuration.add(this.model.root.initial);var a=this.opts.require||c.parent&&c.parent.parent&&c.parent.parent.require&&c.parent.parent.require.bind(c.parent.parent)||b.main&&b.main.require&&b.main.require.bind(b.main)||b,d=this.model.actionFactory(this.opts.log,this._cancel.bind(this),this._send.bind(this),this.opts.origin,this.isIn.bind(this),a,h.platform.parseDocumentFromString,this._sessionid);return this._actions=d.actions,this._datamodel=d.datamodel,this._performBigStep(),this.getConfiguration()},_getOrSetData:function(a,b,c){var d=this._datamodel[b];if(!d)throw new Error("Variable "+b+" not declared in datamodel.");return d[a](c)},_getData:function(a){return this._getOrSetData("get",a)},_setData:function(a,b){return this._getOrSetData("set",a,b)},getConfiguration:function(){return this._configuration.iter().map(function(a){return a.id})},getFullConfiguration:function(){return this._configuration.iter().map(function(a){return[a].concat(this.opts.model.getAncestors(a))},this).reduce(function(a,b){return a.concat(b)},[]).map(function(a){return a.id}).reduce(function(a,b){return a.indexOf(b)>-1?a:a.concat(b)},[])},isIn:function(a){return this.getFullConfiguration().indexOf(a)>-1},isFinal:function(a){return this._isInFinalState},_performBigStep:function(a){a&&this._innerEventQueue.push(new this.opts.EventSet([a]));var b=!0;while(b){var c=this._innerEventQueue.length?this._innerEventQueue.shift():new this.opts.EventSet,d={},f=this._performSmallStep(c,d);b=!f.isEmpty()}this._isInFinalState=this._configuration.iter().every(function(a){return a.kind===e.FINAL})},_performSmallStep:function(a,b){j&&h.platform.log("selecting transitions with eventSet: ",a);var c=this._selectTransitions(a,b);j&&h.platform.log("selected transitions: ",c);if(!c.isEmpty()){j&&h.platform.log("sorted transitions: ",console.log(c));var d=new this.opts.TransitionSet(c.iter().filter(function(a){return a.targets})),f=this._getStatesExited(d),g=f[0],i=f[1],k=this._getStatesEntered(d),l=k[0],m=k[1];j&&h.platform.log("basicStatesExited ",g),j&&h.platform.log("basicStatesEntered ",l),j&&h.platform.log("statesExited ",i),j&&h.platform.log("statesEntered ",m);var n=new this.opts.EventSet;j&&h.platform.log("executing state exit actions"),i.forEach(function(c){(j||this.opts.logStatesEnteredAndExited)&&h.platform.log("exiting ",c.id),this._listeners.forEach(function(a){a.onExit&&a.onExit(c.id)}),c.onexit!==undefined&&this._evaluateAction(c.onexit,a,b,n);var d;c.history&&(c.history.isDeep?d=function(a){return a.kind===e.BASIC&&c.descendants.indexOf(a)>-1}:d=function(a){return a.parent===c},this._historyValue[c.history.id]=i.filter(d))},this);var o=c.iter().sort(function(a,b){return a.documentOrder-b.documentOrder});j&&h.platform.log("executing transitition actions"),o.forEach(function(c){var d=c.targets&&c.targets.map(function(a){return a.id});this._listeners.forEach(function(a){a.onTransition&&a.onTransition(c.source.id,d)}),c.actions!==undefined&&this._evaluateAction(c.actions,a,b,n)},this),j&&h.platform.log("executing state enter actions"),m.forEach(function(c){(j||this.opts.logStatesEnteredAndExited)&&h.platform.log("entering",c.id),this._listeners.forEach(function(a){a.onEntry&&a.onEntry(c.id)}),c.onentry!==undefined&&this._evaluateAction(c.onentry,a,b,n)},this),j&&h.platform.log("updating configuration "),j&&h.platform.log("old configuration ",this._configuration),this._configuration.difference(g),this._configuration.union(l),j&&h.platform.log("new configuration ",this._configuration),n.isEmpty()||(j&&h.platform.log("adding triggered events to inner queue ",n),this._innerEventQueue.push(n)),j&&h.platform.log("updating datamodel for next small step :");for(var p in b)this._setData(p,b[p])}return c},_evaluateAction:function(a,b,c,d){function e(a){d.add(a)}var f=this._getScriptingInterface(c,b,!0);return this._actions[a].call(this.opts.evaluationContext,f.getData,f.setData,f.events,e)},_getScriptingInterface:function(a,b,c){return{setData:c?function(b,c){return a[b]=c}:function(){},getData:this._getData.bind(this),events:b.iter()}},_getStatesExited:function(a){var b=new this.opts.StateSet,c=new this.opts.BasicStateSet;a.iter().forEach(function(a){var d=a.scope,e=d.descendants;this._configuration.iter().forEach(function(a){e.indexOf(a)>-1&&(c.add(a),b.add(a),this.opts.model.getAncestors(a,d).forEach(function(a){b.add(a)}))},this)},this);var d=b.iter().sort(function(a,b){return b.depth-a.depth});return[c,d]},_getStatesEntered:function(a){var b={statesToEnter:new this.opts.StateSet,basicStatesToEnter:new this.opts.BasicStateSet,statesProcessed:new this.opts.StateSet,statesToProcess:[]};a.iter().forEach(function(a){a.targets.forEach(function(c){this._addStateAndAncestors(c,a.scope,b)},this)},this);var c;while(c=b.statesToProcess.pop())this._addStateAndDescendants(c,b);var d=b.statesToEnter.iter().sort(function(a,b){return a.depth-b.depth});return[b.basicStatesToEnter,d]},_addStateAndAncestors:function(a,b,c){this._addStateAndDescendants(a,c),this.opts.model.getAncestors(a,b).forEach(function(a){a.kind===e.COMPOSITE?(c.statesToEnter.add(a),c.statesProcessed.add(a)):this._addStateAndDescendants(a,c)},this)},_addStateAndDescendants:function(a,b){if(b.statesProcessed.contains(a))return;a.kind===e.HISTORY?a.id in this._historyValue?this._historyValue[a.id].forEach(function(c){this._addStateAndAncestors(c,a.parent,b)},this):(b.statesToEnter.add(a),b.basicStatesToEnter.add(a)):(b.statesToEnter.add(a),a.kind===e.PARALLEL?b.statesToProcess.push.apply(b.statesToProcess,a.children.filter(function(a){return a.kind!==e.HISTORY})):a.kind===e.COMPOSITE?b.statesToProcess.push(a.initial):(a.kind===e.INITIAL||a.kind===e.BASIC||a.kind===e.FINAL)&&b.basicStatesToEnter.add(a)),b.statesProcessed.add(a)},_selectTransitions:function(a,b){if(this.opts.onlySelectFromBasicStates)var c=this._configuration.iter();else{var d=new this.opts.StateSet;this._configuration.iter().forEach(function(a){d.add(a),this.opts.model.getAncestors(a).forEach(function(a){d.add(a)})},this),c=d.iter()}var e=this._getScriptingInterface(b,a),f=function(a){return this._actions[a.conditionActionRef].call(this.opts.evaluationContext,e.getData,e.setData,e.events)}.bind(this),i=a.iter().map(function(a){return a.name}),k=i.filter(function(a){return a.search(".")}).length,l=k?g:this.opts.transitionSelector,m=new this.opts.TransitionSet;c.forEach(function(a){l(a,i,f).forEach(function(a){m.add(a)})});var n=this._selectPriorityEnabledTransitions(m);return j&&h.platform.log("priorityEnabledTransitions",n),n},_selectPriorityEnabledTransitions:function(a){var b=new this.opts.TransitionSet,c=this._getInconsistentTransitions(a),d=c[0],e=c[1];b.union(d),j&&h.platform.log("enabledTransitions",a),j&&h.platform.log("consistentTransitions",d),j&&h.platform.log("inconsistentTransitionsPairs",e),j&&h.platform.log("priorityEnabledTransitions",b);while(!e.isEmpty())a=new this.opts.TransitionSet(e.iter().map(function(a){return this.opts.priorityComparisonFn(a)},this)),c=this._getInconsistentTransitions(a),d=c[0],e=c[1],b.union(d),j&&h.platform.log("enabledTransitions",a),j&&h.platform.log("consistentTransitions",d),j&&h.platform.log("inconsistentTransitionsPairs",e),j&&h.platform.log("priorityEnabledTransitions",b);return b},_getInconsistentTransitions:function(a){var b=new this.opts.TransitionSet,c=new this.opts.TransitionPairSet,d=a.iter();j&&h.platform.log("transitions",d);for(var e=0;e<d.length;e++)for(var f=e+1;f<d.length;f++){var g=d[e],i=d[f];this._conflicts(g,i)&&(b.add(g),b.add(i),c.add([g,i]))}var k=a.difference(b);return[k,c]},_conflicts:function(a,b){return!this._isArenaOrthogonal(a,b)},_isArenaOrthogonal:function(a,b){var c=this.opts.model.isOrthogonalTo(a.scope,b.scope);return j&&(h.platform.log("transition scopes",a.scope.id,a.scope.id),h.platform.log("transition scopes are orthogonal?",c)),c},registerListener:function(a){return this._listeners.push(a)},unregisterListener:function(a){return this._listeners.splice(this._listeners.indexOf(a),1)}},l.prototype=Object.create(k.prototype),l.prototype.gen=function(a,b){var c;switch(typeof a){case"string":c={name:a,data:b};break;case"object":if(typeof a.name!="string")throw new Error('Event object must have "name" property of type string.');c=a;break;default:throw new Error("First argument to gen must be a string or object.")}if(this._isStepping)throw new Error("gen called before previous call to gen could complete. If executed in single-threaded environment, this means it was called recursively, which is illegal, as it would break SCION step semantics.");return this._isStepping=!0,this._performBigStep(c),this._isStepping=!1,this.getConfiguration()},l.prototype._send=function(a,b){var c,d,e=this;if(!h.platform.setTimeout)throw new Error("setTimeout function not set");j&&h.platform.log("sending event",a.name,"with content",a.data,"after delay",b.delay),c=function(){return e.gen(a)},d=h.platform.setTimeout(c,b.delay);if(b.sendid)return this._timeoutMap[b.sendid]=d},l.prototype._cancel=function(a){if(!h.platform.clearTimeout)throw new Error("clearTimeout function not set");if(a in this._timeoutMap)return j&&h.platform.log("cancelling ",a," with timeout id ",this._timeoutMap[a]),h.platform.clearTimeout(this._timeoutMap[a])},c.exports={SCXMLInterpreter:k,SimpleInterpreter:l}},"core/scxml/default-transition-selector":function(a,b,c){"use strict",c.exports=function(a,b,c){return a.transitions.filter(function(a){return!a.event||b.indexOf(a.event)>-1&&(!a.cond||c(a))})}},"core/scxml/json2model":function(a,b,c){function f(a){function b(a,b){return d.push(e.gen.util.wrapFunctionBodyInDeclaration(a,b))-1}function c(a){return f[a]}var d=[],f={};a.states.forEach(function(a){f[a.id]=a}),a.transitions.forEach(function(a){a.cond&&(a.conditionActionRef=b(a.cond,!0))}),a.states.forEach(function(d){d.transitions=d.transitions.map(function(b){return a.transitions[b]});var e=[];d.onentry&&(d.onentry=b(d.onentry)),d.onexit&&(d.onexit=b(d.onexit)),d.transitions.forEach(function(a){a.actions&&(a.actions=b(a.actions)),a.lcca&&(a.lcca=f[a.lcca]),a.scope=f[a.scope]}),d.initial=f[d.initial],d.history=f[d.history],d.children=d.children.map(c),d.parent=f[d.parent],d.ancestors&&(d.ancestors=d.ancestors.map(c)),d.descendants&&(d.descendants=d.descendants.map(c)),d.transitions.forEach(function(a){a.source=f[a.source],a.targets=a.targets&&a.targets.map(c)})}),a.root=f[a.root];var g=e.gen.util.makeActionFactory(a.scripts,d,a.datamodel);return g}function g(a,b){var c=f(a);try{a.actionFactory=d.platform.eval(c,b)}catch(e){throw d.platform.log("Failed to evaluate action factory."),d.platform.log("Generated js code to evaluate\n",c),e}}"use strict";var d=b("../../platform"),e=b("../util/code-gen");c.exports=function(a,b){return g(a,b),a};if(b.main===c){var h=process.argv[2],i=function(a,b){if(a)throw a;process.stdout.write(f(JSON.parse(b)))};if(h==="-"){var j="";process.stdin.resume(),process.stdin.on("data",function(a){j+=a}),process.stdin.on("end",function(a){i(null,j)})}else{var k=b("fs");k.readFile(h,"utf8",i)}}},"core/scxml/model":function(a,b,c){"use strict";var d=b("./state-kinds-enum"),e={getAncestors:function(a,b){var c,d,e;return d=a.ancestors.indexOf(b),d>-1?a.ancestors.slice(0,d):a.ancestors},getAncestorsOrSelf:function(a,b){return[a].concat(this.getAncestors(a,b))},getDescendantsOrSelf:function(a){return[a].concat(a.descendants)},isOrthogonalTo:function(a,b){return!this.isAncestrallyRelatedTo(a,b)&&this.getLCA(a,b).kind===d.PARALLEL},isAncestrallyRelatedTo:function(a,b){return this.getAncestorsOrSelf(b).indexOf(a)>-1||this.getAncestorsOrSelf(a).indexOf(b)>-1},getLCA:function(a,b){var c=this.getAncestors(a).filter(function(a){return a.descendants.indexOf(b)>-1},this);return c[0]}};c.exports=e},"core/scxml/scxml-dynamic-name-match-transition-selector":function(a,b,c){function e(a){return new RegExp("^"+a.replace(/\./g,"\\.")+"(\\.[0-9a-zA-Z]+)*$")}function f(a){return d[a]?d[a]:d[a]=e(a)}function g(a,b){var c=a.events,d=c.indexOf("*")>-1?function(){return!0}:function(a){return c.filter(function(b){return f(b).test(a)}).length};return b.filter(d).length}"use strict";var d={};c.exports=function(a,b,c){return a.transitions.filter(function(a){return(!a.events||g(a,b))&&(!a.cond||c(a))})}},"core/scxml/set/ArraySet":function(a,b,c){function d(a){a=a||[],this.o=[],a.forEach(function(a){this.add(a)},this)}"use strict",d.prototype={add:function(a){if(!this.contains(a))return this.o.push(a)},remove:function(a){var b=this.o.indexOf(a);return b===-1?!1:(this.o.splice(b,1),!0)},union:function(a){return a=a.iter?a.iter():a,a.forEach(function(a){this.add(a)},this),this},difference:function(a){return a=a.iter?a.iter():a,a.forEach(function(a){this.remove(a)},this),this},contains:function(a){return this.o.indexOf(a)>-1},iter:function(){return this.o},isEmpty:function(){return!this.o.length},equals:function(a){var b=a.iter(),c=this.o;return c.every(function(a){return b.indexOf(a)>-1})&&b.every(function(a){return c.indexOf(a)>-1})},toString:function(){return"Set("+this.o.toString()+")"}},c.exports=d},"core/scxml/setup-default-opts":function(a,b,c){"use strict";var d=b("./scxml-dynamic-name-match-transition-selector"),e=b("./set/ArraySet"),f=b("./model");c.exports=function(a){return a=a||{},a.TransitionSet=a.TransitionSet||e,a.StateSet=a.StateSet||e,a.BasicStateSet=a.BasicStateSet||e,a.transitionSelector=a.transitionSelector||d,a.model=a.model||f,a}},"core/scxml/state-kinds-enum":function(a,b,c){"use strict",c.exports={BASIC:0,COMPOSITE:1,PARALLEL:2,HISTORY:3,INITIAL:4,FINAL:5}},"core/util/annotate-scxml-json":function(a,b,c){function t(a){return f.platform.dom.getChildren(a).filter(function(a){return f.platform.dom.localName(a)==="script"}).map(function(a){return f.platform.dom.textContent(a)})}function u(a){var b,c,d;c=0,d={};for(b in a)d[b]={name:b,documentOrder:c++};return d}function w(a,b){if(f.platform.dom.hasAttribute(a,"event")){var c,e=f.platform.dom.getAttribute(a,"event");e==="*"?c=[e]:c=e.trim().split(/\s+/).map(function(a){var b=a.match(v);if(b){var c=b[1];if(!b||!c)throw new Error("Unable to parse event: "+a);return c}}),c.filter(function(a){return a!=="*"}).forEach(function(a){l[a]=!0});if(c.indexOf(undefined)>-1)throw new Error("Error parsing event attribute attributes.event")}var g={internal:f.platform.dom.getAttribute(a,"type")==="internal",documentOrder:m.length,id:m.length,source:b.id,cond:f.platform.dom.getAttribute(a,"cond"),events:c,targets:f.platform.dom.hasAttribute(a,"target")?f.platform.dom.getAttribute(a,"target").trim().split(/\s+/):null};return f.platform.dom.getElementChildren(a).length&&(g.actions=d.gen.parentToFnBody(a)),m.push(g),g}function x(a,b){f.platform.dom.getChildren(a).filter(function(a){return f.platform.dom.localName(a)==="data"}).forEach(function(a){if(f.platform.dom.hasAttribute(a,"id")){var b,c=f.platform.dom.getAttribute(a,"id");if(f.platform.dom.hasAttribute(a,"expr"))b={content:f.platform.dom.getAttribute(a,"expr"),type:"expr"};else{var d=f.platform.dom.hasAttribute(a,"type");if(d){var e=f.platform.dom.getAttribute(a,"type"),g=e==="xml"?f.platform.dom.serializeToString(a):f.platform.dom.textContent(a);b={content:g,type:e}}else g=f.platform.dom.textContent(a),b=g.length?{content:g,type:"text"}:null}p[c]=b}})}function y(a,b){var c=f.platform.dom.hasAttribute(a,"id")?f.platform.dom.getAttribute(a,"id"):B(f.platform.dom.localName(a)),l;switch(f.platform.dom.localName(a)){case"state":f.platform.dom.getChildren(a).filter(function(a){return i.indexOf(f.platform.dom.localName(a))>-1}).length?l=g.COMPOSITE:l=g.BASIC;break;case"scxml":l=g.COMPOSITE;break;case"initial":l=g.INITIAL;break;case"parallel":l=g.PARALLEL;break;case"final":l=g.FINAL;break;case"history":l=g.HISTORY;break;default:}var m={id:c,kind:l,descendants:[]};n[c]=m,b.length&&(m.parent=b[b.length-1]),l===g.HISTORY&&(m.isDeep=f.platform.dom.getAttribute(a,"type")==="deep"?!0:!1),m.documentOrder=j.length,j.push(m);if(l===g.BASIC||l===g.INITIAL||l===g.HISTORY)m.basicDocumentOrder=k.length,k.push(m);m.depth=b.length,m.ancestors=b.slice(),b.forEach(function(a){n[a].descendants.push(m.id)});var o,p,r=[],s=[],t=b.concat(m.id),u=!1,v=null,z=function(a){var b=y(a,t);return m.initial=b.id,s.push(b),u=!0};f.platform.dom.getElementChildren(a).forEach(function(a){switch(f.platform.dom.localName(a)){case"transition":r.push(w(a,m));break;case"onentry":p=d.gen.parentToFnBody(a);break;case"onexit":o=d.gen.parentToFnBody(a);break;case"initial":if(!!u)throw new Error("Encountered duplicate initial states in state "+m.id);z(a);break;case"history":var b=y(a,t);m.history=b.id,s.push(b);break;case"datamodel":x(a,t);break;default:if(h.indexOf(f.platform.dom.localName(a))>-1){var c=y(a,t);v===null&&(v=c),s.push(c)}}});if(!u&&f.platform.dom.localName(a)!=="parallel"){var A=f.platform.dom.hasAttribute(a,"initial"),C=function(a){var b=f.platform.dom.createElementNS(q,e.SCXML_NS,"initial"),c=f.platform.dom.createElementNS(q,e.SCXML_NS,"transition");return f.platform.dom.setAttribute(c,"target",a),f.platform.dom.appendChild(b,c),z(b)};A?C(f.platform.dom.getAttribute(a,"initial")):v&&C(v.id)}return m.onexit=o,m.onentry=p,m.transitions=r.map(function(a){return a.documentOrder}),m.children=s.map(function(a){return a.id}),m}function B(a){return A[a]=A[a]||0,""+z+"-"+a+"-"+A[a]++}function C(a,b){var c,d,e;e=[],a.ancestors.forEach(function(a){d=n[a],d.kind===g.COMPOSITE&&d.descendants.indexOf(b.id)>-1&&e.push(a)});if(!e.length)throw new Error("Could not find LCCA for states.");return e[0]}function D(a){var b=n[a.source],c=a.internal&&b.parent&&a.targets&&a.targets.map(function(a){return n[a]}).every(function(a){return b.descendants.map(function(a){return n[a]}).indexOf(a)>-1});return a.targets?c?a.source:a.lcca:a.source}"use strict";var d=b("./code-gen"),e=b("../constants"),f=b("../../platform"),g=b("../scxml/state-kinds-enum"),h=["state","parallel","history","final","initial"],i=h.concat("scxml"),j,k,l,m,n,o,p,q,r=a.transformAndSerialize=r=function(a){return JSON.stringify(s(a))},s=a.transform=function(a){q=a;var b=q.documentElement;j=[],k=[],l={},m=[],n={},o=[],p={};var c=y(b,[]);return j.forEach(function(a){a.ancestors.reverse()}),j.forEach(function(a){a.descendants.reverse()}),m.filter(function(a){return a.targets}).forEach(function(a){var b=n[a.source],c=a.targets.map(function(a){var b=n[a];if(!b)throw new Error("Transition targets state id '"+a+"' but state does not exist.");return b});a.lcca=C(b,c[0])}),m.forEach(function(a){a.scope=D(a)}),{states:j,transitions:m,root:c.id,events:u(l),scripts:t(b),profile:f.platform.dom.getAttribute(b,"profile"),version:f.platform.dom.getAttribute(b,"version"),datamodel:p}},v=/^((([^.]+)\.)*([^.]+))(\.\*)?$/,z="$generated",A={};b.main===c&&console.log(JSON.stringify(s((new(b("xmldom").DOMParser)).parseFromString(b("fs").readFileSync(process.argv[2],"utf8"))),4,4))},"core/util/code-gen":function(a,b,c){function f(a){return d.platform.dom.getElementChildren(a).map(g).join("\n;;\n")}function g(a){var b=h[d.platform.dom.namespaceURI(a)],c=b&&b[d.platform.dom.localName(a)];if(!b||!c)throw new Error("Element "+d.platform.dom.namespaceURI(a)+":"+d.platform.dom.localName(a)+" not yet supported");return c(a)}function i(a){return a?a.slice(-2)==="ms"?parseFloat(a.slice(0,-2)):a.slice(-1)==="s"?parseFloat(a.slice(0,-1))*1e3:parseFloat(a):0}function j(a,b){var c=a;if(b){c+=" = ";switch(b.type){case"xml":c+="$parseXml("+JSON.stringify(b.content)+")";break;case"json":c+="JSON.parse("+JSON.stringify(b.content)+")";break;case"expr":c+=b.content;break;default:c+=JSON.stringify(b.content)}}return c}function k(a){var b="var ",c=[];for(var d in a){var e=a[d];c.push(j(d,e))}return c.length?b+c.join(", ")+";":""}function l(a){var b=[];for(var c in a)b.push('"'+c+'" : {\n'+'"set" : function(v){ return '+c+" = v; },\n"+'"get" : function(){ return '+c+";}"+"\n}");return"{\n"+b.join(",\n")+"\n}"}function m(a,b){return"function(getData,setData,_events,$raise){var _event = _events[0];\n"+(b?"return":"")+" "+a+"\n}"}function n(a,b,c,d){return a+(b.length?b.join("\n"):"")+"var $datamodel = "+c+";\n"+"return {\n"+"datamodel:$datamodel,\n"+"actions:[\n"+d.join(",\n")+"\n]"+"\n};"}function o(a){return"function($log,$cancel,$send,$origin,In,require,$parseXml,_sessionid,_ioprocessors,_x){\n"+a+"\n}"}function p(a,b,c){var d=k(c),e=l(c),f=i.toString()+"\n"+n(d,a,e,b),g=o(f);return g}function q(a){var b=d.platform.dom.hasAttribute(a,"namelist")?d.platform.dom.getAttribute(a,"namelist").trim().split(/ +/):null,c=d.platform.dom.getChildren(a).filter(function(a){return d.platform.dom.localName(a)==="param"}),e=d.platform.dom.getChildren(a).filter(function(a){return d.platform.dom.localName(a)==="content"});if(e.length)return e=e[0],d.platform.dom.getAttribute(e,"type")==="application/json"?d.platform.dom.textContent(e):JSON.stringify(d.platform.dom.textContent(e));if(d.platform.dom.hasAttribute(a,"contentexpr"))return d.platform.dom.getAttribute(a,"contentexpr");var f="{";return b&&b.forEach(function(a){f+='"'+a+'"'+":"+a+",\n"}),c.length&&c.map(function(a){return r(a)}).forEach(function(a){a.expr?f+='"'+a.name+'"'+":"+a.expr+",\n":a.location&&(f+='"'+a.name+'"'+":"+a.location+",\n")}),f+="}",f}function r(a){return{name:d.platform.dom.getAttribute(a,"name"),expr:d.platform.dom.getAttribute(a,"expr"),location:d.platform.dom.getAttribute(a,"location")}}"use strict";var d=b("../../platform"),e=b("../constants"),h={"":{script:function(a){return d.platform.dom.textContent(a)},assign:function(a){return d.platform.dom.getAttribute(a,"location")+" = "+d.platform.dom.getAttribute(a,"expr")+";"},"if":function(a){var b="";b+="if("+d.platform.dom.getAttribute(a,"cond")+"){\n";var c=d.platform.dom.getElementChildren(a);for(var e=0;e<c.length;e++){var f=c[e];if(d.platform.dom.localName(f)==="elseif"||d.platform.dom.localName(f)==="else")break;b+=g(f)+"\n;;\n"}for(;e<c.length;e++){f=c[e];if(d.platform.dom.localName(f)==="elseif")b+="}else if("+d.platform.dom.getAttribute(f,"cond")+"){\n";else{if(d.platform.dom.localName(f)==="else"){b+="}";break}b+=g(f)+"\n;;\n"}}for(;e<c.length;e++)f=c[e],d.platform.dom.localName(f)==="else"?b+="else{\n":b+=g(f)+"\n;;\n";return b+="}",b},elseif:function(){throw new Error("Encountered unexpected elseif tag.")},"else":function(){throw new Error("Encountered unexpected else tag.")},log:function(a){var b=[];return d.platform.dom.hasAttribute(a,"label")&&b.push(JSON.stringify(d.platform.dom.getAttribute(a,"label"))),d.platform.dom.hasAttribute(a,"expr")&&b.push(d.platform.dom.getAttribute(a,"expr")),"$log("+b.join(",")+");"},raise:function(a){return"$raise({ name:"+JSON.stringify(d.platform.dom.getAttribute(a,"event"))+", data : {}});"},cancel:function(a){return"$cancel("+JSON.stringify(d.platform.dom.getAttribute(a,"sendid"))+");"},send:function(a){var b=d.platform.dom.hasAttribute(a,"targetexpr")?d.platform.dom.getAttribute(a,"targetexpr"):JSON.stringify(d.platform.dom.getAttribute(a,"target")),c="_scionTargetRef",e="var "+c+" = "+b+";\n",f="{\ntarget: "+c+",\n"+"name: "+(d.platform.dom.hasAttribute(a,"eventexpr")?d.platform.dom.getAttribute(a,"eventexpr"):JSON.stringify(d.platform.dom.getAttribute(a,"event")))+",\n"+"type: "+(d.platform.dom.hasAttribute(a,"typeexpr")?d.platform.dom.getAttribute(a,"typeexpr"):JSON.stringify(d.platform.dom.getAttribute(a,"type")))+",\n"+"data: "+q(a)+",\n"+"origin: $origin\n"+"}",g=e+"if("+c+" === '#_internal'){\n"+"$raise("+f+");\n"+"}else{\n"+"$send("+f+", {\n"+"delay: "+(d.platform.dom.hasAttribute(a,"delayexpr")?"getDelayInMs("+d.platform.dom.getAttribute(a,"delayexpr")+")":i(d.platform.dom.getAttribute(a,"delay")))+",\n"+"sendId: "+(d.platform.dom.hasAttribute(a,"idlocation")?d.platform.dom.getAttribute(a,"idlocation"):JSON.stringify(d.platform.dom.getAttribute(a,"id")))+"\n"+"}, $raise);"+"}";return g},foreach:function(a){var b=d.platform.dom.hasAttribute(a,"index"),c=d.platform.dom.getAttribute(a,"index")||"$i",e=d.platform.dom.getAttribute(a,"item"),f=d.platform.dom.getAttribute(a,"array"),h=d.platform.dom.getElementChildren(a).map(g).join("\n;;\n");return"(function(){\nif(Array.isArray("+f+")){\n"+f+".forEach(function("+e+","+c+"){\n"+h+"\n});\n"+"}else{\n"+"Object.keys("+f+").forEach(function("+c+"){\n"+e+" = "+f+"["+c+"];\n"+h+"\n});\n"+"}\n"+"})();"}}};h[e.SCXML_NS]=h[""],c.exports={gen:{parentToFnBody:f,actionTagToFnBody:g,actionTags:h,util:{makeDatamodelDeclaration:k,makeDatamodelClosures:l,wrapFunctionBodyInDeclaration:m,makeTopLevelFunctionBody:n,wrapTopLevelFunctionBodyInDeclaration:o,makeActionFactory:p}}}},"core/util/docToModel":function(a,b,c){function g(a,b,c,d){f.platform.getResourceFromUrl?j(a,b,d,function(d){d?c(d.length===1?d[0].err:new Error("Script download errors : \n"+d.map(function(a){return a.url+": "+a.err.message}).join("\n"))):h(a,b,c)}):h(a,b,c)}function h(a,b,c){try{var f=d.transform(b),g=e(f,a);c(null,g)}catch(h){c(h)}}function i(a,b){var c;if(f.platform.url.resolve)c=f.platform.url.resolve(a,b);else{var d=f.platform.url.getPathFromUrl(a),e=f.platform.path.dirname(d),g=f.platform.path.join(e,b);c=f.platform.url.changeUrlPath(a,g)}return c}function j(a,b,c,d){var e=[],g=[],h=0;k(b.documentElement,e),e.length?e.forEach(function(b,j){var k=f.platform.dom.getAttribute(b,"src");a&&(k=i(a,k)),f.platform.getResourceFromUrl(k,function(a,c,i){a?(f.platform.log("Error downloading document "+k+" : "+a.message),g.push({url:k,err:a})):f.platform.dom.textContent(b,c),++h,h==e.length&&d(g.length?g:null)},c)}):d()}function k(a,b){(f.platform.dom.localName(a)==="script"||f.platform.dom.localName(a)==="data")&&f.platform.dom.hasAttribute(a,"src")&&b.push(a),f.platform.dom.getElementChildren(a).forEach(function(a){k(a,b)})}"use strict";var d=b("./annotate-scxml-json"),e=b("../scxml/json2model"),f=b("../../platform");c.exports=g},"core/util/util":function(a,b,c){"use strict",c.exports={merge:function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b];for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}return a}}},platform:function(a,b,c){function d(){return typeof Packages!="undefined"}function e(){return typeof process!="undefined"&&typeof c!="undefined"}function f(){return typeof window!="undefined"&&typeof document!="undefined"}"use strict";var g;f()?c.exports=b("./browser/platform"):e()?c.exports=b("./node/platform"):d()&&(c.exports=b("./rhino/platform"))},scion:function(a,b,c){function g(a,b,c){if(!d.platform.getDocumentFromUrl)throw new Error("Platform does not support getDocumentFromUrl");d.platform.getDocumentFromUrl(a,function(d,e){d?b(d,null):f(a,e,b,c)},c)}function h(a,b,c){if(!d.platform.getDocumentFromFilesystem)throw new Error("Platform does not support getDocumentFromFilesystem");d.platform.getDocumentFromFilesystem(a,function(d,e){d?b(d,null):f(a,e,b,c)},c)}function i(a,b,c){if(!d.platform.parseDocumentFromString)throw new Error("Platform does not support parseDocumentFromString");f(null,d.platform.parseDocumentFromString(a),b,c)}"use strict";var d=b("./platform"),e=b("./core/scxml/SCXML"),f=b("./core/util/docToModel"),j=c.exports={pathToModel:h,urlToModel:g,documentStringToModel:i,documentToModel:f,SCXML:e.SimpleInterpreter,ext:{platformModule:d,actionCodeGeneratorModule:b("./core/util/code-gen")}}}});
View
984 builds/latest/scion.js
@@ -1,54 +1,216 @@
(function(/*! Stitch !*/) {
- if (!this.require) {
- var modules = {}, cache = {}, require = function(name, root) {
- var path = expand(root, name), module = cache[path], fn;
- if (module) {
+
+ var modules = {}, cache = {}, req = function(name, root) {
+ var path = expand(root, name), module = cache[path], fn;
+ if (module) {
+ return module.exports;
+ } else if (fn = modules[path] || modules[path = expand(path, './index')]) {
+ module = {id: path, exports: {}};
+ try {
+ cache[path] = module;
+ fn(module.exports, function(name) {
+ return req(name, dirname(path));
+ }, module);
return module.exports;
- } else if (fn = modules[path] || modules[path = expand(path, './index')]) {
- module = {id: path, exports: {}};
- try {
- cache[path] = module;
- fn(module.exports, function(name) {
- return require(name, dirname(path));
- }, module);
- return module.exports;
- } catch (err) {
- delete cache[path];
- throw err;
- }
- } else {
- throw 'module \'' + name + '\' not found';
+ } catch (err) {
+ delete cache[path];
+ throw err;
}
- }, expand = function(root, name) {
- var results = [], parts, part;
- if (/^\.\.?(\/|$)/.test(name)) {
- parts = [root, name].join('/').split('/');
- } else {
- parts = name.split('/');
+ } else {
+ throw 'module \'' + name + '\' not found';
+ }
+ }, expand = function(root, name) {
+ var results = [], parts, part;
+ if (/^\.\.?(\/|$)/.test(name)) {
+ parts = [root, name].join('/').split('/');
+ } else {
+ parts = name.split('/');
+ }
+ for (var i = 0, length = parts.length; i < length; i++) {
+ part = parts[i];
+ if (part == '..') {
+ results.pop();
+ } else if (part != '.' && part != '') {
+ results.push(part);
}
- for (var i = 0, length = parts.length; i < length; i++) {
- part = parts[i];
- if (part == '..') {
- results.pop();
- } else if (part != '.' && part != '') {
- results.push(part);
+ }
+ return results.join('/');
+ }, dirname = function(path) {
+ return path.split('/').slice(0, -1).join('/');
+ };
+
+ return function(bundle) {
+ for (var key in bundle){
+ modules[key] = bundle[key];
+ }
+
+ //UMD
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as a named module
+ define([],function(){
+ return req('scion','');
+ });
+ } else {
+ // Browser globals
+ this.scion = req('scion','');
+
+ //define global require
+ if (!this.require) {
+ this.require = function(name) {
+ return req(name, '');
}
}
- return results.join('/');
- }, dirname = function(path) {
- return path.split('/').slice(0, -1).join('/');
- };
- this.require = function(name) {
- return require(name, '');
}
- this.require.define = function(bundle) {
- for (var key in bundle)
- modules[key] = bundle[key];
- };
- }
- return this.require.define;
-}).call(this)({"browser/browser-listener-client": function(exports, require, module) {//TODO: this will be like node-listener-client.js, except will use jquery/AJAX for its remoting
+ };
+}).call(this)({"base-platform/dom": function(exports, require, module) {/*
+ Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+"use strict";
+
+//a small DOM helper/compatibility layer
+
+module.exports = {
+
+ getChildren : function(node){
+ return Array.prototype.slice.call(node.childNodes);
+ },
+
+ localName : function(node){
+ return node.localName;
+ },
+
+ getAttribute : function(node,attribute){
+ return node.getAttribute(attribute);
+ },
+
+ hasAttribute : function(node,attribute){
+ return node.hasAttribute(attribute);
+ },
+
+ namespaceURI : function(node){
+ return node.namespaceURI;
+ },
+
+ createElementNS : function(doc,ns,localName){
+ return doc.createElementNS(ns,localName);
+ },
+
+ setAttribute : function(node,name,value){
+ return node.setAttribute(name,value);
+ },
+
+ appendChild : function(parent,child){
+ return parent.appendChild(child);
+ },
+
+ textContent : function(node,txt){
+ if(txt === undefined){
+ if(node.nodeType === 1){
+ //element
+ if(node.textContent !== undefined){
+ return node.textContent;
+ }else{
+ //IE
+ return this.getChildren(node).
+ map(function(textNode){return this.textContent(textNode);},this).join("");
+ }
+ }else if(node.nodeType === 3 || node.nodeType === 4){
+ //textnode
+ return node.data;
+ }
+ return "";
+ }else{
+ if(node.nodeType === 1){
+ //element node
+ if(node.textContent !== undefined){
+ return node.textContent = txt;
+ }else{
+ //IE
+ var textNode = node.ownerDocument.createTextNode(txt);
+ node.appendChild(textNode);
+ return txt;
+ }
+ }else if(node.nodeType === 3){
+ //textnode
+ return node.data = txt;
+ }
+ }
+ },
+
+ getElementChildren : function(node){
+ return this.getChildren(node).filter(function(c){return c.nodeType === 1;});
+ }
+
+};
+}, "base-platform/eval": function(exports, require, module) {module.exports = function(content,name){
+ //JScript doesn't return functions from evaled function expression strings,
+ //so we wrap it here in a trivial self-executing function which gets eval'd
+ return eval('(function(){\nreturn ' + content + ';})()');
+};
+}, "base-platform/path": function(exports, require, module) {/*
+ Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+"use strict";
+
+//these are quick-and-dirty implementations
+//there may be missing edge cases
+module.exports = {
+
+ sep : "/",
+
+ join : function(path1,path2){
+ return path1 + "/" + path2;
+ },
+
+ dirname : function(path){
+ return path.split(this.sep).slice(0,-1).join(this.sep);
+ },
+
+ basename : function(path,ext){
+ var name = path.split(this.sep).slice(-1);
+ if(ext){
+ var names = this.extname(name);
+ if(names[1] === ext){
+ name = names[1];
+ }
+ }
+
+ return name;
+ },
+
+ extname : function(path){
+ //http://stackoverflow.com/a/4546093/366856
+ return path.split(/\\.(?=[^\\.]+$)/)[1];
+ }
+};
+}, "browser/browser-listener-client": function(exports, require, module) {//TODO: this will be like node-listener-client.js, except will use jquery/AJAX for its remoting
}, "browser/dom": function(exports, require, module) {/*
Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
@@ -67,7 +229,7 @@
"use strict";
-var baseDom = require('../embedded/dom');
+var baseDom = require('../base-platform/dom');
function getItem(nodeList,index){
return "item" in nodeList ? nodeList.item(index) : nodeList[index];
@@ -95,6 +257,10 @@ dom.getChildren = function(node){
return toReturn;
};
+dom.serializeToString = function(node){
+ return node.xml || (new XMLSerializer()).serializeToString(node);
+};
+
module.exports = dom;
}, "browser/platform": function(exports, require, module) {/*
Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
@@ -114,19 +280,19 @@ module.exports = dom;
"use strict";
-var util = require('../core/util/util'),
- basePlatform = require('../embedded/platform').platform;
+var util = require('../core/util/util');
//browser mostly just inherits path from basePlatform
-exports.platform = util.merge(Object.create(basePlatform),{
+exports.platform = {
/** @expose */
ajax : window.jQuery, //this can be overridden
//used in parsing
+ eval : require('../base-platform/eval'),
/** @this {platform} */
- getDocumentFromUrl : function(url,cb){
+ getDocumentFromUrl : function(url,cb,context){
this.ajax.get(url,function(r){
cb(null,r);
},"xml").error(function(e){
@@ -139,13 +305,13 @@ exports.platform = util.merge(Object.create(basePlatform),{
},
/** @this {platform} */
- getDocumentFromFilesystem : function(url,cb){
- this.getDocumentFromUrl(url,cb);
+ getDocumentFromFilesystem : function(url,cb,context){
+ this.getDocumentFromUrl(url,cb,context);
},
//TODO: the callback is duplicate code. move this out.
/** @this {platform} */
- getResourceFromUrl : function(url,cb){
+ getResourceFromUrl : function(url,cb,context){
this.ajax.get(url,function(r){
cb(null,r);
}).error(function(e){
@@ -172,13 +338,14 @@ exports.platform = util.merge(Object.create(basePlatform),{
window.clearTimeout(timeoutId);
},
- log : window.console.log.bind(console),
+ log : window.console && window.console.log && (window.console.log.bind ? window.console.log.bind(window.console) : window.console.log),
+
+ path : require('../base-platform/path'),
url : require('./url'),
dom : require('./dom')
-});
-
+};
}, "browser/url": function(exports, require, module) {/*
Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
@@ -293,6 +460,8 @@ function SCXMLInterpreter(model, opts){
this.opts.TransitionPairSet = this.opts.TransitionPairSet || ArraySet;
this.opts.priorityComparisonFn = this.opts.priorityComparisonFn || getTransitionWithHigherSourceChildPriority(this.opts.model);
+ this._sessionid = this.opts.sessionid || "";
+
this._configuration = new this.opts.BasicStateSet();
this._historyValue = {};
this._innerEventQueue = [];
@@ -333,7 +502,9 @@ SCXMLInterpreter.prototype = {
this._send.bind(this),
this.opts.origin,
this.isIn.bind(this),
- actionCodeRequire);
+ actionCodeRequire,
+ pm.platform.parseDocumentFromString,
+ this._sessionid);
this._actions = tmp.actions;
this._datamodel = tmp.datamodel;
@@ -375,6 +546,11 @@ SCXMLInterpreter.prototype = {
return this.getFullConfiguration().indexOf(stateName) > -1;
},
+ /** @expose */
+ isFinal : function(stateName) {
+ return this._isInFinalState;
+ },
+
/** @private */
_performBigStep : function(e) {
if (e) this._innerEventQueue.push(new this.opts.EventSet([e]));
@@ -401,7 +577,7 @@ SCXMLInterpreter.prototype = {
if (!selectedTransitions.isEmpty()) {
- if (printTrace) pm.platform.log("sorted transitions: ", selectedTransitions);
+ if (printTrace) pm.platform.log("sorted transitions: ", console.log(selectedTransitions));
//we only want to enter and exit states from transitions with targets
//filter out targetless transitions here - we will only use these to execute transition actions
@@ -516,7 +692,7 @@ SCXMLInterpreter.prototype = {
/** @private */
_evaluateAction : function(actionRef, eventSet, datamodelForNextStep, eventsToAddToInnerQueue) {
function $raise(event){
- eventsToAddToInnerQueue.add({ name: event, data : {}});
+ eventsToAddToInnerQueue.add(event);
}
var n = this._getScriptingInterface(datamodelForNextStep, eventSet, true);
@@ -539,15 +715,22 @@ SCXMLInterpreter.prototype = {
var statesExited = new this.opts.StateSet();
var basicStatesExited = new this.opts.BasicStateSet();
+ //States exited are defined to be active states that are
+ //descendants of the scope of each priority-enabled transition.
+ //Here, we iterate through the transitions, and collect states
+ //that match this condition.
transitions.iter().forEach(function(transition){
- var lca = transition.lca;
- var desc = lca.descendants;
+ var scope = transition.scope,
+ desc = scope.descendants;
+ //For each state in the configuration
+ //is that state a descendant of the transition scope?
+ //Store ancestors of that state up to but not including the scope.
this._configuration.iter().forEach(function(state){
if(desc.indexOf(state) > -1){
basicStatesExited.add(state);
statesExited.add(state);
- this.opts.model.getAncestors(state,lca).forEach(function(anc){
+ this.opts.model.getAncestors(state,scope).forEach(function(anc){
statesExited.add(anc);
});
}
@@ -563,82 +746,86 @@ SCXMLInterpreter.prototype = {
/** @private */
_getStatesEntered : function(transitions) {
- var statesToEnter = new this.opts.StateSet();
- var basicStatesToEnter = new this.opts.BasicStateSet();
- var statesProcessed = new this.opts.StateSet();
- var statesToProcess = [];
-
- var processTransitionSourceAndTarget = (function(source,target){
- //process each target
- processState(target);
-
- //and process ancestors of targets up to LCA, but according to special rules
- var lca = this.opts.model.getLCA(source,target);
- this.opts.model.getAncestors(target,lca).forEach(function(s){
- if (s.kind === stateKinds.COMPOSITE) {
- //just add him to statesToEnter, and declare him processed
- //this is to prevent adding his initial state later on
- statesToEnter.add(s);
-
- statesProcessed.add(s);
- }else{
- //everything else can just be passed through as normal
- processState(s);
- }
- });
- }).bind(this);
-
- var processState = (function(s){
-
- if(statesProcessed.contains(s)) return;
-
- if (s.kind === stateKinds.HISTORY) {
- if (s.id in this._historyValue) {
- this._historyValue[s.id].forEach(function(stateFromHistory){
- processTransitionSourceAndTarget(s,stateFromHistory);
- });
- } else {
- statesToEnter.add(s);
- basicStatesToEnter.add(s);
- }
- } else {
- statesToEnter.add(s);
-
- if (s.kind === stateKinds.PARALLEL) {
- statesToProcess.push.apply(statesToProcess,
- s.children.filter(function(s){return s.kind !== stateKinds.HISTORY;}));
- } else if (s.kind === stateKinds.COMPOSITE) {
- statesToProcess.push(s.initial);
- } else if (s.kind === stateKinds.INITIAL || s.kind === stateKinds.BASIC || s.kind === stateKinds.FINAL) {
- basicStatesToEnter.add(s);
- }
- }
-
- statesProcessed.add(s);
-
- }).bind(this);
+ var o = {
+ statesToEnter : new this.opts.StateSet(),
+ basicStatesToEnter : new this.opts.BasicStateSet(),
+ statesProcessed : new this.opts.StateSet(),
+ statesToProcess : []
+ };
//do the initial setup
transitions.iter().forEach(function(transition){
transition.targets.forEach(function(target){
- processTransitionSourceAndTarget(transition.source,target);
- });
- });
+ this._addStateAndAncestors(target,transition.scope,o);
+ },this);
+ },this);
//loop and add states until there are no more to add (we reach a stable state)
var s;
/*jsl:ignore*/
- while(s = statesToProcess.pop()){
+ while(s = o.statesToProcess.pop()){
/*jsl:end*/
- processState(s);
+ this._addStateAndDescendants(s,o);
}
//sort based on depth
- var sortedStatesEntered = statesToEnter.iter().sort(function(s1, s2) {
+ var sortedStatesEntered = o.statesToEnter.iter().sort(function(s1, s2) {
return s1.depth - s2.depth;
});
- return [basicStatesToEnter, sortedStatesEntered];
+ return [o.basicStatesToEnter, sortedStatesEntered];
+ },
+
+ /** @private */
+ _addStateAndAncestors : function(target,scope,o){
+
+ //process each target
+ this._addStateAndDescendants(target,o);
+
+ //and process ancestors of targets up to the scope, but according to special rules
+ this.opts.model.getAncestors(target,scope).forEach(function(s){
+
+ if (s.kind === stateKinds.COMPOSITE) {
+ //just add him to statesToEnter, and declare him processed
+ //this is to prevent adding his initial state later on
+ o.statesToEnter.add(s);
+
+ o.statesProcessed.add(s);
+ }else{
+ //everything else can just be passed through as normal
+ this._addStateAndDescendants(s,o);
+ }
+ },this);
+ },
+
+ /** @private */
+ _addStateAndDescendants : function(s,o){
+
+ if(o.statesProcessed.contains(s)) return;
+
+ if (s.kind === stateKinds.HISTORY) {
+ if (s.id in this._historyValue) {
+ this._historyValue[s.id].forEach(function(stateFromHistory){
+ this._addStateAndAncestors(stateFromHistory,s.parent,o);
+ },this);
+ } else {
+ o.statesToEnter.add(s);
+ o.basicStatesToEnter.add(s);
+ }
+ } else {
+ o.statesToEnter.add(s);
+
+ if (s.kind === stateKinds.PARALLEL) {
+ o.statesToProcess.push.apply(o.statesToProcess,
+ s.children.filter(function(s){return s.kind !== stateKinds.HISTORY;}));
+ } else if (s.kind === stateKinds.COMPOSITE) {
+ o.statesToProcess.push(s.initial);
+ } else if (s.kind === stateKinds.INITIAL || s.kind === stateKinds.BASIC || s.kind === stateKinds.FINAL) {
+ o.basicStatesToEnter.add(s);
+ }
+ }
+
+ o.statesProcessed.add(s);
},
/** @private */
@@ -750,13 +937,11 @@ SCXMLInterpreter.prototype = {
/** @private */
_isArenaOrthogonal : function(t1, t2) {
- var t1LCA = t1.targets ? t1.lca : t1.source;
- var t2LCA = t2.targets ? t2.lca : t2.source;
- var isOrthogonal = this.opts.model.isOrthogonalTo(t1LCA, t2LCA);
+ var isOrthogonal = this.opts.model.isOrthogonalTo(t1.scope, t2.scope);
if (printTrace) {
- pm.platform.log("transition LCAs", t1LCA.id, t2LCA.id);
- pm.platform.log("transition LCAs are orthogonal?", isOrthogonal);
+ pm.platform.log("transition scopes", t1.scope.id, t1.scope.id);
+ pm.platform.log("transition scopes are orthogonal?", isOrthogonal);
}
return isOrthogonal;
@@ -943,9 +1128,11 @@ function linkReferencesAndGenerateActionFactory(json){
state.transitions.forEach(function(transition){
if(transition.actions) transition.actions = makeEvaluationFn(transition.actions);
- if(transition.lca){
- transition.lca = idToStateMap[transition.lca];
+ if(transition.lcca){
+ transition.lcca = idToStateMap[transition.lcca];
}
+
+ transition.scope = idToStateMap[transition.scope];
});
state.initial = idToStateMap[state.initial];
@@ -1333,7 +1520,11 @@ var transform = exports.transform = function(scxmlDoc) {
return state;
});
- transition.lca = getLCA(source, targets[0]);
+ transition.lcca = getLCCA(source, targets[0]);
+ });
+
+ transitions.forEach(function(transition){
+ transition.scope = getScope(transition);
});
return {
@@ -1349,7 +1540,7 @@ var transform = exports.transform = function(scxmlDoc) {
};
function genRootScripts(root) {
- return pm.platform.dom.getChildren(root).filter(function(c){return pm.platform.dom.localName(c) === "script";}).map(function(c){return c.textContent;});
+ return pm.platform.dom.getChildren(root).filter(function(c){return pm.platform.dom.localName(c) === "script";}).map(function(c){return pm.platform.dom.textContent(c);});
}
function genEventsEnum(uniqueEvents) {
@@ -1402,6 +1593,7 @@ function transformTransitionNode (transitionNode, parentState) {
}
var transition = {
+ internal : pm.platform.dom.getAttribute(transitionNode,"type") === 'internal',
documentOrder: transitions.length,
id: transitions.length,
source: parentState.id,
@@ -1414,7 +1606,7 @@ function transformTransitionNode (transitionNode, parentState) {
transitions.push(transition);
- //set up LCA later
+ //set up LCCA later
return transition;
}
@@ -1422,7 +1614,43 @@ function transformTransitionNode (transitionNode, parentState) {
function transformDatamodel(node, ancestors) {
pm.platform.dom.getChildren(node).filter(function(child){return pm.platform.dom.localName(child) === 'data';}).forEach(function(child){
if (pm.platform.dom.hasAttribute(child,"id")) {
- datamodel[pm.platform.dom.getAttribute(child,"id")] = pm.platform.dom.hasAttribute(child,"expr") ? pm.platform.dom.getAttribute(child,"expr") : null;
+
+ var datamodelObject;
+
+ var id = pm.platform.dom.getAttribute(child,"id");
+
+ if(pm.platform.dom.hasAttribute(child,"expr")){
+ datamodelObject = {
+ content : pm.platform.dom.getAttribute(child,"expr"),
+ type : 'expr'
+ };
+ }else{
+ var hasType = pm.platform.dom.hasAttribute(child,'type');
+
+
+ //fetch the first text node to get the text content
+ if(hasType){
+ var type = pm.platform.dom.getAttribute(child,'type');
+
+ var textContent = type === 'xml' ?
+ pm.platform.dom.serializeToString(child) :
+ pm.platform.dom.textContent(child);
+
+ datamodelObject = {
+ content : textContent,
+ type : type
+ };
+ }else{
+ textContent = pm.platform.dom.textContent(child);
+ datamodelObject = textContent.length ?
+ {
+ content : textContent,
+ type : 'text'
+ } : null;
+ }
+ }
+
+ datamodel[id] = datamodelObject;
}
});
}
@@ -1576,17 +1804,40 @@ function genId(tagName) {
return "" + idRoot + "-" + tagName + "-" + (idCounter[tagName]++);
}
-function getLCA(s1, s2) {
- var a, anc, commonAncestors, _i, _len, _ref, _ref2;
- commonAncestors = [];
+function getLCCA(s1, s2) {
+ var a, anc, commonCompoundAncestors;
+ commonCompoundAncestors = [];
s1.ancestors.forEach(function(a){
anc = idToStateMap[a];
- if(anc.descendants.indexOf(s2.id) > -1){
- commonAncestors.push(a);
+ if(anc.kind === stateKinds.COMPOSITE &&
+ anc.descendants.indexOf(s2.id) > -1){
+ commonCompoundAncestors.push(a);
}
});
- if(!commonAncestors.length) throw new Error("Could not find LCA for states.");
- return commonAncestors[0];
+ if(!commonCompoundAncestors.length) throw new Error("Could not find LCCA for states.");
+ return commonCompoundAncestors[0];
+}
+
+function getScope(transition){
+ //Transition scope is normally the least common compound ancestor (lcca).
+ //Internal transitions have a scope equal to the source state.
+
+ var source = idToStateMap[transition.source];
+
+ var transitionIsReallyInternal =
+ transition.internal &&
+ source.parent && //root state won't have parent
+ transition.targets && //does it target its descendants
+ transition.targets.map(function(targetId){return idToStateMap[targetId];}).every(
+ function(target){ return source.descendants.map(function(id){return idToStateMap[id];}).indexOf(target) > -1;});
+
+ if(!transition.targets){
+ return transition.source;
+ }else if(transitionIsReallyInternal){
+ return transition.source;
+ }else{
+ return transition.lcca;
+ }
}
//epic one-liner
@@ -1628,7 +1879,7 @@ function actionTagToFnBody(action){
if(!(generator && generatorFn)) throw new Error("Element " + pm.platform.dom.namespaceURI(action) + ':' + pm.platform.dom.localName(action) + " not yet supported");
- return generatorFn(action);
+ return generatorFn(action);
}
var actionTags = {
@@ -1650,7 +1901,7 @@ var actionTags = {
for(var i = 0; i < childNodes.length; i++){
var child = childNodes[i];
- if(pm.platform.dom.localName(child) === "elseif" || pm.platform.dom.localName(child) === "else"){
+ if(pm.platform.dom.localName(child) === "elseif" || pm.platform.dom.localName(child) === "else"){
break;
}else{
s += actionTagToFnBody(child) + "\n;;\n";
@@ -1704,7 +1955,7 @@ var actionTags = {
},
"raise" : function(action){
- return "$raise(" + JSON.stringify(pm.platform.dom.getAttribute(action,"event")) + ");";
+ return "$raise({ name:" + JSON.stringify(pm.platform.dom.getAttribute(action,"event")) + ", data : {}});";
},
"cancel" : function(action){
@@ -1712,16 +1963,30 @@ var actionTags = {
},
"send" : function(action){
- return "$send({\n" +
- "target: " + (pm.platform.dom.hasAttribute(action,"targetexpr") ? pm.platform.dom.getAttribute(action,"targetexpr") : JSON.stringify(pm.platform.dom.getAttribute(action,"target"))) + ",\n" +
- "name: " + (pm.platform.dom.hasAttribute(action,"eventexpr") ? pm.platform.dom.getAttribute(action,"eventexpr") : JSON.stringify(pm.platform.dom.getAttribute(action,"event"))) + ",\n" +
+ var target = (pm.platform.dom.hasAttribute(action,"targetexpr") ? pm.platform.dom.getAttribute(action,"targetexpr") : JSON.stringify(pm.platform.dom.getAttribute(action,"target"))),
+ targetVariableName = '_scionTargetRef',
+ targetDeclaration = 'var ' + targetVariableName + ' = ' + target + ';\n';
+
+ var event = "{\n" +
+ "target: " + targetVariableName + ",\n" +
+ "name: " + (pm.platform.dom.hasAttribute(action,"eventexpr") ? pm.platform.dom.getAttribute(action,"eventexpr") : JSON.stringify(pm.platform.dom.getAttribute(action,"event"))) + ",\n" +
"type: " + (pm.platform.dom.hasAttribute(action,"typeexpr") ? pm.platform.dom.getAttribute(action,"typeexpr") : JSON.stringify(pm.platform.dom.getAttribute(action,"type"))) + ",\n" +
"data: " + constructSendEventData(action) + ",\n" +
"origin: $origin\n" +
- "}, {\n" +
- "delay: " + (pm.platform.dom.hasAttribute(action,"delayexpr") ? pm.platform.dom.getAttribute(action,"delayexpr") : getDelayInMs(pm.platform.dom.getAttribute(action,"delay"))) + ",\n" +
- "sendId: " + (pm.platform.dom.hasAttribute(action,"idlocation") ? pm.platform.dom.getAttribute(action,"idlocation") : JSON.stringify(pm.platform.dom.getAttribute(action,"id"))) + "\n" +
- "});";
+ "}";
+
+ var send =
+ targetDeclaration +
+ "if(" + targetVariableName + " === '#_internal'){\n" +
+ "$raise(" + event + ");\n" +
+ "}else{\n" +
+ "$send(" + event + ", {\n" +
+ "delay: " + (pm.platform.dom.hasAttribute(action,"delayexpr") ? 'getDelayInMs(' + pm.platform.dom.getAttribute(action,"delayexpr") + ')' : getDelayInMs(pm.platform.dom.getAttribute(action,"delay"))) + ",\n" +
+ "sendId: " + (pm.platform.dom.hasAttribute(action,"idlocation") ? pm.platform.dom.getAttribute(action,"idlocation") : JSON.stringify(pm.platform.dom.getAttribute(action,"id"))) + "\n" +
+ "}, $raise);" +
+ "}";
+
+ return send;
},
"foreach" : function(action){
@@ -1731,18 +1996,18 @@ var actionTags = {
arr = pm.platform.dom.getAttribute(action,"array"),
foreachBody = pm.platform.dom.getElementChildren(action).map(actionTagToFnBody).join("\n;;\n");
- return "(function(){\n" +
+ return "(function(){\n" +
"if(Array.isArray(" + arr + ")){\n" +
arr + ".forEach(function(" + item + "," + index + "){\n" +
foreachBody +
- "\n});\n" +
+ "\n});\n" +
"}else{\n" +
//assume object
"Object.keys(" + arr + ").forEach(function(" + index + "){\n" +
- item + " = " + arr + "[" + index + "];\n" +
+ item + " = " + arr + "[" + index + "];\n" +
foreachBody +
- "\n});\n" +
- "}\n" +
+ "\n});\n" +
+ "}\n" +
"})();";
}
}
@@ -1764,14 +2029,39 @@ function getDelayInMs(delayString){
}
}
+function getDatamodelExpression(id, datamodelObject){
+ var s = id;
+
+ if(datamodelObject){
+ s += ' = ';
+
+ switch(datamodelObject.type){
+ case 'xml' :
+ s += '$parseXml(' + JSON.stringify(datamodelObject.content) + ')';
+ break;
+ case 'json' :
+ s += 'JSON.parse(' + JSON.stringify(datamodelObject.content) + ')';
+ break;
+ case 'expr' :
+ s += datamodelObject.content;
+ break;
+ default :
+ s += JSON.stringify(datamodelObject.content);
+ break;
+ }
+ }
+
+ return s;
+}
+
//utility functions
//this creates the string which declares the datamodel in the document scope
function makeDatamodelDeclaration(datamodel){
var s = "var ";
var vars = [];
for(var id in datamodel){
- var expr = datamodel[id];
- vars.push(expr ? id + " = " + expr : id);
+ var datamodelObject = datamodel[id];
+ vars.push(getDatamodelExpression(id,datamodelObject));
}
return vars.length ? (s + vars.join(", ") + ";") : "";
}
@@ -1780,9 +2070,9 @@ function makeDatamodelDeclaration(datamodel){
function makeDatamodelClosures(datamodel){
var vars = [];
for(var id in datamodel){
- vars.push( '"' + id + '" : {\n' +
- '"set" : function(v){ return ' + id + ' = v; },\n' +
- '"get" : function(){ return ' + id + ';}' +
+ vars.push( '"' + id + '" : {\n' +
+ '"set" : function(v){ return ' + id + ' = v; },\n' +
+ '"get" : function(){ return ' + id + ';}' +
'\n}');
}
return '{\n' + vars.join(',\n') + '\n}';
@@ -1790,35 +2080,40 @@ function makeDatamodelClosures(datamodel){
function wrapFunctionBodyInDeclaration(action,isExpression){
return "function(getData,setData,_events,$raise){var _event = _events[0];\n" +
- (isExpression ? "return" : "") + " " + action +
+ (isExpression ? "return" : "") + " " + action +
"\n}";
}
function makeTopLevelFunctionBody(datamodelDeclaration,topLevelScripts,datamodelClosures,actionStrings){
- return datamodelDeclaration +
- (topLevelScripts.length ? topLevelScripts.join("\n") : "") +
- "return {\n" +
- "datamodel:" + datamodelClosures + "," +
+ return datamodelDeclaration +
+ (topLevelScripts.length ? topLevelScripts.join("\n") : "") +
+ "var $datamodel = " + datamodelClosures + ";\n" +
+ "return {\n" +
+ "datamodel:$datamodel,\n" +
"actions:[\n" + actionStrings.join(",\n") + "\n]" + //return all functions which get called during execution
"\n};";
}
function wrapTopLevelFunctionBodyInDeclaration(fnBody){
- return "function($log,$cancel,$send,$origin,In,require){\n" + fnBody + "\n}";
+ return "function($log,$cancel,$send,$origin,In,require,$parseXml,_sessionid,_ioprocessors,_x){\n" + fnBody + "\n}";
}
//this function ensures that the code in each SCXML document will run in "document scope".
//SCXML embeds js code as strings in the document, hence the use of "eval" to dynamically evaluate things.
//This function ensures that eval() is only called once, when the model is parsed. It will not be called during execution of the statechart.
-//However, each SCXML interpreter instance will have its own copies of the functions declared in the document.
+//However, each SCXML interpreter instance will have its own copies of the functions declared in the document.
//This is similar to the way HTML works - each page has its own copies of evaluated scripts.
function makeActionFactory(topLevelScripts,actionStrings,datamodel){
var datamodelDeclaration = makeDatamodelDeclaration(datamodel);
var datamodelClosures = makeDatamodelClosures(datamodel);
- var topLevelFnBody = makeTopLevelFunctionBody(datamodelDeclaration,topLevelScripts,datamodelClosures,actionStrings);
+ //we need to include getDelayInMs function declaration to handle send/@delayexpr, which is evaluated at runtime
+ var topLevelFnBody =
+ getDelayInMs.toString() + '\n' +
+ makeTopLevelFunctionBody(datamodelDeclaration,topLevelScripts,datamodelClosures,actionStrings);
var fnStr = wrapTopLevelFunctionBodyInDeclaration(topLevelFnBody);
- return fnStr;
+ //require('fs').writeFileSync('out.js',fnStr);
+ return fnStr;
}
@@ -1827,7 +2122,7 @@ function constructSendEventData(action){
var namelist = pm.platform.dom.hasAttribute(action,"namelist") ? pm.platform.dom.getAttribute(action,"namelist").trim().split(/ +/) : null,
params = pm.platform.dom.getChildren(action).filter(function(child){return pm.platform.dom.localName(child) === 'param';}),
content = pm.platform.dom.getChildren(action).filter(function(child){return pm.platform.dom.localName(child) === 'content';});
-
+
if(content.length){
//TODO: instead of using textContent, serialize the XML
content = content[0];
@@ -1909,76 +2204,96 @@ var annotator = require('./annotate-scxml-json'),
json2model = require('../scxml/json2model'),
pm = require('../../platform');
-function documentToModel(url,doc,cb){
+function documentToModel(url,doc,cb,context){
//do whatever transforms
//inline script tags
//platformGet may be undefined, and we can continue without it, hence the guard
if(pm.platform.getResourceFromUrl){
- inlineSrcs(url,doc,function(errors){
- if(errors){
- //I think we should probably just log any of these errors
- pm.platform.log("Errors downloading src attributes",errors);
+ inlineSrcs(url,doc,context,function(errors){
+ if(errors){
+ //treat script download errors as fatal
+ //pass through a single error - aggregate if there's more than one
+ cb(errors.length === 1 ?
+ errors[0].err :
+ new Error(
+ 'Script download errors : \n' +
+ errors.map(function(oErr){return oErr.url + ': ' + oErr.err.message;}).join('\n')));
+ }else{
+ //otherwise, attempt to convert document to model object
+ docToModel(url,doc,cb);
}
- docToModel(doc,url,cb);
});
}else{
- docToModel(doc,url,cb);
+ docToModel(url,doc,cb);
}
}
-function docToModel(doc,url,cb){
+function docToModel(url,doc,cb){
try {
var annotatedScxmlJson = annotator.transform(doc);
- var model = json2model(annotatedScxmlJson,url);
+ var model = json2model(annotatedScxmlJson,url);
cb(null,model);
}catch(e){
cb(e);
}
}
-function inlineSrcs(url,doc,cb){
+function fixupUrl(baseUrl, targetUrl) {
+ var newUrl;
+ if (pm.platform.url.resolve) {
+ newUrl = pm.platform.url.resolve(baseUrl, targetUrl);
+ } else {
+ var documentUrlPath = pm.platform.url.getPathFromUrl(baseUrl);
+ var documentDir = pm.platform.path.dirname(documentUrlPath);
+ var scriptPath = pm.platform.path.join(documentDir,targetUrl);
+ newUrl = pm.platform.url.changeUrlPath(baseUrl,scriptPath);
+ }
+
+ return newUrl;
+}
+
+function inlineSrcs(docUrl,doc,context,cb){
//console.log('inlining scripts');
-
- var scriptActionsWithSrcAttributes = [], errors = [];
-
- traverse(doc.documentElement,scriptActionsWithSrcAttributes);
-
- //async forEach
- function retrieveScripts(){
- var script = scriptActionsWithSrcAttributes.pop();
- if(script){
- //quick and dirty for now:
- //to be totally correct, what we need to do here is:
- //parse the url, extract the pathname, call dirname on path, and join that with the path to the file
- var scriptUrl = pm.platform.dom.getAttribute(script,"src");
- if(url){
- var documentUrlPath = pm.platform.url.getPathFromUrl(url);
- var documentDir = pm.platform.path.dirname(documentUrlPath);
- var scriptPath = pm.platform.path.join(documentDir,scriptUrl);
- scriptUrl = pm.platform.url.changeUrlPath(url,scriptPath);
+
+ var nodesWithSrcAttributes = [], errors = [], resultCount = 0;
+
+ traverse(doc.documentElement,nodesWithSrcAttributes);
+
+ if (nodesWithSrcAttributes.length) {
+ // kick off fetches in parallel
+ nodesWithSrcAttributes.forEach(function(node, idx) {
+ var nodeUrl = pm.platform.dom.getAttribute(node,"src");
+ if(docUrl) {
+ nodeUrl = fixupUrl(docUrl, nodeUrl);
}
- //platform.log('fetching script src',scriptUrl);
- pm.platform.getResourceFromUrl(scriptUrl,function(err,text){
+
+ /* TBD: For data elements, use mimeType (aka Content-Type returned by HTTP server (if any))
+ * to determine how to process the external resource.
+ * e.g. treat application/json as JSON per hint in C.2.1 of http://www.w3.org/TR/scxml/#profiles
+ */
+ pm.platform.getResourceFromUrl(nodeUrl,function(err,text,mimeType){
if(err){
//just capture the error, and continue on
- pm.platform.log("Error downloading document " + scriptUrl + " : " + err.message);
- errors.push(err);
+ pm.platform.log("Error downloading document " + nodeUrl + " : " + err.message);
+ errors.push({url : nodeUrl, err : err});
}else{
- pm.platform.dom.textContent(script,text);
+ pm.platform.dom.textContent(node,text);
}
- retrieveScripts();
- });
- }else{
- cb(errors.length ? errors : null);
- }
+ ++resultCount;
+ if (resultCount == nodesWithSrcAttributes.length) {
+ cb(errors.length ? errors : null);
+ }
+ },context);
+ });
+ } else {
+ cb();
}
- retrieveScripts(); //kick him off
}
function traverse(node,nodeList){
if((pm.platform.dom.localName(node) === 'script' || pm.platform.dom.localName(node) === 'data') && pm.platform.dom.hasAttribute(node,"src")){
- nodeList.push(node);
- }
+ nodeList.push(node);
+ }
pm.platform.dom.getElementChildren(node).forEach(function(child){traverse(child,nodeList);});
}
@@ -2016,218 +2331,6 @@ module.exports = {
return target;
}
};
-}, "embedded/dom": function(exports, require, module) {/*
- Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-"use strict";
-
-//a small DOM helper/compatibility layer
-
-module.exports = {
-
- getChildren : function(node){
- return Array.prototype.slice.call(node.childNodes);
- },
-
- localName : function(node){
- return node.localName;
- },
-
- getAttribute : function(node,attribute){
- return node.getAttribute(attribute);
- },
-
- hasAttribute : function(node,attribute){
- return node.hasAttribute(attribute);
- },
-
- namespaceURI : function(node){
- return node.namespaceURI;
- },
-
- createElementNS : function(doc,ns,localName){
- return doc.createElementNS(ns,localName);
- },
-
- setAttribute : function(node,name,value){
- return node.setAttribute(name,value);
- },
-
- appendChild : function(parent,child){
- return parent.appendChild(child);
- },
-
- textContent : function(node,txt){
- if(txt === undefined){
- if(node.nodeType === 1){
- //element
- return node.textContent;
- }else if(node.nodeType === 3 || node.nodeType === 4){
- //textnode
- return node.data;
- }
- return "";
- }else{
- if(node.nodeType === 1){
- //element node
- return node.textContent = txt;
- }else if(node.nodeType === 3){
- //textnode
- return node.data = txt;
- }
- }
- },
-
- getElementChildren : function(node){
- return this.getChildren(node).filter(function(c){return c.nodeType === 1;});
- }
-
-};
-}, "embedded/path": function(exports, require, module) {/*
- Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-"use strict";
-
-//these are quick-and-dirty implementations
-//there may be missing edge cases
-module.exports = {
-
- sep : "/",
-
- join : function(path1,path2){
- return path1 + "/" + path2;
- },
-
- dirname : function(path){
- return path.split(this.sep).slice(0,-1).join(this.sep);
- },
-
- basename : function(path,ext){
- var name = path.split(this.sep).slice(-1);
- if(ext){
- var names = this.extname(name);
- if(names[1] === ext){
- name = names[1];
- }
- }
-
- return name;
- },
-
- extname : function(path){
- //http://stackoverflow.com/a/4546093/366856
- return path.split(/\\.(?=[^\\.]+$)/)[1];
- }
-};
-}, "embedded/platform": function(exports, require, module) {/*
- Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-"use strict";
-
-//this provides an incomplete base platform implementation
-//other platform implementations can optionally extend it.
-
-function parseDocumentFromString(str){
- var xmldom = require('../../external/xmldom/dom-parser');
- return (new xmldom.DOMParser()).parseFromString(str);
-}
-
-//most shells will also at least be able to implement: getDocumentFromFilesystem and log
-
-exports.platform = {
- parseDocumentFromString : parseDocumentFromString,
-
- eval : function(content,name){
- //JScript doesn't return functions from evaled function expression strings,
- //so we wrap it here in a trivial self-executing function which gets eval'd
- return eval('(function(){\nreturn ' + content + ';})()');
- },
-
- path : require('./path'),
-
- url : require('./url'),
-
- dom : require('./dom')
-
-};
-}, "embedded/url": function(exports, require, module) {/*
- Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-"use strict";
-
-//this base module could be used with jsuri [http://code.google.com/p/jsuri/], a portable, pure-js URI parser implemenation
-//currently, none of the "blessed" environments use it, but it could simplify things for embedding
-//assume global Uri object
-//require('external/jsUri/dist/jsuri'); //this is just to load up a global Uri object
-
-function parseUri(uri){
- /*jsl:ignore*/
- if(typeof Uri === undefined) throw new Error("URI parser not loaded");
- return new Uri(url);
- /*jsl:end*/
-}
-
-module.exports = {
- getPathFromUrl : function(url){
- return parseUri(url).path();
- },
-
- changeUrlPath : function(url,newPath){
- return parseUri(url).path(newPath).toString();
- }
-};
}, "platform": function(exports, require, module) {/*
Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
@@ -2266,8 +2369,6 @@ if(isBrowser()){
module.exports = require('./node/platform');
}else if(isRhino()){
module.exports = require('./rhino/platform');
-}else{
- module.exports = require('./embedded/platform');
}
}, "scion": function(exports, require, module) {/*
Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors
@@ -2291,41 +2392,56 @@ var pm = require('./platform'),
scxml = require('./core/scxml/SCXML'),
documentToModel = require('./core/util/docToModel');
-function urlToModel(url,cb){
+/*
+ *@url URL of the SCXML document to retrieve and convert to a model
+ *@cb callback to invoke with an error or the model
+ *@context Optional. host-specific data passed along to the platform-specific resource-fetching API (e.g. to provide better traceability)
+ */
+function urlToModel(url,cb,context){
if(!pm.platform.getDocumentFromUrl) throw new Error("Platform does not support getDocumentFromUrl");
pm.platform.getDocumentFromUrl(url,function(err,doc){
if(err){
cb(err,null);
}else{
- documentToModel(url,doc,cb);
+ documentToModel(url,doc,cb,context);
}
- });
+ },context);
}
-function pathToModel(url,cb){
+/*
+ *@url file system path of the SCXML document to retrieve and convert to a model
+ *@cb callback to invoke with an error or the model
+ *@context Optional. host-specific data passed along to the platform-specific resource-fetching API (e.g. to provide better traceability)
+ */
+function pathToModel(url,cb,context){
if(!pm.platform.getDocumentFromFilesystem) throw new Error("Platform does not support getDocumentFromFilesystem");
pm.platform.getDocumentFromFilesystem(url,function(err,doc){
if(err){
cb(err,null);
}else{
- documentToModel(url,doc,cb);
+ documentToModel(url,doc,cb,context);
}
- });
+ },context);
}
-function documentStringToModel(s,cb){
+/*
+ *@s SCXML document string to convert to a model
+ *@cb callback to invoke with an error or the model
+ *@context Optional. host-specific data passed along to the platform-specific resource-fetching API (e.g. to provide better traceability)
+ */
+function documentStringToModel(s,cb,context){
if(!pm.platform.parseDocumentFromString) throw new Error("Platform does not support parseDocumentFromString");
- documentToModel(null,pm.platform.parseDocumentFromString(s),cb);
+ documentToModel(null,pm.platform.parseDocumentFromString(s),cb,context);
}
//export standard interface
var scion = module.exports = {
pathToModel : pathToModel,
- urlToModel : urlToModel,
- documentStringToModel : documentStringToModel,
+ urlToModel : urlToModel,
+ documentStringToModel : documentStringToModel,
documentToModel : documentToModel,
SCXML : scxml.SimpleInterpreter,
ext : {
Please sign in to comment.
Something went wrong with that request. Please try again.