Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Guria
Created January 10, 2016 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Guria/8a1b46e04c952857d27f to your computer and use it in GitHub Desktop.
Save Guria/8a1b46e04c952857d27f to your computer and use it in GitHub Desktop.
requirebin sketch
// require() some stuff from npm (like you were using browserify)
// and then hit Run Code to run it on the right
Controller = require('cerebral')
Model = require('cerebral-model-baobab')
controller = Controller(Model({}))
controller.modules({
a: function(){
return { metsgg: 4 }
},
b: function(m,c) {
res = c.getModules()
}
})
document.write(JSON.stringify(res))
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(_x3,_x4,_x5){var _again=true;_function:while(_again){var object=_x3,property=_x4,receiver=_x5;_again=false;if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{_x3=parent;_x4=property;_x5=receiver;_again=true;desc=parent=undefined;continue _function}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}}};function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj["default"]=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var _emmett=require("emmett");var _emmett2=_interopRequireDefault(_emmett);var _cursor=require("./cursor");var _cursor2=_interopRequireDefault(_cursor);var _monkey=require("./monkey");var _watcher=require("./watcher");var _watcher2=_interopRequireDefault(_watcher);var _type=require("./type");var _type2=_interopRequireDefault(_type);var _update2=require("./update");var _update3=_interopRequireDefault(_update2);var _helpers=require("./helpers");var helpers=_interopRequireWildcard(_helpers);var arrayFrom=helpers.arrayFrom;var coercePath=helpers.coercePath;var deepFreeze=helpers.deepFreeze;var getIn=helpers.getIn;var makeError=helpers.makeError;var deepMerge=helpers.deepMerge;var shallowClone=helpers.shallowClone;var shallowMerge=helpers.shallowMerge;var uniqid=helpers.uniqid;var DEFAULTS={autoCommit:true,asynchronous:true,immutable:true,lazyMonkeys:true,persistent:true,pure:true,validate:null,validationBehavior:"rollback"};function hashPath(path){return"λ"+path.map(function(step){if(_type2["default"]["function"](step)||_type2["default"].object(step))return"#"+uniqid()+"#";return step}).join("λ")}var Baobab=function(_Emitter){_inherits(Baobab,_Emitter);function Baobab(initialData,opts){var _this=this;_classCallCheck(this,Baobab);_get(Object.getPrototypeOf(Baobab.prototype),"constructor",this).call(this);if(arguments.length<1)initialData={};if(!_type2["default"].object(initialData)&&!_type2["default"].array(initialData))throw makeError("Baobab: invalid data.",{data:initialData});this.options=shallowMerge({},DEFAULTS,opts);if(!this.options.persistent){this.options.immutable=false;this.options.pure=false}this._identity="[object Baobab]";this._cursors={};this._future=null;this._transaction=[];this._affectedPathsIndex={};this._monkeys={};this._previousData=null;this._data=initialData;this.root=new _cursor2["default"](this,[],"λ");delete this.root.release;if(this.options.immutable)deepFreeze(this._data);var bootstrap=function bootstrap(name){_this[name]=function(){var r=this.root[name].apply(this.root,arguments);return r instanceof _cursor2["default"]?this:r}};["apply","clone","concat","deepClone","deepMerge","exists","get","push","merge","pop","project","serialize","set","shift","splice","unset","unshift"].forEach(bootstrap);this._refreshMonkeys();var validationError=this.validate();if(validationError)throw Error("Baobab: invalid data.",{error:validationError})}_createClass(Baobab,[{key:"_refreshMonkeys",value:function _refreshMonkeys(node,path,operation){var _this2=this;var clean=function clean(data){var p=arguments.length<=1||arguments[1]===undefined?[]:arguments[1];if(data instanceof _monkey.Monkey){data.release();(0,_update3["default"])(_this2._monkeys,p,{type:"unset"},{immutable:false,persistent:false,pure:false});return}if(_type2["default"].object(data)){for(var k in data){clean(data[k],p.concat(k))}}};var register=[];var walk=function walk(data){var p=arguments.length<=1||arguments[1]===undefined?[]:arguments[1];if(data instanceof _monkey.MonkeyDefinition||data instanceof _monkey.Monkey){var monkeyInstance=new _monkey.Monkey(_this2,p,data instanceof _monkey.Monkey?data.definition:data);register.push(monkeyInstance);(0,_update3["default"])(_this2._monkeys,p,{type:"set",value:monkeyInstance},{immutable:false,persistent:false,pure:false});return}if(_type2["default"].object(data)){for(var k in data){walk(data[k],p.concat(k))}}};if(!arguments.length){walk(this._data);register.forEach(function(m){return m.checkRecursivity()})}else{var monkeysNode=getIn(this._monkeys,path).data;if(monkeysNode)clean(monkeysNode,path);if(operation!=="unset"){walk(node,path);register.forEach(function(m){return m.checkRecursivity()})}}return this}},{key:"validate",value:function validate(affectedPaths){var _options=this.options;var validate=_options.validate;var behavior=_options.validationBehavior;if(typeof validate!=="function")return null;var error=validate.call(this,this._previousData,this._data,affectedPaths||[[]]);if(error instanceof Error){if(behavior==="rollback"){this._data=this._previousData;this._affectedPathsIndex={};this._transaction=[];this._previousData=this._data}this.emit("invalid",{error:error});return error}return null}},{key:"select",value:function select(path){path=path||[];if(arguments.length>1)path=arrayFrom(arguments);if(!_type2["default"].path(path))throw makeError("Baobab.select: invalid path.",{path:path});path=[].concat(path);var hash=hashPath(path);var cursor=this._cursors[hash];if(!cursor){cursor=new _cursor2["default"](this,path,hash);this._cursors[hash]=cursor}this.emit("select",{path:path,cursor:cursor});return cursor}},{key:"update",value:function update(path,operation){var _this3=this;path=coercePath(path);if(!_type2["default"].operationType(operation.type))throw makeError('Baobab.update: unknown operation type "'+operation.type+'".',{operation:operation});var _getIn=getIn(this._data,path);var solvedPath=_getIn.solvedPath;var exists=_getIn.exists;if(!solvedPath)throw makeError("Baobab.update: could not solve the given path.",{path:solvedPath});var monkeyPath=_type2["default"].monkeyPath(this._monkeys,solvedPath);if(monkeyPath&&solvedPath.length>monkeyPath.length)throw makeError("Baobab.update: attempting to update a read-only path.",{path:solvedPath});if(operation.type==="unset"&&!exists)return;var realOperation=operation;if(/merge/.test(operation.type)){var monkeysNode=getIn(this._monkeys,solvedPath).data;if(_type2["default"].object(monkeysNode)){realOperation=shallowClone(realOperation);if(/deep/.test(realOperation.type))realOperation.value=deepMerge({},monkeysNode,realOperation.value);else realOperation.value=shallowMerge({},monkeysNode,realOperation.value)}}if(!this._transaction.length)this._previousData=this._data;var result=(0,_update3["default"])(this._data,solvedPath,realOperation,this.options);var data=result.data;var node=result.node;if(!("data"in result))return node;var affectedPath=solvedPath.concat(operation.type==="push"?node.length-1:[]);var hash=hashPath(affectedPath);this._data=data;this._affectedPathsIndex[hash]=true;this._transaction.push(shallowMerge({},operation,{path:affectedPath}));this._refreshMonkeys(node,solvedPath,operation.type);this.emit("write",{path:affectedPath});if(!this.options.autoCommit)return node;if(!this.options.asynchronous){this.commit();return node}if(!this._future)this._future=setTimeout(function(){return _this3.commit()},0);return node}},{key:"commit",value:function commit(){if(!this._transaction.length)return this;if(this._future)this._future=clearTimeout(this._future);var affectedPaths=Object.keys(this._affectedPathsIndex).map(function(h){return h!=="λ"?h.split("λ").slice(1):[]});var validationError=this.validate(affectedPaths);if(validationError)return this;var transaction=this._transaction,previousData=this._previousData;this._affectedPathsIndex={};this._transaction=[];this._previousData=this._data;this.emit("update",{paths:affectedPaths,currentData:this._data,transaction:transaction,previousData:previousData});return this}},{key:"watch",value:function watch(mapping){return new _watcher2["default"](this,mapping)}},{key:"release",value:function release(){var k=undefined;this.emit("release");delete this.root;delete this._data;delete this._previousData;delete this._transaction;delete this._affectedPathsIndex;delete this._monkeys;for(k in this._cursors)this._cursors[k].release();delete this._cursors;this.kill()}},{key:"toJSON",value:function toJSON(){return this.serialize()}},{key:"toString",value:function toString(){return this._identity}}]);return Baobab}(_emmett2["default"]);exports["default"]=Baobab;Baobab.monkey=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}if(!args.length)throw new Error("Baobab.monkey: missing definition.");if(args.length===1&&typeof args[0]!=="function")return new _monkey.MonkeyDefinition(args[0]);return new _monkey.MonkeyDefinition(args)};Baobab.dynamicNode=Baobab.monkey;Baobab.Cursor=_cursor2["default"];Baobab.MonkeyDefinition=_monkey.MonkeyDefinition;Baobab.Monkey=_monkey.Monkey;Baobab.type=_type2["default"];Baobab.helpers=helpers;Baobab.VERSION="2.3.0";module.exports=exports["default"]},{"./cursor":2,"./helpers":3,"./monkey":4,"./type":5,"./update":6,"./watcher":7,emmett:8}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(_x3,_x4,_x5){var _again=true;_function:while(_again){var object=_x3,property=_x4,receiver=_x5;_again=false;if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{_x3=parent;_x4=property;_x5=receiver;_again=true;desc=parent=undefined;continue _function}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}}};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var _emmett=require("emmett");var _emmett2=_interopRequireDefault(_emmett);var _monkey=require("./monkey");var _type=require("./type");var _type2=_interopRequireDefault(_type);var _helpers=require("./helpers");function checkPossibilityOfDynamicTraversal(method,solvedPath){if(!solvedPath)throw(0,_helpers.makeError)("Baobab.Cursor."+method+": "+("cannot use "+method+" on an unresolved dynamic path."),{path:solvedPath})}var Cursor=function(_Emitter){_inherits(Cursor,_Emitter);function Cursor(tree,path,hash){var _this=this;_classCallCheck(this,Cursor);_get(Object.getPrototypeOf(Cursor.prototype),"constructor",this).call(this);path=path||[];this._identity="[object Cursor]";this._archive=null;this.tree=tree;this.path=path;this.hash=hash;this.state={killed:false,recording:false,undoing:false};this._dynamicPath=_type2["default"].dynamicPath(this.path);this._monkeyPath=_type2["default"].monkeyPath(this.tree._monkeys,this.path);if(!this._dynamicPath)this.solvedPath=this.path;else this.solvedPath=(0,_helpers.getIn)(this.tree._data,this.path).solvedPath;this._writeHandler=function(_ref){var data=_ref.data;if(_this.state.killed||!(0,_helpers.solveUpdate)([data.path],_this._getComparedPaths()))return;_this.solvedPath=(0,_helpers.getIn)(_this.tree._data,_this.path).solvedPath};var fireUpdate=function fireUpdate(previousData){var self=_this;var eventData=Object.defineProperties({},{previousData:{get:function get(){return(0,_helpers.getIn)(previousData,self.solvedPath).data},configurable:true,enumerable:true},currentData:{get:function get(){return self.get()},configurable:true,enumerable:true}});if(_this.state.recording&&!_this.state.undoing)_this.archive.add(eventData.previousData);_this.state.undoing=false;return _this.emit("update",eventData)};this._updateHandler=function(event){if(_this.state.killed)return;var _event$data=event.data;var paths=_event$data.paths;var previousData=_event$data.previousData;var update=fireUpdate.bind(_this,previousData);var comparedPaths=_this._getComparedPaths();if((0,_helpers.solveUpdate)(paths,comparedPaths))return update()};var bound=false;this._lazyBind=function(){if(bound)return;bound=true;if(_this._dynamicPath)_this.tree.on("write",_this._writeHandler);return _this.tree.on("update",_this._updateHandler)};if(this._dynamicPath){this._lazyBind()}else{this.on=(0,_helpers.before)(this._lazyBind,this.on.bind(this));this.once=(0,_helpers.before)(this._lazyBind,this.once.bind(this))}}_createClass(Cursor,[{key:"_getComparedPaths",value:function _getComparedPaths(){var additionalPaths=this._monkeyPath?(0,_helpers.getIn)(this.tree._monkeys,this._monkeyPath).data.relatedPaths():[];return[this.solvedPath].concat(additionalPaths)}},{key:"isRoot",value:function isRoot(){return!this.path.length}},{key:"isLeaf",value:function isLeaf(){return _type2["default"].primitive(this._get().data)}},{key:"isBranch",value:function isBranch(){return!this.isRoot()&&!this.isLeaf()}},{key:"root",value:function root(){return this.tree.select()}},{key:"select",value:function select(path){if(arguments.length>1)path=(0,_helpers.arrayFrom)(arguments);return this.tree.select(this.path.concat(path))}},{key:"up",value:function up(){if(!this.isRoot())return this.tree.select(this.path.slice(0,-1));return null}},{key:"down",value:function down(){checkPossibilityOfDynamicTraversal("down",this.solvedPath);if(!(this._get().data instanceof Array))throw Error("Baobab.Cursor.down: cannot go down on a non-list type.");return this.tree.select(this.solvedPath.concat(0))}},{key:"left",value:function left(){checkPossibilityOfDynamicTraversal("left",this.solvedPath);var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("Baobab.Cursor.left: cannot go left on a non-list type.");return last?this.tree.select(this.solvedPath.slice(0,-1).concat(last-1)):null}},{key:"right",value:function right(){checkPossibilityOfDynamicTraversal("right",this.solvedPath);var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("Baobab.Cursor.right: cannot go right on a non-list type.");if(last+1===this.up()._get().data.length)return null;return this.tree.select(this.solvedPath.slice(0,-1).concat(last+1))}},{key:"leftmost",value:function leftmost(){checkPossibilityOfDynamicTraversal("leftmost",this.solvedPath);var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("Baobab.Cursor.leftmost: cannot go left on a non-list type.");return this.tree.select(this.solvedPath.slice(0,-1).concat(0))}},{key:"rightmost",value:function rightmost(){checkPossibilityOfDynamicTraversal("rightmost",this.solvedPath);var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("Baobab.Cursor.rightmost: cannot go right on a non-list type.");var list=this.up()._get().data;return this.tree.select(this.solvedPath.slice(0,-1).concat(list.length-1))}},{key:"map",value:function map(fn,scope){checkPossibilityOfDynamicTraversal("map",this.solvedPath);var array=this._get().data,l=arguments.length;if(!_type2["default"].array(array))throw Error("baobab.Cursor.map: cannot map a non-list type.");return array.map(function(item,i){return fn.call(l>1?scope:this,this.select(i),i,array)},this)}},{key:"_get",value:function _get(){var path=arguments.length<=0||arguments[0]===undefined?[]:arguments[0];if(!_type2["default"].path(path))throw(0,_helpers.makeError)("Baobab.Cursor.getters: invalid path.",{path:path});if(!this.solvedPath)return{data:undefined,solvedPath:null,exists:false};return(0,_helpers.getIn)(this.tree._data,this.solvedPath.concat(path))}},{key:"exists",value:function exists(path){path=(0,_helpers.coercePath)(path);if(arguments.length>1)path=(0,_helpers.arrayFrom)(arguments);return this._get(path).exists}},{key:"get",value:function get(path){path=(0,_helpers.coercePath)(path);if(arguments.length>1)path=(0,_helpers.arrayFrom)(arguments);var _get2=this._get(path);var data=_get2.data;var solvedPath=_get2.solvedPath;this.tree.emit("get",{data:data,solvedPath:solvedPath,path:this.path.concat(path)});return data}},{key:"clone",value:function clone(){var data=this.get.apply(this,arguments);return(0,_helpers.shallowClone)(data)}},{key:"deepClone",value:function deepClone(){var data=this.get.apply(this,arguments);return(0,_helpers.deepClone)(data)}},{key:"serialize",value:function serialize(path){path=(0,_helpers.coercePath)(path);if(arguments.length>1)path=(0,_helpers.arrayFrom)(arguments);if(!_type2["default"].path(path))throw(0,_helpers.makeError)("Baobab.Cursor.getters: invalid path.",{path:path});if(!this.solvedPath)return undefined;var fullPath=this.solvedPath.concat(path);var data=(0,_helpers.deepClone)((0,_helpers.getIn)(this.tree._data,fullPath).data),monkeys=(0,_helpers.getIn)(this.tree._monkeys,fullPath).data;var dropComputedData=function dropComputedData(d,m){if(!_type2["default"].object(m)||!_type2["default"].object(d))return;for(var k in m){if(m[k]instanceof _monkey.Monkey)delete d[k];else dropComputedData(d[k],m[k])}};dropComputedData(data,monkeys);return data}},{key:"project",value:function project(projection){if(_type2["default"].object(projection)){var data={};for(var k in projection){data[k]=this.get(projection[k])}return data}else if(_type2["default"].array(projection)){var data=[];for(var i=0,l=projection.length;i<l;i++){data.push(this.get(projection[i]))}return data}throw(0,_helpers.makeError)("Baobab.Cursor.project: wrong projection.",{projection:projection})}},{key:"startRecording",value:function startRecording(maxRecords){maxRecords=maxRecords||Infinity;if(maxRecords<1)throw(0,_helpers.makeError)("Baobab.Cursor.startRecording: invalid max records.",{value:maxRecords});this.state.recording=true;if(this.archive)return this;this._lazyBind();this.archive=new _helpers.Archive(maxRecords);return this}},{key:"stopRecording",value:function stopRecording(){this.state.recording=false;return this}},{key:"undo",value:function undo(){var steps=arguments.length<=0||arguments[0]===undefined?1:arguments[0];if(!this.state.recording)throw new Error("Baobab.Cursor.undo: cursor is not recording.");var record=this.archive.back(steps);if(!record)throw Error("Baobab.Cursor.undo: cannot find a relevant record.");this.state.undoing=true;this.set(record);return this}},{key:"hasHistory",value:function hasHistory(){return!!(this.archive&&this.archive.get().length)}},{key:"getHistory",value:function getHistory(){return this.archive?this.archive.get():[]}},{key:"clearHistory",value:function clearHistory(){if(this.archive)this.archive.clear();return this}},{key:"release",value:function release(){if(this._dynamicPath)this.tree.off("write",this._writeHandler);this.tree.off("update",this._updateHandler);if(this.hash)delete this.tree._cursors[this.hash];delete this.tree;delete this.path;delete this.solvedPath;delete this.archive;this.kill();this.state.killed=true}},{key:"toJSON",value:function toJSON(){return this.serialize()}},{key:"toString",value:function toString(){return this._identity}}]);return Cursor}(_emmett2["default"]);exports["default"]=Cursor;if(typeof Symbol==="function"&&typeof Symbol.iterator!=="undefined"){Cursor.prototype[Symbol.iterator]=function(){var array=this._get().data;if(!_type2["default"].array(array))throw Error("baobab.Cursor.@@iterate: cannot iterate a non-list type.");var i=0;var cursor=this,length=array.length;return{next:function next(){if(i<length){return{value:cursor.select(i++)}}return{done:true}}}}}var INTRANSITIVE_SETTERS={unset:true,pop:true,shift:true};function makeSetter(name,typeChecker){Cursor.prototype[name]=function(path,value){if(arguments.length>2)throw(0,_helpers.makeError)("Baobab.Cursor."+name+": too many arguments.");if(arguments.length===1&&!INTRANSITIVE_SETTERS[name]){value=path;path=[]}path=(0,_helpers.coercePath)(path);if(!_type2["default"].path(path))throw(0,_helpers.makeError)("Baobab.Cursor."+name+": invalid path.",{path:path});if(typeChecker&&!typeChecker(value))throw(0,_helpers.makeError)("Baobab.Cursor."+name+": invalid value.",{path:path,value:value});if(!this.solvedPath)throw(0,_helpers.makeError)("Baobab.Cursor."+name+": the dynamic path of the cursor cannot be solved.",{path:this.path});var fullPath=this.solvedPath.concat(path);return this.tree.update(fullPath,{type:name,value:value})}}makeSetter("set");makeSetter("unset");makeSetter("apply",_type2["default"]["function"]);makeSetter("push");makeSetter("concat",_type2["default"].array);makeSetter("unshift");makeSetter("pop");makeSetter("shift");makeSetter("splice",_type2["default"].splicer);makeSetter("merge",_type2["default"].object);makeSetter("deepMerge",_type2["default"].object);module.exports=exports["default"]},{"./helpers":3,"./monkey":4,"./type":5,emmett:8}],3:[function(require,module,exports){(function(global){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();exports.arrayFrom=arrayFrom;exports.before=before;exports.coercePath=coercePath;exports.getIn=getIn;exports.makeError=makeError;exports.solveRelativePath=solveRelativePath;exports.solveUpdate=solveUpdate;exports.splice=splice;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var _monkey=require("./monkey");var _type=require("./type");var _type2=_interopRequireDefault(_type);var noop=Function.prototype;function index(a,fn){var i=undefined,l=undefined;for(i=0,l=a.length;i<l;i++){if(fn(a[i]))return i}return-1}function slice(array){var newArray=new Array(array.length);var i=undefined,l=undefined;for(i=0,l=array.length;i<l;i++)newArray[i]=array[i];return newArray}var Archive=function(){function Archive(size){_classCallCheck(this,Archive);this.size=size;this.records=[]}_createClass(Archive,[{key:"get",value:function get(){return this.records}},{key:"add",value:function add(record){this.records.unshift(record);if(this.records.length>this.size)this.records.length=this.size;return this}},{key:"clear",value:function clear(){this.records=[];return this}},{key:"back",value:function back(steps){var record=this.records[steps-1];if(record)this.records=this.records.slice(steps);return record}}]);return Archive}();exports.Archive=Archive;function arrayFrom(culprit){return slice(culprit)}function before(decorator,fn){return function(){decorator.apply(null,arguments);fn.apply(null,arguments)}}function cloneRegexp(re){var pattern=re.source;var flags="";if(re.global)flags+="g";if(re.multiline)flags+="m";if(re.ignoreCase)flags+="i";if(re.sticky)flags+="y";if(re.unicode)flags+="u";return new RegExp(pattern,flags)}function cloner(deep,item){if(!item||typeof item!=="object"||item instanceof Error||item instanceof _monkey.MonkeyDefinition||"ArrayBuffer"in global&&item instanceof ArrayBuffer)return item;if(_type2["default"].array(item)){if(deep){var a=[];var i=undefined,l=undefined;for(i=0,l=item.length;i<l;i++)a.push(cloner(true,item[i]));return a}return slice(item)}if(item instanceof Date)return new Date(item.getTime());if(item instanceof RegExp)return cloneRegexp(item);if(_type2["default"].object(item)){var o={};var k=undefined;for(k in item){if(_type2["default"].lazyGetter(item,k)){Object.defineProperty(o,k,{get:Object.getOwnPropertyDescriptor(item,k).get,enumerable:true,configurable:true})}else if(item.hasOwnProperty(k)){o[k]=deep?cloner(true,item[k]):item[k]}}return o}return item}var shallowClone=cloner.bind(null,false),deepClone=cloner.bind(null,true);exports.shallowClone=shallowClone;exports.deepClone=deepClone;function coercePath(target){if(target||target===0||target==="")return target;return[]}function compare(object,description){var ok=true,k=undefined;if(!object)return false;for(k in description){if(_type2["default"].object(description[k])){ok=ok&&compare(object[k],description[k])}else if(_type2["default"].array(description[k])){ok=ok&&!!~description[k].indexOf(object[k])}else{if(object[k]!==description[k])return false}}return ok}function freezer(deep,o){if(typeof o!=="object"||o===null||o instanceof _monkey.Monkey)return;Object.freeze(o);if(!deep)return;if(Array.isArray(o)){var i=undefined,l=undefined;for(i=0,l=o.length;i<l;i++)freezer(true,o[i])}else{var p=undefined,k=undefined;for(k in o){if(_type2["default"].lazyGetter(o,k))continue;p=o[k];if(!p||!o.hasOwnProperty(k)||typeof p!=="object"||Object.isFrozen(p))continue;freezer(true,p)}}}var isFreezeSupported=typeof Object.freeze==="function";var freeze=isFreezeSupported?freezer.bind(null,false):noop,deepFreeze=isFreezeSupported?freezer.bind(null,true):noop;exports.freeze=freeze;exports.deepFreeze=deepFreeze;var notFoundObject={data:undefined,solvedPath:null,exists:false};function getIn(object,path){if(!path)return notFoundObject;var solvedPath=[];var exists=true,c=object,idx=undefined,i=undefined,l=undefined;for(i=0,l=path.length;i<l;i++){if(!c)return{data:undefined,solvedPath:path,exists:false};if(typeof path[i]==="function"){if(!_type2["default"].array(c))return notFoundObject;idx=index(c,path[i]);if(!~idx)return notFoundObject;solvedPath.push(idx);c=c[idx]}else if(typeof path[i]==="object"){if(!_type2["default"].array(c))return notFoundObject;idx=index(c,function(e){return compare(e,path[i])});if(!~idx)return notFoundObject;solvedPath.push(idx);c=c[idx]}else{solvedPath.push(path[i]);exists=typeof c==="object"&&path[i]in c;c=c[path[i]]}}return{data:c,solvedPath:solvedPath,exists:exists}}function makeError(message,data){var err=new Error(message);for(var k in data){err[k]=data[k]}return err}function merger(deep){for(var _len=arguments.length,objects=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){objects[_key-1]=arguments[_key]}var o=objects[0];var t=undefined,i=undefined,l=undefined,k=undefined;for(i=1,l=objects.length;i<l;i++){t=objects[i];for(k in t){if(deep&&_type2["default"].object(t[k])&&!(t[k]instanceof _monkey.Monkey)){o[k]=merger(true,o[k]||{},t[k])}else{o[k]=t[k]}}}return o}var shallowMerge=merger.bind(null,false),deepMerge=merger.bind(null,true);exports.shallowMerge=shallowMerge;exports.deepMerge=deepMerge;function solveRelativePath(base,to){var solvedPath=[];for(var i=0,l=to.length;i<l;i++){var step=to[i];if(step==="."){if(!i)solvedPath=base.slice(0)}else if(step===".."){solvedPath=(!i?base:solvedPath).slice(0,-1)}else{solvedPath.push(step)}}return solvedPath}function solveUpdate(affectedPaths,comparedPaths){var i=undefined,j=undefined,k=undefined,l=undefined,m=undefined,n=undefined,p=undefined,c=undefined,s=undefined;for(i=0,l=affectedPaths.length;i<l;i++){p=affectedPaths[i];if(!p.length)return true;for(j=0,m=comparedPaths.length;j<m;j++){c=comparedPaths[j];if(!c||!c.length)return true;for(k=0,n=c.length;k<n;k++){s=c[k];if(s!=p[k])break;if(k+1===n||k+1===p.length)return true}}}return false}function splice(array,startIndex,nb){nb=Math.max(0,nb);for(var _len2=arguments.length,elements=Array(_len2>3?_len2-3:0),_key2=3;_key2<_len2;_key2++){elements[_key2-3]=arguments[_key2]}if(startIndex>=0)return array.slice(0,startIndex).concat(elements).concat(array.slice(startIndex+nb));return array.slice(0,array.length+startIndex).concat(elements).concat(array.slice(array.length+startIndex+nb))}var uniqid=function(){var i=0;return function(){return i++}}();exports.uniqid=uniqid}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./monkey":4,"./type":5}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var _type=require("./type");var _type2=_interopRequireDefault(_type);var _update2=require("./update");var _update3=_interopRequireDefault(_update2);var _helpers=require("./helpers");var MonkeyDefinition=function MonkeyDefinition(definition){var _this=this;_classCallCheck(this,MonkeyDefinition);var monkeyType=_type2["default"].monkeyDefinition(definition);if(!monkeyType)throw(0,_helpers.makeError)("Baobab.monkey: invalid definition.",{definition:definition});this.type=monkeyType;if(this.type==="object"){this.getter=definition.get;this.projection=definition.cursors||{};this.paths=Object.keys(this.projection).map(function(k){return _this.projection[k];
});this.options=definition.options||{}}else{var offset=1,options={};if(_type2["default"].object(definition[definition.length-1])){offset++;options=definition[definition.length-1]}this.getter=definition[definition.length-offset];this.projection=definition.slice(0,-offset);this.paths=this.projection;this.options=options}this.hasDynamicPaths=this.paths.some(_type2["default"].dynamicPath)};exports.MonkeyDefinition=MonkeyDefinition;var Monkey=function(){function Monkey(tree,pathInTree,definition){var _this2=this;_classCallCheck(this,Monkey);this.tree=tree;this.path=pathInTree;this.definition=definition;this.isRecursive=false;var projection=definition.projection,relative=_helpers.solveRelativePath.bind(null,pathInTree.slice(0,-1));if(definition.type==="object"){this.projection=Object.keys(projection).reduce(function(acc,k){acc[k]=relative(projection[k]);return acc},{});this.depPaths=Object.keys(this.projection).map(function(k){return _this2.projection[k]})}else{this.projection=projection.map(relative);this.depPaths=this.projection}this.state={killed:false};this.listener=function(_ref){var path=_ref.data.path;if(_this2.state.killed)return;var concerned=(0,_helpers.solveUpdate)([path],_this2.relatedPaths());if(concerned)_this2.update()};this.tree.on("write",this.listener);this.update()}_createClass(Monkey,[{key:"checkRecursivity",value:function checkRecursivity(){var _this3=this;this.isRecursive=this.depPaths.some(function(p){return!!_type2["default"].monkeyPath(_this3.tree._monkeys,p)});if(this.isRecursive){this.tree.off("write",this.listener);this.tree.on("write",this.listener)}return this}},{key:"relatedPaths",value:function relatedPaths(){var _this4=this;var paths=undefined;if(this.definition.hasDynamicPaths)paths=this.depPaths.map(function(p){return(0,_helpers.getIn)(_this4.tree._data,p).solvedPath});else paths=this.depPaths;if(!this.isRecursive)return paths;return paths.reduce(function(accumulatedPaths,path){var monkeyPath=_type2["default"].monkeyPath(_this4.tree._monkeys,path);if(!monkeyPath)return accumulatedPaths.concat([path]);var relatedMonkey=(0,_helpers.getIn)(_this4.tree._monkeys,monkeyPath).data;return accumulatedPaths.concat(relatedMonkey.relatedPaths())},[])}},{key:"update",value:function update(){var deps=this.tree.project(this.projection);var lazyGetter=function(tree,def,data){var cache=null,alreadyComputed=false;return function(){if(!alreadyComputed){cache=def.getter.apply(tree,def.type==="object"?[data]:data);if(tree.options.immutable&&def.options.immutable!==false)(0,_helpers.deepFreeze)(cache);alreadyComputed=true}return cache}}(this.tree,this.definition,deps);lazyGetter.isLazyGetter=true;if(this.tree.options.lazyMonkeys){this.tree._data=(0,_update3["default"])(this.tree._data,this.path,{type:"monkey",value:lazyGetter},this.tree.options).data}else{var result=(0,_update3["default"])(this.tree._data,this.path,{type:"set",value:lazyGetter(),options:{mutableLeaf:!this.definition.options.immutable}},this.tree.options);if("data"in result)this.tree._data=result.data}return this}},{key:"release",value:function release(){this.tree.off("write",this.listener);this.state.killed=true;delete this.projection;delete this.depPaths;delete this.tree}}]);return Monkey}();exports.Monkey=Monkey},{"./helpers":3,"./type":5,"./update":6}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _monkey=require("./monkey");var type={};function anyOf(target,allowed){return allowed.some(function(t){return type[t](target)})}type.array=function(target){return Array.isArray(target)};type.object=function(target){return target&&typeof target==="object"&&!Array.isArray(target)&&!(target instanceof Date)&&!(target instanceof RegExp)&&!(typeof Map==="function"&&target instanceof Map)&&!(typeof Set==="function"&&target instanceof Set)};type.string=function(target){return typeof target==="string"};type.number=function(target){return typeof target==="number"};type["function"]=function(target){return typeof target==="function"};type.primitive=function(target){return target!==Object(target)};type.splicer=function(target){if(!type.array(target)||target.length<2)return false;return anyOf(target[0],["number","function","object"])&&type.number(target[1])};var ALLOWED_FOR_PATH=["string","number","function","object"];type.path=function(target){if(!target&&target!==0&&target!=="")return false;return[].concat(target).every(function(step){return anyOf(step,ALLOWED_FOR_PATH)})};type.dynamicPath=function(path){return path.some(function(step){return type["function"](step)||type.object(step)})};type.monkeyPath=function(data,path){var subpath=[];var c=data,i=undefined,l=undefined;for(i=0,l=path.length;i<l;i++){subpath.push(path[i]);if(typeof c!=="object")return null;c=c[path[i]];if(c instanceof _monkey.Monkey)return subpath}return null};type.lazyGetter=function(o,propertyKey){var descriptor=Object.getOwnPropertyDescriptor(o,propertyKey);return descriptor&&descriptor.get&&descriptor.get.isLazyGetter===true};type.monkeyDefinition=function(definition){if(type.object(definition)){if(!type["function"](definition.get)||definition.cursors&&(!type.object(definition.cursors)||!Object.keys(definition.cursors).every(function(k){return type.path(definition.cursors[k])})))return null;return"object"}else if(type.array(definition)){var offset=1;if(type.object(definition[definition.length-1]))offset++;if(!type["function"](definition[definition.length-offset])||!definition.slice(0,-offset).every(function(p){return type.path(p)}))return null;return"array"}return null};type.watcherMapping=function(definition){return type.object(definition)&&Object.keys(definition).every(function(k){return type.path(definition[k])})};var VALID_OPERATIONS=["set","apply","push","unshift","concat","pop","shift","deepMerge","merge","splice","unset"];type.operationType=function(string){return typeof string==="string"&&!!~VALID_OPERATIONS.indexOf(string)};exports["default"]=type;module.exports=exports["default"]},{"./monkey":4}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=update;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++)arr2[i]=arr[i];return arr2}else{return Array.from(arr)}}var _type=require("./type");var _type2=_interopRequireDefault(_type);var _helpers=require("./helpers");function err(operation,expectedTarget,path){return(0,_helpers.makeError)('Baobab.update: cannot apply the "'+operation+'" on '+("a non "+expectedTarget+" (path: /"+path.join("/")+")."),{path:path})}function update(data,path,operation){var opts=arguments.length<=3||arguments[3]===undefined?{}:arguments[3];var operationType=operation.type;var value=operation.value;var _operation$options=operation.options;var operationOptions=_operation$options===undefined?{}:_operation$options;var dummy={root:data},dummyPath=["root"].concat(_toConsumableArray(path)),currentPath=[];var p=dummy,i=undefined,l=undefined,s=undefined;for(i=0,l=dummyPath.length;i<l;i++){s=dummyPath[i];if(i>0)currentPath.push(s);if(i===l-1){if(operationType==="set"){if(opts.pure&&p[s]===value)return{node:p[s]};if(_type2["default"].lazyGetter(p,s)){Object.defineProperty(p,s,{value:value,enumerable:true,configurable:true})}else if(opts.persistent&&!operationOptions.mutableLeaf){p[s]=(0,_helpers.shallowClone)(value)}else{p[s]=value}}else if(operationType==="monkey"){Object.defineProperty(p,s,{get:value,enumerable:true,configurable:true})}else if(operationType==="apply"){var result=value(p[s]);if(opts.pure&&p[s]===result)return{node:p[s]};if(_type2["default"].lazyGetter(p,s)){Object.defineProperty(p,s,{value:result,enumerable:true,configurable:true})}else if(opts.persistent){p[s]=(0,_helpers.shallowClone)(result)}else{p[s]=result}}else if(operationType==="push"){if(!_type2["default"].array(p[s]))throw err("push","array",currentPath);if(opts.persistent)p[s]=p[s].concat([value]);else p[s].push(value)}else if(operationType==="unshift"){if(!_type2["default"].array(p[s]))throw err("unshift","array",currentPath);if(opts.persistent)p[s]=[value].concat(p[s]);else p[s].unshift(value)}else if(operationType==="concat"){if(!_type2["default"].array(p[s]))throw err("concat","array",currentPath);if(opts.persistent)p[s]=p[s].concat(value);else p[s].push.apply(p[s],value)}else if(operationType==="splice"){if(!_type2["default"].array(p[s]))throw err("splice","array",currentPath);if(opts.persistent)p[s]=_helpers.splice.apply(null,[p[s]].concat(value));else p[s].splice.apply(p[s],value)}else if(operationType==="pop"){if(!_type2["default"].array(p[s]))throw err("pop","array",currentPath);if(opts.persistent)p[s]=(0,_helpers.splice)(p[s],-1,1);else p[s].pop()}else if(operationType==="shift"){if(!_type2["default"].array(p[s]))throw err("shift","array",currentPath);if(opts.persistent)p[s]=(0,_helpers.splice)(p[s],0,1);else p[s].shift()}else if(operationType==="unset"){if(_type2["default"].object(p))delete p[s];else if(_type2["default"].array(p))p.splice(s,1)}else if(operationType==="merge"){if(!_type2["default"].object(p[s]))throw err("merge","object",currentPath);if(opts.persistent)p[s]=(0,_helpers.shallowMerge)({},p[s],value);else p[s]=(0,_helpers.shallowMerge)(p[s],value)}else if(operationType==="deepMerge"){if(!_type2["default"].object(p[s]))throw err("deepMerge","object",currentPath);if(opts.persistent)p[s]=(0,_helpers.deepMerge)({},p[s],value);else p[s]=(0,_helpers.deepMerge)(p[s],value)}if(opts.immutable&&!operationOptions.mutableLeaf)(0,_helpers.deepFreeze)(p);break}else if(_type2["default"].primitive(p[s])){p[s]={}}else if(opts.persistent){p[s]=(0,_helpers.shallowClone)(p[s])}if(opts.immutable&&l>0)(0,_helpers.freeze)(p);p=p[s]}if(_type2["default"].lazyGetter(p,s))return{data:dummy.root};return{data:dummy.root,node:p[s]}}module.exports=exports["default"]},{"./helpers":3,"./type":5}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(_x,_x2,_x3){var _again=true;_function:while(_again){var object=_x,property=_x2,receiver=_x3;_again=false;if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{_x=parent;_x2=property;_x3=receiver;_again=true;desc=parent=undefined;continue _function}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}}};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var _emmett=require("emmett");var _emmett2=_interopRequireDefault(_emmett);var _cursor=require("./cursor");var _cursor2=_interopRequireDefault(_cursor);var _type=require("./type");var _type2=_interopRequireDefault(_type);var _helpers=require("./helpers");var Watcher=function(_Emitter){_inherits(Watcher,_Emitter);function Watcher(tree,mapping){var _this=this;_classCallCheck(this,Watcher);_get(Object.getPrototypeOf(Watcher.prototype),"constructor",this).call(this);this.tree=tree;this.mapping=null;this.state={killed:false};this.refresh(mapping);this.handler=function(e){if(_this.state.killed)return;var watchedPaths=_this.getWatchedPaths();if((0,_helpers.solveUpdate)(e.data.paths,watchedPaths))return _this.emit("update")};this.tree.on("update",this.handler)}_createClass(Watcher,[{key:"getWatchedPaths",value:function getWatchedPaths(){var _this2=this;var rawPaths=Object.keys(this.mapping).map(function(k){var v=_this2.mapping[k];if(v instanceof _cursor2["default"])return v.solvedPath;return _this2.mapping[k]});return rawPaths.reduce(function(cp,p){p=[].concat(p);if(_type2["default"].dynamicPath(p))p=(0,_helpers.getIn)(_this2.tree._data,p).solvedPath;if(!p)return cp;var monkeyPath=_type2["default"].monkeyPath(_this2.tree._monkeys,p);if(monkeyPath)return cp.concat((0,_helpers.getIn)(_this2.tree._monkeys,monkeyPath).data.relatedPaths());return cp.concat([p])},[])}},{key:"getCursors",value:function getCursors(){var _this3=this;var cursors={};Object.keys(this.mapping).forEach(function(k){var path=_this3.mapping[k];if(path instanceof _cursor2["default"])cursors[k]=path;else cursors[k]=_this3.tree.select(path)});return cursors}},{key:"refresh",value:function refresh(mapping){if(!_type2["default"].watcherMapping(mapping))throw(0,_helpers.makeError)("Baobab.watch: invalid mapping.",{mapping:mapping});this.mapping=mapping;var projection={};for(var k in mapping){projection[k]=mapping[k]instanceof _cursor2["default"]?mapping[k].path:mapping[k]}this.get=this.tree.project.bind(this.tree,projection)}},{key:"release",value:function release(){this.tree.off("update",this.handler);this.state.killed=true;this.kill()}}]);return Watcher}(_emmett2["default"]);exports["default"]=Watcher;module.exports=exports["default"]},{"./cursor":2,"./helpers":3,"./type":5,emmett:8}],8:[function(require,module,exports){(function(){"use strict";var __allowedOptions={once:"boolean",scope:"object"};var __order=0;function shallowMerge(o1,o2){var o={},k;for(k in o1)o[k]=o1[k];for(k in o2)o[k]=o2[k];return o}function isPlainObject(v){return v&&typeof v==="object"&&!Array.isArray(v)&&!(v instanceof Function)&&!(v instanceof RegExp)}function forIn(object,fn,scope){var symbols,k,i,l;for(k in object)fn.call(scope||null,k,object[k]);if(Object.getOwnPropertySymbols){symbols=Object.getOwnPropertySymbols(object);for(i=0,l=symbols.length;i<l;i++)fn.call(scope||null,symbols[i],object[symbols[i]])}}var Emitter=function(){this._enabled=true;this.unbindAll()};Emitter.prototype.unbindAll=function(){this._handlers={};this._handlersAll=[];this._handlersComplex=[];return this};Emitter.prototype.on=function(a,b,c){var i,l,k,event,eArray,handlersList,bindingObject;if(isPlainObject(a)){forIn(a,function(name,fn){this.on(name,fn,b)},this);return this}if(typeof a==="function"){c=b;b=a;a=null}eArray=[].concat(a);for(i=0,l=eArray.length;i<l;i++){event=eArray[i];bindingObject={order:__order++,fn:b};if(typeof event==="string"||typeof event==="symbol"){if(!this._handlers[event])this._handlers[event]=[];handlersList=this._handlers[event];bindingObject.type=event}else if(event instanceof RegExp){handlersList=this._handlersComplex;bindingObject.pattern=event}else if(event===null){handlersList=this._handlersAll}else{throw Error("Emitter.on: invalid event.")}for(k in c||{})if(__allowedOptions[k])bindingObject[k]=c[k];handlersList.push(bindingObject)}return this};Emitter.prototype.once=function(){var args=Array.prototype.slice.call(arguments),li=args.length-1;if(isPlainObject(args[li])&&args.length>1)args[li]=shallowMerge(args[li],{once:true});else args.push({once:true});return this.on.apply(this,args)};function filter(target,fn){target=target||[];var a=[],l,i;for(i=0,l=target.length;i<l;i++)if(target[i].fn!==fn)a.push(target[i]);return a}Emitter.prototype.off=function(events,fn){var i,n,k,event;if(arguments.length===1&&typeof events==="function"){fn=arguments[0];for(k in this._handlers){this._handlers[k]=filter(this._handlers[k],fn);if(this._handlers[k].length===0)delete this._handlers[k]}this._handlersAll=filter(this._handlersAll,fn);this._handlersComplex=filter(this._handlersComplex,fn)}else if(arguments.length===1&&(typeof events==="string"||typeof events==="symbol")){delete this._handlers[events]}else if(arguments.length===2){var eArray=[].concat(events);for(i=0,n=eArray.length;i<n;i++){event=eArray[i];this._handlers[event]=filter(this._handlers[event],fn);if((this._handlers[event]||[]).length===0)delete this._handlers[event]}}else if(isPlainObject(events)){forIn(events,this.off,this)}return this};Emitter.prototype.listeners=function(event){var handlers=this._handlersAll||[],complex=false,h,i,l;if(!event)throw Error("Emitter.listeners: no event provided.");handlers=handlers.concat(this._handlers[event]||[]);for(i=0,l=this._handlersComplex.length;i<l;i++){h=this._handlersComplex[i];if(~event.search(h.pattern)){complex=true;handlers.push(h)}}if(this._handlersAll.length||complex)return handlers.sort(function(a,b){return a.order-b.order});else return handlers.slice(0)};Emitter.prototype.emit=function(events,data){if(!this._enabled)return this;if(isPlainObject(events)){forIn(events,this.emit,this);return this}var eArray=[].concat(events),onces=[],event,parent,handlers,handler,i,j,l,m;for(i=0,l=eArray.length;i<l;i++){handlers=this.listeners(eArray[i]);for(j=0,m=handlers.length;j<m;j++){handler=handlers[j];event={type:eArray[i],target:this};if(arguments.length>1)event.data=data;handler.fn.call("scope"in handler?handler.scope:this,event);if(handler.once)onces.push(handler)}for(j=onces.length-1;j>=0;j--){parent=onces[j].type?this._handlers[onces[j].type]:onces[j].pattern?this._handlersComplex:this._handlersAll;parent.splice(parent.indexOf(onces[j]),1)}}return this};Emitter.prototype.kill=function(){this.unbindAll();this._handlers=null;this._handlersAll=null;this._handlersComplex=null;this._enabled=false;this.unbindAll=this.on=this.once=this.off=this.emit=this.listeners=Function.prototype};Emitter.prototype.disable=function(){this._enabled=false;return this};Emitter.prototype.enable=function(){this._enabled=true;return this};Emitter.version="3.1.1";if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=Emitter;exports.Emitter=Emitter}else if(typeof define==="function"&&define.amd)define("emmett",[],function(){return Emitter});else this.Emitter=Emitter}).call(this)},{}],"cerebral-model-baobab":[function(require,module,exports){var Baobab=require("baobab");function deepmerge(target,src){var array=Array.isArray(src);var dst=array&&[]||{};if(array){target=target||[];dst=src.slice();src.forEach(function(e,i){if(typeof dst[i]==="undefined"){dst[i]=e}else if(typeof e==="object"){dst[i]=deepmerge(target[i],e)}})}else{if(target&&typeof target==="object"){Object.keys(target).forEach(function(key){dst[key]=target[key]})}Object.keys(src).forEach(function(key){if(typeof src[key]!=="object"||!src[key]){dst[key]=src[key]}else{if(!target[key]){dst[key]=src[key]}else{dst[key]=deepmerge(target[key],src[key])}}})}return dst}var Model=function(initialState,options){options=options||{};var tree=new Baobab(initialState,options);var model=function(controller){controller.on("reset",function(){tree.set(initialState)});controller.on("seek",function(seek,recording){recording.initialState.forEach(function(state){tree.set(state.path,state.value)})});return{tree:tree,logModel:function(){return tree.get()},accessors:{get:function(path){return tree.get(path)},toJSON:function(){return tree.toJSON()},serialize:function(path){return tree.serialize(path)},"export":function(){return tree.serialize()},keys:function(path){return Object.keys(tree.get(path))},findWhere:function(path,obj){var keysCount=Object.keys(obj).length;return tree.get(path).filter(function(item){return Object.keys(item).filter(function(key){return key in obj&&obj[key]===item[key]}).length===keysCount}).pop()}},mutators:{set:function(path,value){tree.set(path,value)},"import":function(newState){var newState=deepmerge(initialState,newState);tree.set(newState)},unset:function(path,keys){if(keys){keys.forEach(function(key){tree.unset(path.concat(key))})}else{tree.unset(path)}},push:function(path,value){tree.push(path,value)},splice:function(){var args=[].slice.call(arguments);tree.splice.call(tree,args.shift(),args)},merge:function(path,value){tree.merge(path,value)},concat:function(path,value){tree.apply(path,function(existingValue){return existingValue.concat(value)})},pop:function(path){tree.apply(path,function(existingValue){var copy=existingValue.slice();copy.pop();return copy})},shift:function(path){tree.apply(path,function(existingValue){var copy=existingValue.slice();copy.shift();return copy})},unshift:function(path,value){tree.unshift(path,value)}}}};model.tree=tree;return model};Model.monkey=Baobab.monkey;Model.dynamicNode=Baobab.dynamicNode;module.exports=Model},{baobab:1}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var utils=require("./utils.js");module.exports=function(model){var registered=[];var computed=[];var createMapper=function(cb){var initialRun=true;var currentState={};var currentValue;var get=function(path){if(typeof path==="function"){return currentState["COMPUTED_"+registered.indexOf(path)]=getComputedValue(path)}else{return currentState[path.join(".%.")]=model.accessors.get(path)}};return function(){var hasChanged=Object.keys(currentState).reduce(function(hasChanged,key){if(hasChanged){return true}if(key.indexOf("COMPUTED")===0){return getComputedValue(registered[key.split("_")[1]])!==currentState[key]}else{return model.accessors.get(key.split(".%."))!==currentState[key]}},false);if(hasChanged||initialRun){currentState={};initialRun=false;return currentValue=cb(get)}else{return currentValue}}};var has=function(computedFunc){return registered.indexOf(computedFunc)!==-1};var getComputedValue=function(computedFunc){if(!has(computedFunc)){registered.push(computedFunc);computed.push(createMapper(computedFunc))}return computed[registered.indexOf(computedFunc)]()};return{register:function(computeFunc){registered.push(computeFunc);computed.push(createMapper(computeFunc));return this.getComputedValue(computeFunc)},has:has,getComputedValue:getComputedValue}}},{"./utils.js":13}],2:[function(require,module,exports){var utils=require("./utils.js");module.exports=function(signalStore,signalMethods,controller,model){var currentSignal=null;var currentSeek=0;var currentRecording=null;var lastSignal=null;var durationTimer=null;var playbackTimers=[];var pauseState=null;var timers=[];var duration=0;var started=null;var ended=null;var isPlaying=false;var isRecording=false;var isCatchingUp=false;var startSeek=0;var catchup=null;var triggerSignal=function(signal){var signalName=signal.name.split(".");var signalMethodPath=signalMethods;while(signalName.length){signalMethodPath=signalMethodPath[signalName.shift()]}currentSignal=signal;signalMethodPath(signal.input,{isRecorded:true})};return{seek:function(seek){startSeek=seek;clearTimeout(durationTimer);playbackTimers.forEach(clearTimeout);controller.emit("seek",startSeek,currentRecording);if(signalStore.isRemembering()){return}catchup=currentRecording.signals.filter(function(signal){return signal.start-currentRecording.start<startSeek});isCatchingUp=true;catchup.forEach(triggerSignal);isCatchingUp=false},getCurrentSignal:function(){return currentSignal},createTimer:function(){var update=function(){duration+=500;controller.emit("duration",duration);if(duration<currentRecording.duration){durationTimer=setTimeout(update,500);controller.emit("change")}}.bind(this);durationTimer=setTimeout(update,500)},resetState:function(){controller.emit("recorderReset",currentRecording)},play:function(){if(isPlaying||isRecording){throw new Error("CEREBRAL Recorder - You can not play while already playing or recording")}this.createTimer();var signalsCount=currentRecording.signals.length;var startIndex=catchup.length;for(var x=startIndex;x<signalsCount;x++){var signal=currentRecording.signals[x];var durationTarget=signal.start-currentRecording.start-startSeek;playbackTimers.push(setTimeout(triggerSignal.bind(null,signal),durationTarget))}isPlaying=true;started=Date.now()},record:function(options){if(signalStore.isRemembering()){return}options=options||{};if(currentRecording){this.resetState()}var paths=options.paths||[[]];var state=paths.map(function(path){return{path:path,value:controller.get(path)}});currentRecording={initialState:state,start:Date.now(),signals:[]};isRecording=true},stop:function(){var wasPlaying=isPlaying;clearTimeout(durationTimer);isPlaying=false;isRecording=false;if(signalStore.isRemembering()||wasPlaying){return}currentRecording.end=Date.now();currentRecording.duration=currentRecording.end-currentRecording.start},pause:function pause(){if(signalStore.isRemembering()){return}ended=Date.now();currentSeek=ended-started;clearTimeout(durationTimer);playbackTimers.forEach(clearTimeout);isPlaying=false},addSignal:function(signal){currentRecording.signals.push(signal)},isRecording:function(){return isRecording},isPlaying:function(){return isPlaying},isCatchingUp:function(){return isCatchingUp},getRecording:function(){return currentRecording},getCurrentSeek:function(){return currentSeek},loadRecording:function(recording){currentRecording=recording}}}},{"./utils.js":13}],3:[function(require,module,exports){var utils=require("./utils.js");module.exports=function(controller,model,allModules){var initialState={};var registerSignals=function(moduleName,signals){var scopedSignals=Object.keys(signals).reduce(function(scopedSignals,key){scopedSignals[moduleName+"."+key]=signals[key];return scopedSignals},{});return controller.signals(scopedSignals,{modulePath:moduleName.split(".")})};var registerSignalsSync=function(moduleName,signals){var scopedSignals=Object.keys(signals).reduce(function(scopedSignals,key){scopedSignals[moduleName+"."+key]=signals[key];return scopedSignals},{});return controller.signalsSync(scopedSignals,{modulePath:moduleName.split(".")})};var registerServices=function(moduleName,services){var scopedServices=Object.keys(services).reduce(function(scopedServices,key){scopedServices[moduleName+"."+key]=services[key];return scopedServices},{});controller.services(scopedServices)};var registerInitialState=function(moduleName,state){utils.setDeep(initialState,moduleName,state);model.mutators.set(moduleName.split("."),state)};controller.on("reset",function(){model.mutators.merge([],initialState)});return function registerModules(parentModuleName,modules){if(arguments.length===1){modules=parentModuleName;parentModuleName=null}Object.keys(modules).forEach(function(moduleName){var moduleConstructor=modules[moduleName];var actualName=moduleName;if(parentModuleName){moduleName=parentModuleName+"."+moduleName}var signals=utils.setDeep(controller.signals,moduleName,{});var moduleExport={name:actualName,path:moduleName.split(".")};var module={name:moduleName,alias:function(alias){allModules[alias]=moduleExport},signals:registerSignals.bind(null,moduleName),signalsSync:registerSignalsSync.bind(null,moduleName),services:registerServices.bind(null,moduleName),state:registerInitialState.bind(null,moduleName),getSignals:function(){return signals},modules:registerModules.bind(null,moduleName)};var constructedModule=moduleConstructor(module,controller);allModules[moduleName]=Object.keys(constructedModule||{}).reduce(function(module,key){module[key]=constructedModule[key];return module},moduleExport)});return allModules}}},{"./utils.js":13}],4:[function(require,module,exports){(function(global){var utils=require("./utils.js");var createActionArgs=require("./createActionArgs.js");var createNext=require("./createNext.js");var analyze=require("./analyze.js");var staticTree=require("./staticTree");var types=require("./types.js");var createModulesArg=require("./createModulesArg.js");var batchedSignals=[];var pending=false;var requestAnimationFrame=global.requestAnimationFrame||function(cb){setTimeout(cb,0)};module.exports=function(signalStore,recorder,devtools,controller,model,services,compute,modules){return function(){var args=[].slice.call(arguments);var signalName=args.shift();var defaultOptions=args[1]||{};defaultOptions.modulePath=defaultOptions.modulePath||[];var chain=args[0]||[];if(utils.isDeveloping()){analyze(signalName,chain)}var signalChain=function(payload,options){if(utils.isDeveloping()&&!signalStore.isRemembering()&&signalStore.getCurrentIndex()!==-1&&signalStore.getCurrentIndex()<signalStore.getSignals().length-1){console.warn("Cerebral - Looking in the past, ignored signal "+signalName);return}options=options||{};if(recorder.isPlaying()&&!options.isRecorded){return}var tree=staticTree(signalChain.chain);var actions=tree.actions;var runSync=defaultOptions.isSync||options.isSync;var branches=options.branches||tree.branches;var runSignal=function(){var signalArgs=payload||{};if(utils.isDeveloping()){try{JSON.stringify(signalArgs)}catch(e){console.log("Not serializable",signalArgs);throw new Error("Cerebral - Could not serialize input to signal. Please check signal "+signalName)}}var start=Date.now();var recorderSignal={name:signalName,input:payload,start:start,asyncActionPaths:[],asyncActionResults:[]};var signal={name:signalName,start:start,isSync:runSync,isExecuting:true,branches:branches,duration:0,input:payload};if(!signalStore.isRemembering()&&!recorder.isCatchingUp()){controller.emit("signalStart",{signal:signal})}if(recorder.isRecording()){recorder.addSignal(recorderSignal)}signalStore.addSignal(signal);var runBranch=function(branch,index,start){var currentBranch=branch[index];if(!currentBranch&&branch===signal.branches&&!signalStore.isRemembering()&&!recorder.isCatchingUp()){if(branch[index-1]){branch[index-1].duration=Date.now()-start}signal.isExecuting=false;controller.emit("signalEnd",{signal:signal});controller.emit("change",{signal:signal});devtools&&devtools.update();return}if(!currentBranch){return}if(Array.isArray(currentBranch)){if(signalStore.isRemembering()){currentBranch.forEach(function(action){utils.merge(signalArgs,action.output);if(action.outputPath){runBranch(action.outputs[action.outputPath],0)}});runBranch(branch,index+1)}else if(recorder.isCatchingUp()){var currentSignal=recorder.getCurrentSignal();currentBranch.forEach(function(action){var recordedAction=currentSignal.asyncActionResults[currentSignal.asyncActionPaths.indexOf(action.path.join("."))];utils.merge(signalArgs,recordedAction.output);if(action.outputPath){runBranch(action.outputs[recordedAction.outputPath],0)}});runBranch(branch,index+1)}else{controller.emit("change",{signal:signal});var promises=currentBranch.map(function(action){controller.emit("actionStart",{action:action,signal:signal});var actionFunc=actions[action.actionIndex];var inputArg=actionFunc.defaultInput?utils.merge({},actionFunc.defaultInput,signalArgs):signalArgs;var actionArgs=createActionArgs.async(action,inputArg,model,compute);if(utils.isDeveloping()&&actionFunc.input){utils.verifyInput(action.name,signal.name,actionFunc.input,inputArg)}signalStore.addAsyncAction();action.isExecuting=true;action.input=utils.merge({},inputArg);var next=createNext.async(actionFunc);var modulesArg=createModulesArg(modules,actionArgs[1],services);actionFunc.call(null,{input:actionArgs[0],
state:actionArgs[1],output:next.fn,services:services,modules:modulesArg,module:defaultOptions.modulePath.reduce(function(modules,key){return modules[key]},modulesArg)});return next.promise.then(function(result){action.hasExecuted=true;action.isExecuting=false;action.output=result.arg;utils.merge(signalArgs,result.arg);signalStore.removeAsyncAction();if(recorder.isRecording()){recorderSignal.asyncActionPaths.push(action.path.join("."));recorderSignal.asyncActionResults.push({output:result.arg,outputPath:result.path})}if(result.path){action.outputPath=result.path;controller.emit("actionEnd",{action:action,signal:signal});var result=runBranch(action.outputs[result.path],0,Date.now());controller.emit("change",{signal:signal});devtools&&devtools.update();return result}else{devtools&&devtools.update()}})});devtools&&devtools.update();return Promise.all(promises).then(function(){return runBranch(branch,index+1,Date.now())}).catch(function(error){controller.emit("error",error);throw error})}}else{if(signalStore.isRemembering()){var action=currentBranch;action.mutations.forEach(function(mutation){model.mutators[mutation.name].apply(null,[mutation.path.slice()].concat(mutation.args))});if(action.outputPath){runBranch(action.outputs[action.outputPath],0)}runBranch(branch,index+1)}else{var action=currentBranch;controller.emit("actionStart",{action:action,signal:signal});var actionFunc=actions[action.actionIndex];var inputArg=actionFunc.defaultInput?utils.merge({},actionFunc.defaultInput,signalArgs):signalArgs;var actionArgs=createActionArgs.sync(action,inputArg,model,compute);if(utils.isDeveloping()&&actionFunc.input){utils.verifyInput(action.name,signal.name,actionFunc.input,inputArg)}action.mutations=[];action.input=utils.merge({},inputArg);var next=createNext.sync(actionFunc,signal.name);var modulesArg=createModulesArg(modules,actionArgs[1],services);actionFunc.call(null,{input:actionArgs[0],state:actionArgs[1],output:next,services:services,modules:modulesArg,module:defaultOptions.modulePath.reduce(function(exportedModule,key){return exportedModule[key]},modulesArg)});var result=next._result||{};utils.merge(signalArgs,result.arg);action.isExecuting=false;action.hasExecuted=true;action.output=result.arg;if(!branch[index+1]||Array.isArray(branch[index+1])){action.duration=Date.now()-start}if(result.path){action.outputPath=result.path;var result=runBranch(action.outputs[result.path],0,start);if(result&&result.then){return result.then(function(){return runBranch(branch,index+1,Date.now())})}else{return runBranch(branch,index+1,start)}}else if(result.then){return result.then(function(){controller.emit("actionEnd",{action:action,signal:signal});return runBranch(branch,index+1,start)})}else{controller.emit("actionEnd",{action:action,signal:signal});return runBranch(branch,index+1,start)}}}};runBranch(signal.branches,0,Date.now());return};if(runSync||signalStore.isRemembering()||recorder.isCatchingUp()){runSignal()}else{batchedSignals.push(runSignal);if(!pending){requestAnimationFrame(function(){while(batchedSignals.length){batchedSignals.shift()()}pending=false});pending=true}}};signalChain.chain=chain;signalChain.sync=function(payload){signalChain(payload,{isSync:true})};signalChain.signalName=signalName;return signalChain}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./analyze.js":7,"./createActionArgs.js":8,"./createModulesArg.js":9,"./createNext.js":10,"./staticTree":11,"./types.js":12,"./utils.js":13}],5:[function(require,module,exports){var utils=require("./utils.js");module.exports=function(signalMethods,controller){var signals=[];var willKeepState=false;var executingAsyncActionsCount=0;var isRemembering=false;var currentIndex=signals.length-1;var hasRememberedInitial=false;return{toggleKeepState:function(){willKeepState=!willKeepState},addAsyncAction:function(){executingAsyncActionsCount++},removeAsyncAction:function(){executingAsyncActionsCount--},addSignal:function(signal){if(utils.isDeveloping()){currentIndex++;if(isRemembering){return}if(currentIndex<signals.length){signals.splice(currentIndex,signals.length-currentIndex)}signals.push(signal)}},rememberNow:function(){if(!signals.length){return}this.remember(signals.length-1)},reset:function(){if(!isRemembering){signals=[];currentIndex=-1;controller.emit("reset")}},rememberInitial:function(index){if(hasRememberedInitial){return}hasRememberedInitial=true;this.remember(index)},remember:function(index){isRemembering=true;controller.emit("reset");if(index===-1){currentIndex=index;isRemembering=false}else{currentIndex=-1;try{for(var x=0;x<=index;x++){var signal=signals[x];if(!signal){break}var signalName=signal.name.split(".");var signalMethodPath=signalMethods;while(signalName.length){signalMethodPath=signalMethodPath[signalName.shift()]}signalMethodPath(signal.input,{branches:signal.branches});currentIndex=x}}catch(e){console.log(e);console.warn("CEREBRAL - There was an error remembering state, it has been reset");this.reset()}}controller.emit("change");isRemembering=false},removeRunningSignals:function(){for(var x=0;x<signals.length;x++){if(signals[x].isExecuting){signals.splice(x,1);x--}}},getSignals:function(){return signals},setSignals:function(newSignals){signals=signals.concat(newSignals)},isExecutingAsync:function(){return!!executingAsyncActionsCount},isRemembering:function(){return isRemembering},willKeepState:function(){return willKeepState},getCurrentIndex:function(){return currentIndex}}}},{"./utils.js":13}],6:[function(require,module,exports){var utils=require("./utils.js");module.exports=function(signalStore,controller){if(!utils.isDeveloping()){return{update:function(){},start:function(){}}}var isInitialized=false;var disableDebugger=false;var getDetail=function(){return JSON.stringify({signals:signalStore.getSignals(),willKeepState:signalStore.willKeepState(),disableDebugger:disableDebugger,currentSignalIndex:signalStore.getCurrentIndex(),isExecutingAsync:signalStore.isExecutingAsync(),isRemembering:signalStore.isRemembering(),computedPaths:[]})};var update=utils.debounce(function(){if(disableDebugger){return}var event=new CustomEvent("cerebral.dev.update",{detail:getDetail()});window.dispatchEvent(event)},100);var initialize=function(){if(isInitialized){return}disableDebugger=utils.hasLocalStorage()&&localStorage.getItem("cerebral_disable_debugger")?JSON.parse(localStorage.getItem("cerebral_disable_debugger")):false;var signals=utils.hasLocalStorage()&&localStorage.getItem("cerebral_signals")?JSON.parse(localStorage.getItem("cerebral_signals")):[];var willKeepState=utils.hasLocalStorage()&&localStorage.getItem("cerebral_willKeepState")?JSON.parse(localStorage.getItem("cerebral_willKeepState")):true;if(willKeepState){signalStore.toggleKeepState()}isInitialized=true;if(signalStore.isExecutingAsync()){controller.once("signalEnd",function(){var event=new CustomEvent("cerebral.dev.cerebralPong",{detail:getDetail()});signalStore.setSignals(signals);signalStore.remember(signalStore.getSignals().length-1);window.dispatchEvent(event)})}else{var event=new CustomEvent("cerebral.dev.cerebralPong",{detail:getDetail()});signalStore.setSignals(signals);signalStore.rememberInitial(signalStore.getSignals().length-1);window.dispatchEvent(event)}};window.addEventListener("cerebral.dev.debuggerPing",function(){if(utils.isDeveloping()){initialize()}});window.addEventListener("cerebral.dev.requestUpdate",function(){update()});window.addEventListener("cerebral.dev.toggleKeepState",function(){signalStore.toggleKeepState();update()});window.addEventListener("cerebral.dev.toggleDisableDebugger",function(){disableDebugger=!disableDebugger;if(disableDebugger&&signalStore.willKeepState()){signalStore.toggleKeepState()}var event=new CustomEvent("cerebral.dev.update",{detail:getDetail()});window.dispatchEvent(event)});window.addEventListener("cerebral.dev.resetStore",function(){signalStore.reset();controller.emit("change");update()});window.addEventListener("cerebral.dev.remember",function(event){signalStore.remember(event.detail);update()});window.addEventListener("cerebral.dev.logComputedPath",function(event){console.log("CEREBRAL - Computed path:",controller.getComputedValue(event.detail))});window.addEventListener("cerebral.dev.logPath",function(event){var name=event.detail.name;var value=controller.get(event.detail.path);console.log("CEREBRAL - "+name+":",value.toJS?value.toJS():value)});window.addEventListener("cerebral.dev.logModel",function(event){console.log("CEREBRAL - model:",controller.logModel())});window.addEventListener("unload",function(){signalStore.removeRunningSignals();utils.hasLocalStorage()&&localStorage.setItem("cerebral_signals",isInitialized&&signalStore.willKeepState()?JSON.stringify(signalStore.getSignals()):JSON.stringify([]));utils.hasLocalStorage()&&localStorage.setItem("cerebral_willKeepState",isInitialized&&JSON.stringify(signalStore.willKeepState()));utils.hasLocalStorage()&&localStorage.setItem("cerebral_disable_debugger",isInitialized&&JSON.stringify(disableDebugger))});return{update:update,start:function(){var event=new Event("cerebral.dev.cerebralPing");window.dispatchEvent(event)}}}},{"./utils.js":13}],7:[function(require,module,exports){var utils=require("./utils.js");module.exports=function(signalName,actions){var traverse=function(actions,parentActions,parentIndex){actions.forEach(function(action,index){if(typeof action==="undefined"){throw new Error(['Cerebral: Action number "'+index+'" in signal "'+signalName+'" does not exist. Check that you have spelled it correctly!'].join(""))}if(Array.isArray(action)){traverse(action,actions,index)}else{var nextPaths=actions[index+1];if(action.output&&(parentActions&&typeof nextPaths==="function"||!parentActions&&(typeof nextPaths!=="function"||!nextPaths)||parentActions&&typeof parentActions[parentIndex+1]!=="function")){throw new Error(['Cerebral: The action "'+utils.getFunctionName(action)+'" in signal "'+signalName+'" has an output definition, but there is '+"no action to receive it. "+(nextPaths?"But there are "+JSON.stringify(Object.keys(nextPaths))+" paths, should it be outputs?":"")].join(""))}else if(action.outputs&&(!nextPaths||typeof nextPaths==="function")){throw new Error(['Cerebral: The action "'+utils.getFunctionName(action)+'" in signal "'+signalName+'" has an output value. '+"There should be these paths: "+JSON.stringify(Array.isArray(action.outputs)?action.outputs:Object.keys(action.outputs))].join(""))}else if(Array.isArray(action.outputs)){var nextPaths=actions[index+1];action.outputs.forEach(function(output){if(!Array.isArray(nextPaths[output])){throw new Error(['Cerebral: The action "'+utils.getFunctionName(action)+'" in signal "'+signalName+'" can not find path to its "'+output+'" output'].join(""))}})}else if(action.outputs){Object.keys(action.outputs).forEach(function(output){if(!Array.isArray(nextPaths[output])){throw new Error(['Cerebral: The action "'+utils.getFunctionName(action)+'" in signal "'+signalName+'" can not find path to its "'+output+'" output'].join(""))}})}else if(!Array.isArray(action)&&typeof action==="object"&&typeof action!==null){var prevAction=actions[index-1];Object.keys(action).forEach(function(key){if(!Array.isArray(action[key])){throw new Error(['Cerebral: The paths for action "'+utils.getFunctionName(prevAction)+'" in signal "'+signalName+'" are not valid. They have to be an array"'].join(""))}})}}})};traverse(actions)}},{"./utils.js":13}],8:[function(require,module,exports){var utils=require("./utils.js");var createStateArg=function(action,model,isAsync,compute){var state=Object.keys(model.accessors||{}).reduce(function(state,accessor){state[accessor]=function(){var args=[].slice.call(arguments);var path=[];if(args[0]&&Array.isArray(args[0])){path=args.shift()}else if(args[0]&&typeof args[0]==="string"){path=args.shift().split(".")}if(accessor==="get"&&typeof arguments[0]==="function"){return compute.getComputedValue(arguments[0])}return model.accessors[accessor].apply(null,[path].concat(args))};return state},{});Object.keys(model.mutators||{}).reduce(function(state,mutator){state[mutator]=function(){if(isAsync){throw new Error("Cerebral: You can not mutate state in async actions. Output values and set them with a sync action")}var path=[];var args=[].slice.call(arguments);if(Array.isArray(args[0])){path=args.shift()}else if(typeof args[0]==="string"){path=[args.shift()]}action.mutations.push({name:mutator,path:path.slice(),args:args});return model.mutators[mutator].apply(null,[path.slice()].concat(args))};return state},state);return state};module.exports={sync:function(action,signalArgs,model,compute){return[signalArgs,createStateArg(action,model,false,compute)]},async:function(action,signalArgs,model,compute){return[signalArgs,createStateArg(action,model,true,compute)]}}},{"./utils.js":13}],9:[function(require,module,exports){var utils=require("./utils.js");module.exports=function(modules,state,services){var modulesArg={};Object.keys(modules).forEach(function(key){var path=modules[key].path;var module={};module.state=Object.keys(state).reduce(function(module,key){module[key]=function(){var args=[].slice.call(arguments);var statePath=path;if(args[0]&&Array.isArray(args[0])){statePath=statePath.concat(args.shift())}else if(args[0]&&typeof args[0]==="string"){statePath=statePath.concat(args.shift().split("."))}return state[key].apply(null,[statePath].concat(args))};return module},{});module.services=path.reduce(function(services,key){return services?services[key]:null},services);utils.setDeep(modulesArg,key,module)});return modulesArg}},{"./utils.js":13}],10:[function(require,module,exports){var utils=require("./utils.js");var types=require("./types.js");var validateOutput=function(action,path,arg,signalName){if(!action.output&&!action.outputs||Array.isArray(action.outputs)){return}var checkers=action.output||action.outputs[path||action.defaultOutput];if(checkers===undefined&&arg===undefined){return}Object.keys(checkers).forEach(function(key){if(!types(checkers[key],arg[key])){throw new Error(['Cerebral: There is a wrong output of action "'+utils.getFunctionName(action)+'" '+'in signal "'+signalName+'". Check the following prop: "'+key+'"'].join(""))}})};var createNextFunction=function(action,signalName,resolver){var next=function(){if(next.hasRun){throw new Error("Cerebral - You are running an async output on a synchronous action in "+signalName+". The action is "+action.name+". Either put it in an array or make sure the output is synchronous")}var path=typeof arguments[0]==="string"?arguments[0]:null;var arg=path?arguments[1]:arguments[0];if(utils.isDeveloping()){try{JSON.stringify(arg)}catch(e){console.log("Not serializable",arg);throw new Error("Cerebral - Could not serialize output. Please check signal "+signalName+" and action "+action.name)}}if(!path&&!action.defaultOutput&&action.outputs){throw new Error(['Cerebral: There is a wrong output of action "'+utils.getFunctionName(action)+'" '+'in signal "'+signalName+'". Set defaultOutput or use one of outputs '+JSON.stringify(Object.keys(action.output||action.outputs))].join(""))}if(utils.isDeveloping()){validateOutput(action,path,arg,signalName)}var result={path:path?path:action.defaultOutput,arg:arg};if(resolver){resolver(result)}else{next._result=result}};return next};var addOutputs=function(action,next){if(!action.outputs){next.success=next.bind(null,"success");next.error=next.bind(null,"error")}else if(Array.isArray(action.outputs)){action.outputs.forEach(function(key){next[key]=next.bind(null,key)})}else{Object.keys(action.outputs).forEach(function(key){next[key]=next.bind(null,key)})}};module.exports={sync:function(action,signalName){var next=createNextFunction(action,signalName);addOutputs(action,next);if(utils.isDeveloping()){setTimeout(function(){next.hasRun=true},0)}return next},async:function(action,signalName){var resolver=null;var promise=new Promise(function(resolve){resolver=resolve});var next=createNextFunction(action,signalName,resolver);addOutputs(action,next);return{fn:next,promise:promise}}}},{"./types.js":12,"./utils.js":13}],11:[function(require,module,exports){var utils=require("./utils.js");var traverse=function(item,parentItem,path,actions,isSync){if(Array.isArray(item)){item=item.slice();isSync=!isSync;return item.map(function(subItem,index){path.push(index);var result=traverse(subItem,item,path,actions,isSync);path.pop();return result}).filter(function(action){return!!action})}else if(typeof item==="function"){var action={name:item.displayName||utils.getFunctionName(item),input:{},output:null,duration:0,mutations:[],isAsync:!isSync,outputPath:null,isExecuting:false,hasExecuted:false,path:path.slice(),outputs:null,actionIndex:actions.indexOf(item)===-1?actions.push(item)-1:actions.indexOf(item)};var nextItem=parentItem[parentItem.indexOf(item)+1];if(!Array.isArray(nextItem)&&typeof nextItem==="object"){parentItem.splice(parentItem.indexOf(nextItem),1);action.outputs=Object.keys(nextItem).reduce(function(paths,key){path=path.concat("outputs",key);paths[key]=traverse(nextItem[key],parentItem,path,actions,false);path.pop();path.pop();return paths},{})}return action}};module.exports=function(signals){var actions=[];var branches=traverse(signals,[],[],actions,false);return{branches:branches,actions:actions}}},{"./utils.js":13}],12:[function(require,module,exports){module.exports=function(type,value){var types=[String,Number,Array,Object,Boolean];if(type===null&&value!==null){return false}if(type===undefined&&value!==undefined){return false}if(type===String&&typeof value!=="string"){return false}if(type===Number&&typeof value!=="number"){return false}if(type===Array&&!Array.isArray(value)){return false}if(type===Object&&!(typeof value==="object"&&!Array.isArray(value)&&value!==null)){return false}if(type===Boolean&&typeof value!=="boolean"){return false}if(types.indexOf(type)===-1&&typeof type==="function"){return type(value)}return true}},{}],13:[function(require,module,exports){(function(process,global){var types=require("./types.js");module.exports={getFunctionName:function(fun){var ret=fun.toString();ret=ret.substr("function ".length);ret=ret.substr(0,ret.indexOf("("));return ret},merge:function(target,source){source=source||{};return Object.keys(source).reduce(function(target,key){target[key]=source[key];return target},target)},hasLocalStorage:function(){return typeof global.localStorage!=="undefined"},isPathObject:function(obj){return obj&&(obj.resolve||obj.reject)},debounce:function debounce(func,wait,immediate){var timeout;return function(){var context=this,args=arguments;var later=function(){timeout=null;if(!immediate)func.apply(context,args)};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow)func.apply(context,args)}},isAction:function(action){return typeof action==="function"},isDeveloping:function(){return typeof process==="undefined"||process.env.NODE_ENV!=="production"},verifyInput:function(actionName,signalName,input,signalArgs){Object.keys(input).forEach(function(key){if(typeof signalArgs[key]==="undefined"||!types(input[key],signalArgs[key])){throw new Error(['Cerebral: You are giving the wrong input to the action "'+actionName+'" '+'in signal "'+signalName+'". Check the following prop: "'+key+'"'].join(""))}})},extractMatchingPathFunctions:function(source,target){var incompatible=false;var traverse=function(obj,currentTarget,path,results){if(incompatible){return incompatible}if(typeof obj==="function"){results[path.join(".")]=obj}else if(typeof obj==="object"&&!Array.isArray(obj)&&obj!==null){for(var key in obj){if(!(key in currentTarget)){return incompatible=path.slice().concat(key)}else{path.push(key);traverse(obj[key],currentTarget[key],path,results);path.pop(key)}}}return incompatible||results};return traverse(source,target,[],{})},setDeep:function(object,stringPath,value){var path=stringPath.split(".");var setKey=path.pop();while(path.length){var key=path.shift();object=object[key]=object[key]||{}}object[setKey]=object[setKey]?Object.keys(object[setKey]).reduce(function(value,key){value[key]=object[setKey][key];return value},value):value;return value}}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./types.js":12,_process:15}],14:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{throw TypeError('Uncaught, unspecified "error" event.')}return false}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],15:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],cerebral:[function(require,module,exports){var CreateSignalFactory=require("./CreateSignalFactory.js");var CreateSignalStore=require("./CreateSignalStore.js");var CreateRecorder=require("./CreateRecorder.js");var CreateRegisterModules=require("./CreateRegisterModules.js");var Devtools=require("./Devtools.js");var Compute=require("./Compute.js");var EventEmitter=require("events").EventEmitter;var Controller=function(Model,services){if(services){console.warn("Passing services to controller is DEPRECATED. Please add them to controller with controller.services({})")}var controller=new EventEmitter;var model=Model(controller);var compute=Compute(model);var signals={};var devtools=null;var signalStore=CreateSignalStore(signals,controller);var modules={};services=services||{};if(typeof window!=="undefined"&&typeof window.addEventListener!=="undefined"){devtools=Devtools(signalStore,controller)}var recorder=CreateRecorder(signalStore,signals,controller,model);var signalFactory=CreateSignalFactory(signalStore,recorder,devtools,controller,model,services,compute,modules);var signal=function(){var signalNamePath=arguments[0].split(".");var signalName=signalNamePath.pop();var signalMethodPath=signals;while(signalNamePath.length){var pathName=signalNamePath.shift();signalMethodPath=signalMethodPath[pathName]=signalMethodPath[pathName]||{}}return signalMethodPath[signalName]=signalFactory.apply(null,arguments)};var service=function(name,service){var serviceNamePath=name.split(".");var serviceName=serviceNamePath.pop();var serviceMethodPath=services;while(serviceNamePath.length){var pathName=serviceNamePath.shift();serviceMethodPath=serviceMethodPath[pathName]=serviceMethodPath[pathName]||{}}return serviceMethodPath[serviceName]=service};controller.signal=function(){console.warn("This method is deprecated, use controller.signals() instead");signal.apply(null,arguments)};controller.signalSync=function(){console.warn("This method is deprecated, use controller.signals() instead");var defaultOptions=arguments[2]||{};defaultOptions.isSync=true;return signal.apply(null,[arguments[0],arguments[1],defaultOptions])};controller.getSignals=function(){return signals};controller.getServices=function(){return services};controller.getStore=function(){return signalStore};controller.getRecorder=function(){return recorder};controller.get=function(){if(typeof arguments[0]==="function"){return compute.has(arguments[0])?compute.getComputedValue(arguments[0]):compute.register(arguments[0])}var path=!arguments.length?[]:typeof arguments[0]==="string"?[].slice.call(arguments):arguments[0];return model.accessors.get(path)};controller.getDevtools=function(){return devtools};controller.logModel=function(){return model.logModel()};controller.getModules=function(){return modules};controller.modules=CreateRegisterModules(controller,model,modules);controller.signals=function(signals,options){Object.keys(signals).forEach(function(key){signal(key,signals[key],options)})};controller.signalsSync=function(signals,options){Object.keys(signals).forEach(function(key){options=options||{};options.isSync=true;signal.call(null,key,signals[key],options)})};controller.services=function(newServices){Object.keys(newServices).forEach(function(key){service(key,newServices[key])});return controller.getServices()};return controller};Controller.ServerController=function(state){var model={accessors:{get:function(path){path=path.slice();var key=path.pop();var grabbedState=state;while(path.length){grabbedState=grabbedState[path.shift()]}return grabbedState[key]}}};var compute=Compute(model);return{isServer:true,get:function(path){if(typeof arguments[0]==="function"){return compute.has(arguments[0])?compute.getComputedValue(arguments[0]):compute.register(arguments[0])}var path=!arguments.length?[]:typeof arguments[0]==="string"?[].slice.call(arguments):arguments[0];return model.accessors.get(path)}}};module.exports=Controller},{"./Compute.js":1,"./CreateRecorder.js":2,"./CreateRegisterModules.js":3,"./CreateSignalFactory.js":4,"./CreateSignalStore.js":5,"./Devtools.js":6,events:14}]},{},[]);Controller=require("cerebral");Model=require("cerebral-model-baobab");controller=Controller(Model({}));controller.modules({a:function(){return{metsgg:4}},b:function(m,c){res=c.getModules()}});document.write(JSON.stringify(res));
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"cerebral-model-baobab": "0.4.5",
"cerebral": "0.30.0"
}
}
<!-- contents of this file will be placed inside the <body> -->
<!-- contents of this file will be placed inside the <head> -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment