UNPKG

shared-updated

Version:

Modern fork of shared (Kevin Jones), updated for latest Node.js and MongoDB

102 lines (101 loc) 48 kB
var shared; (function(c){var f=c.utils||(c.utils={}),j=require("bintrees").RBTree,h=function(c){f.dassert(f.isValue(c));this._size=0;this._hashfn=c;this._tree=new j(function(b,e){return b.hash-e.hash})};h.prototype.size=function(){return this._size};h.prototype.find=function(c){f.dassert(f.isValue(c));var b=this._hashfn(c),b=this._tree.find({hash:b});if(null!==b)for(var e=0;e<b.values.length;e++)if(f.isEqual(c,b.values[e].key))return b.values[e].value;return null};h.prototype.insert=function(c,b){f.dassert(f.isValue(c));f.dassert(f.isValue(b)); var e=this._hashfn(c),a=this._tree.find({hash:e});if(null!==a){for(var e=null,d=0;d<a.values.length;d++)if(null===a.values[d].key)null===e&&(e=d);else if(f.isEqual(c,a.values[d].key))return!1;null!==e?a.values[e]={key:c,value:b}:a.values.push({key:c,value:b})}else this._tree.insert({hash:e,values:[{key:c,value:b}]});this._size++;return!0};h.prototype.findOrInsert=function(c,b){"undefined"===typeof b&&(b={});var e=this.find(c);if(null!==e)return e;this.insert(c,b);return b};h.prototype.remove=function(c){f.dassert(f.isValue(c)); var b=this._hashfn(c),b=this._tree.find({hash:b});if(null!==b)for(var e=0;e<b.values.length;e++)if(f.isEqual(c,b.values[e].key))return b.values[e].key=null,b.values[e].value=null,this._size--,!0;return!1};h.prototype.apply=function(c){for(var b=this._tree.iterator();b.next();)for(var e=b.data(),a=0;a<e.values.length;a++)if(null!==e.values[a].key&&!1===c(e.values[a].key,e.values[a].value))return!1;return!0};h.prototype.removeAll=function(){this._tree.clear();this._size=0};f.Map=h;c=function(c){"undefined"=== typeof c&&(c=[]);this._map=new h(function(b){return f.hash(b.toString())});for(var b=this._id=0;b<c.length;b++)this.put(c[b])};c.prototype.put=function(c){(c=this._map.insert(c,this._id))&&this._id++;return c};c.prototype.has=function(c){return null!==this._map.find(c)};c.prototype.id=function(c){return this._map.find(c)};c.prototype.remove=function(c){return this._map.remove(c)};c.prototype.size=function(){return this._map.size()};c.prototype.removeAll=function(){return this._map.removeAll()};c.prototype.apply= function(c){return this._map.apply(function(b){return c(b)})};f.StringSet=c;var g=function(){this._elems=[]};g.prototype.size=function(){return this._elems.length};g.prototype.empty=function(){return 0===this.size()};g.prototype.front=function(){return this.at(0)};g.prototype.back=function(){return this.at(this.size()-1)};g.prototype.at=function(c){f.dassert(0<=c&&c<this.size());return this._elems[c]};g.prototype.setAt=function(c,b){f.dassert(0<=c&&c<this.size());this._elems[c]=b};g.prototype.push= function(c){this._elems.push(c)};g.prototype.pop=function(){f.dassert(!this.empty());return this._elems.pop()};g.prototype.unshift=function(c){this._elems.unshift(c)};g.prototype.shift=function(){f.dassert(!this.empty());return this._elems.shift()};g.prototype.array=function(){return this._elems};g.prototype.first=function(c){for(var b=0;b<this._elems.length;b++)if(c(this._elems[b]))return this._elems[b];return null};g.prototype.filter=function(c){for(var b=new g,e=0;e<this._elems.length;e++)c(this._elems[e])&& b.push(this._elems[e]);return b};g.prototype.apply=function(c){for(var b=0;b<this._elems.length;b++)c(this._elems[b])};f.Queue=g})(shared||(shared={}));var __extends=this.__extends||function(c,f){function j(){this.constructor=c}j.prototype=f.prototype;c.prototype=new j}; (function(c){var f=c.utils||(c.utils={}),j=function(k){d&&g.ok(k)},h=require("fs"),g=require("assert");require("util");var l=require("cluster");f.LogLevel={INFO:1,WARN:2,FATAL:3,NONE:4};var b=function(k){this._fd=k};b.prototype.write=function(k){k=new Buffer(k);h.writeSync(this._fd,k,0,k.length,null)};f.WriteableFD=b;var e=function(k,d,a,b,c){this._to=k;this._prefix=d;this._level=a;this._debug=new f.StringSet(b);this._next=c};e.prototype.logLevel=function(){return this._level};e.prototype.isDebugLogging= function(k){return this._debug.has(k)};e.prototype.enableDebugLogging=function(k,d){f.isValue(d)&&!d?this._debug.remove(k):this._debug.put(k)};e.prototype.disableDebugLogging=function(){this._debug.removeAll()};e.prototype.debug=function(k,d){for(var a=[],b=0;b<arguments.length-2;b++)a[b]=arguments[b+2];this.isDebugLogging(k)&&(b=k+": "+d,this.log(f.LogLevel.INFO,b,a),this._next&&this._next.log(f.LogLevel.INFO,b,a))};e.prototype.info=function(k){for(var d=[],a=0;a<arguments.length-1;a++)d[a]=arguments[a+ 1];this.log(f.LogLevel.INFO,k,d);this._next&&this._next.log(f.LogLevel.INFO,k,d)};e.prototype.warn=function(k){for(var d=[],a=0;a<arguments.length-1;a++)d[a]=arguments[a+1];this.log(f.LogLevel.WARN,k,d);this._next&&this._next.log(f.LogLevel.INFO,k,d)};e.prototype.fatal=function(k){for(var d=[],a=0;a<arguments.length-1;a++)d[a]=arguments[a+1];this.log(f.LogLevel.FATAL,k,d);this._next&&this._next.log(f.LogLevel.FATAL,k,d)};e.prototype.write=function(k){this._to.write(k);this._next&&this._next.write(k)}; e.prototype.trace=function(k){for(var d=[],a=0;a<arguments.length-1;a++)d[a]=arguments[a+1];a=Error();a.name="Trace";a.message=f.dateFormat(this._prefix,k,d);Error.captureStackTrace(a,arguments.callee);this.write(a.stack+"\n")};e.prototype.log=function(d,a,b){switch(d){case f.LogLevel.INFO:this.logLevel()<=f.LogLevel.INFO&&this._to.write(f.dateFormat(this._prefix+" INFO",a,b));break;case f.LogLevel.WARN:this.logLevel()<=f.LogLevel.WARN&&this._to.write(f.dateFormat(this._prefix+" WARNING",a,b));break; case f.LogLevel.FATAL:if(this.logLevel()<=f.LogLevel.FATAL&&(d=f.dateFormat(this._prefix+" FATAL",a,b),this._to.write(d),!f.isValue(this._next)))throw Error("Fatal error: "+d);break;case f.LogLevel.NONE:break;default:j(!1)}this._next&&this._next.log(f.LogLevel.INFO,a,b)};f.Logger=e;c=function(d,a,b,c,g){d=this.openLog(d);e.call(this,d,a,b,c,g)};__extends(c,e);c.prototype.openLog=function(d){for(var a=0;;){var c=d+"-"+process.pid+"-"+a;try{var e=h.openSync(c,"ax","0666");return new b(e)}catch(g){if(a++, 10===a)throw g;}}};f.FileLogger=c;var a=null;f.setdefaultLogger=function(d){j(f.isValue(d));a=d};f.defaultLogger=function(){if(!a){var d="master";l.worker&&(d="work "+l.worker.id);a=new e(process.stdout,d,f.LogLevel.INFO,[])}return a};var d=!0;f.enableAsserts=function(a){d=a};f.assertsEnabled=function(){return d};f.dassert=j})(shared||(shared={})); (function(c){var f=c.utils||(c.utils={}),j=function(d){return void 0!==d&&null!==d},h=function(d){return d&&"object"===typeof d&&!(d instanceof Array)},g=function(d){return d&&"object"===typeof d&&d instanceof Array},l=function(d){f.dassert(g(d));return d.slice(0)},b=function(d){f.dassert(h(d));var a={},k;for(k in d)a[k]=d[k];return a},e=function(d,a,k){var b="";null!==d&&0<d.length&&(b+=d+" ");var c=0,e=k.length;d=b+String(a).replace(/%[sdj%]/g,function(d){if("%%"===d)return"%";if(c>=e)return d; switch(d){case "%s":return String(k[c++]);case "%d":return Number(k[c++]).toString();case "%j":return JSON.stringify(k[c++]);default:return d}});d+="\n";for(a=k[c];c<e;a=k[++c])d=null===a||"object"!==typeof a?d+(a+"\n"):d+(JSON.stringify(a,null," ")+"\n");return d},a=require("underscore"),d=require("os");f.hash=function(d,a){f.dassert(j(d));var k=5381;j(a)&&(k=a);for(var b=d.length,c=0;c<b;c++)k=(k<<5)-k+d.charCodeAt(c),k&=k;return k};f.isEqual=function(d,k){return a.isEqual(d,k)};f.isValue=j;f.isObject= h;f.isArray=g;f.isObjectOrArray=function(d){return d&&"object"===typeof d};f.typeOf=function(d){var a=typeof d;"object"===a&&(d?d instanceof Array&&(a="array"):a="null");return a};f.treatAs=function(d){var a=typeof d;if("object"===a){if(d)return Object.prototype.toString.call(d).match(/^\[object\s(.*)\]$/)[1];a="null"}return a};f.cloneArray=l;f.cloneObject=b;f.clone=function(d){return h(d)?b(d):l(d)};f.toInteger=function(d){d=+d;return isNaN(d)?0:0===d||Infinity===d||-Infinity==d?d:0>d?-1*Math.floor(-d): Math.floor(d)};f.dateFormat=function(d,a,k){return(new Date).toISOString()+" "+e(d,a,k)};f.format=e;var k=null;f.hostInfo=function(){if(null===k){k=d.hostname();var a=d.networkInterfaces(),b;for(b in a){var c=0;a[b].forEach(function(d){"IPv4"===d.family&&"127.0.0.1"!==d.address&&(k+=" ["+d.address+"]",++c)})}}return k};f.exceptionInfo=function(d){return d instanceof Error?d.stack:JSON.stringify(d)}})(shared||(shared={})); (function(c){var f=c.utils||(c.utils={}),j=function(){return new l},h=function(b){return b instanceof l},g=function(b){var a=new l(b);f.dassert(h(a)&&a.toString()==b.toLowerCase());return a},l=require("mongodb").ObjectID;f.uidStringLength=24;f.UID=j;f.isUID=h;f.makeUID=g;f.toObjectID=function(b){return b};var b=function(){this._id=null};b.prototype.id=function(){null===this._id&&(this._id=j());return this._id};f.UniqueObject=b;b=function(){this._map=new c.utils.Map(c.utils.hash)};b.prototype.size= function(){return this._map.size()};b.prototype.find=function(b){return this._map.find(b.toString())};b.prototype.insert=function(b,a){return this._map.insert(b.toString(),a)};b.prototype.findOrInsert=function(b,a){"undefined"===typeof a&&(a={});return this._map.findOrInsert(b.toString(),a)};b.prototype.remove=function(b){return this._map.remove(b.toString())};b.prototype.apply=function(b){return this._map.apply(function(a,d){return b(g(a),d)})};b.prototype.removeAll=function(){this._map.removeAll()}; f.IdMap=b})(shared||(shared={})); (function(c){var f=c.types||(c.types={}),j=c.utils.UniqueObject,h=function(c,b){j.call(this);this._isobj=c;this._props=b};__extends(h,j);h.prototype.isobj=function(){return this._isobj};h.prototype.isarray=function(){return!this._isobj};h.prototype.props=function(){return this._props};h.prototype.typeDesc=function(){var c="o#";this.isarray()&&(c="a#");for(var b=0;b<this._props.length;b++)c+=this._props[b],c+="#";return c};f.TypeDesc=h;var g=function(){c.utils.dassert(null==g._instance);this._tree= new c.utils.Map(c.utils.hash)};g.instance=function(){g._instance||(g._instance=new g);return g._instance};g.prototype.type=function(f){c.utils.dassert(c.utils.isObjectOrArray(f));var b=g.props(f),e=this._tree.find(b);null===e&&(e=b.split("#"),e.shift(),e.pop(),e=new h(c.utils.isObject(f),e),this._tree.insert(b,e));return e};g.props=function(g){c.utils.dassert(c.utils.isObjectOrArray(g));var b="o#";g instanceof Array&&(b="a#");for(var e in g)g.hasOwnProperty(e)&&(b+=e,b+="#");return b};f.TypeStore= g})(shared||(shared={})); (function(c){var f=c.serial||(c.serial={}),j=function(b,e,a){"undefined"===typeof a&&(a="");c.utils.dassert(c.utils.isObject(b));var d=c.utils.treatAs(e);switch(d){case "null":a+="null";break;case "undefined":a+="undefined";break;case "number":case "Number":case "boolean":case "Boolean":a+=e.toString();break;case "string":case "String":a+=JSON.stringify(e);break;case "Date":a+=JSON.stringify(e.toString());break;case "Object":case "Array":a+="<"+b.valueId(e)+">";break;case "function":case "RegExp":case "Error":a+="null"; break;default:c.utils.defaultLogger().fatal("Unexpected type: %s",d)}return a},h=function(b){c.utils.dassert(c.utils.isUID(b));this._id=b};h.prototype.id=function(){return this._id};f.Reference=h;f.writeObject=function(b,e,a,d){"undefined"===typeof a&&(a="");"undefined"===typeof d&&(d=!1);c.utils.dassert(c.utils.isObjectOrArray(b));c.utils.dassert(c.utils.isObjectOrArray(e));a=e instanceof Array?a+"[":a+"{";d&&(a+=b.valueId(e)+" ",a+=b.valueRev(e)+" ");d=Object.keys(e);for(var k=0;k<d.length;k++)a= j(b,d[k],a),a+=":",a=j(b,e[d[k]],a),k<d.length-1&&(a+=",");return a=e instanceof Array?a+"]":a+"}"};f.writeValue=j;f.readObject=function(b,e){c.utils.dassert(1<b.length&&("["===b.charAt(0)||"{"===b.charAt(0))&&("]"===b.charAt(b.length-1)||"}"===b.charAt(b.length-1)));"{"===b.charAt(0)?c.utils.isValue(e)?c.utils.dassert(c.utils.isObject(e)):e={}:c.utils.isValue(e)?(c.utils.dassert(c.utils.isArray(e)),e.length=0):e=[];for(var a=new g(b.substr(1,b.length-2)),d=Object.keys(e),k=0;;){a.skipWS();if(a.eof())break; var m=a.readNextValue();c.utils.dassert("string"===typeof m);if(-1!==k&&m!=d[k]){for(;k<d.length;k++)delete e[d[k]];k=-1}a.skipWS();c.utils.dassert(!a.eof());c.utils.dassert(":"===a.peek());a.skip();a.skipWS();var f=a.readNextValue();e[m]=f;a.skipWS();if(a.eof())break;else c.utils.dassert(","===a.peek()),a.skip(),a.skipWS()}return e};f.readValue=function(b){c.utils.dassert(c.utils.isValue(b));return(new g(b)).readNextValue()};var g,l=function(b){c.utils.dassert(c.utils.isValue(b));this._from=b;this._at= 0};l._numberPat=/^-?(0|([1-9][0-9]*))(\.[0-9]+)?([eE][-+][0-9]+)?/;l.prototype.eof=function(){return this._at>=this._from.length};l.prototype.skip=function(b){"undefined"===typeof b&&(b=1);this._at+=b};l.prototype.skipWS=function(){for(;this._at<this._from.length&&(" "===this._from[this._at]||"\t"===this._from[this._at]);)this._at++};l.prototype.peek=function(b){"undefined"===typeof b&&(b=0);c.utils.dassert(this._at+b<this._from.length);return this._from[this._at+b]};l.prototype.readNextValue=function(){if("null"=== this._from.substr(this._at,4))return this._at+=4,null;if("undefined"===this._from.substr(this._at,9))this._at+=9;else{if("true"===this._from.substr(this._at,4))return this._at+=4,!0;if("false"===this._from.substr(this._at,5))return this._at+=5,!1;if("NaN"===this._from.substr(this._at,3))return this._at+=3,NaN;if("Infinity"===this._from.substr(this._at,8))return this._at+=8,Infinity;if("-Infinity"===this._from.substr(this._at,9))return this._at+=9,-Infinity;if('"'===this._from.charAt(this._at)){for(var b= this._at+1;b<this._from.length;){if("\\"===this._from.charAt(b))b+=1;else if('"'===this._from.charAt(b))break;b+=1}if(b<this._from.length){var e=this._from.substr(this._at,b-this._at+1);this._at=b+1;return JSON.parse(e)}}if("<"===this._from.charAt(this._at)&&">"===this._from.charAt(this._at+1+c.utils.uidStringLength))return b=this._from.substr(this._at+1,c.utils.uidStringLength),this._at+=2+c.utils.uidStringLength,new h(c.utils.makeUID(b));if(b=this.numberLength())return e=parseFloat(this._from.substr(this._at)), c.utils.dassert(!isNaN(e)),this._at+=b,e;c.utils.defaultLogger().fatal("Unexpected value encoding: %s",this._from.substr(this._at))}};l.prototype.numberLength=function(){var b=l._numberPat.exec(this._from.substr(this._at));return b?b[0].length:0};g=l})(shared||(shared={})); (function(c){var f=c.tracker||(c.tracker={}),j=function(d){return void 0===d._tracker?null:d._tracker},h=function(d){c.utils.dassert(c.utils.isObject(d._tracker));return d._tracker},g=function(d,a){var b=d.toString(),c=a.toString();return b<c?-1:b>c?1:0},l=function(d,a){var b=Object.getOwnPropertyDescriptor(d,a);return void 0!=b.get&&void 0!=b.set},b=function(d,a){var b=Object.getOwnPropertyDescriptor(d,a);void 0!=b.get&&void 0!=b.set&&Object.defineProperty(d,a,{value:d[a]})};require("buffer");var e= function(d,a,b){this._id=d;this._prop=a;this._missing=b};e.prototype.id=function(){return this._id};e.prototype.prop=function(){return this._prop};e.prototype.missing=function(){return this._missing};f.UnknownReference=e;f.getTrackerUnsafe=j;f.getTracker=h;f.isTracked=function(d){return c.utils.isObject(d._tracker)};var a=function(d,a,e,f){"undefined"===typeof e&&(e=c.utils.UID());c.utils.dassert(c.utils.isObject(d));c.utils.dassert(c.utils.isUID(e));(null===a||"object"!==typeof a)&&c.utils.defaultLogger().fatal("Trying to track non-object/array type"); a.hasOwnProperty("_tracker")&&c.utils.defaultLogger().fatal("Trying to track already tracked object or array");this._tc=d;this._rev=f||0;this._id=e;this._lastTx=-1;this._id=e;this._type=c.types.TypeStore.instance().type(a);this._userdata=null;this._ref=0;Object.defineProperty(a,"_tracker",{value:this});a instanceof Array&&(Object.defineProperty(a,"shift",{enumerable:!1,configurable:!1,value:function(){var d=h(a);if(0===d.tc().disable){d.tc().disable++;var b=Object.keys(a),c=[];b.forEach(function(d, b,e){c.push(l(a,e[b]))});0<a.length&&d.addShift(a,0,1);for(var e=Array.prototype.shift.apply(a,arguments),b=Object.keys(a),g=0;g<a.length;g++){var m=b[g];c[g+1]&&!l(a,m)&&d.track(a,m)}d.tc().disable--;return e}return Array.prototype.shift.apply(a,arguments)}}),Object.defineProperty(a,"unshift",{enumerable:!1,configurable:!1,value:function(){var d=h(a);if(0===d.tc().disable){d.tc().disable++;var b=Object.keys(a),c=[];b.forEach(function(d,b,e){c.push(l(a,e[b]))});0<arguments.length&&d.addUnshift(a, 0,arguments.length);for(var e=Array.prototype.unshift.apply(a,arguments),g=0;g<arguments.length;g++)d.track(a,g+""),d.addNew(a,g+"",a[g]);for(b=Object.keys(a);g<a.length;g++){var m=b[g];c[g-arguments.length]&&!l(a,m)&&d.track(a,m)}d.tc().disable--;return e}return Array.prototype.unshift.apply(a,arguments)}}),Object.defineProperty(a,"reverse",{enumerable:!1,configurable:!1,value:function(){var d=h(a);if(0===d.tc().disable){d.tc().disable++;var c=Object.keys(a),e=[];c.forEach(function(d,b,c){e.push(l(a, c[b]))});e.reverse();d.addReverse(a);for(var g=Array.prototype.reverse.apply(a,arguments),c=Object.keys(g),m=0;m<c.length;m++){var f=c[m],n=l(a,f);e[m]&&!n?d.track(a,f):!e[m]&&n&&b(a,f)}d.tc().disable--;return g}return Array.prototype.reverse.apply(a,arguments)}}),Object.defineProperty(a,"sort",{enumerable:!1,configurable:!1,value:function(d){var c=h(a);if(0===c.tc().disable){c.tc().disable++;var e=Object.keys(a),m=[];e.forEach(function(d,b,c){m.push({elem:a[c[b]],track:l(a,c[b])})});var f=d;void 0=== f&&(f=g);var n=function(d,a){return f(d.elem,a.elem)};Array.prototype.sort.apply(m,[n]);for(d=0;d<m.length;d++){n=e[d];a[n]=m[d].elem;var j=l(a,n);m[d].track&&!j?c.track(a,n):!m[d].track&&j&&b(a,n)}c.addSort(a);c.tc().disable--;return a}Array.prototype.sort.apply(m,[n])}}),Object.defineProperty(a,"splice",{enumerable:!1,configurable:!1,value:function(){var d=h(a);if(0===d.tc().disable){d.tc().disable++;var e=a.length,g=c.utils.toInteger(arguments[0]),g=0>g?Math.max(e+g,0):Math.min(g,e),m=e-g;void 0!== arguments[1]&&(m=Math.min(Math.max(c.utils.toInteger(arguments[1]),0),e-g));var e=Math.max(arguments.length-2,0),f=Object.keys(a),n=[];f.forEach(function(d,b,c){n.push(l(a,c[b]))});for(var j=Array.prototype.splice.apply(a,arguments),r=0;r<f.length;r++){var s=+f[r];if(s<g||s>=g+m){s>=g&&(s+=e-m);var s=s+"",x=l(a,s);n[r]&&!x?d.track(a,s):!n[r]&&x&&b(a,s)}}for(r=g;r<g+e;r++)void 0!==a[r]&&b(a,r+"");0<m&&d.addShift(a,g,m);0<e&&d.addUnshift(a,g,e);d.tc().disable--;return j}return Array.prototype.splice.apply(a, arguments)}}));for(var j in a)this.track(a,j)};a.prototype.kill=function(){this._tc=null};a.prototype.isDead=function(){return null===this._tc};a.prototype.tc=function(){return this._tc};a.prototype.id=function(){return this._id};a.prototype.type=function(){return this._type};a.prototype.rev=function(d){void 0!==d&&(this._rev+=d);return this._rev};a.prototype.setRev=function(d){d>=this._rev&&(this._rev=d);return this._rev};a.prototype.ref=function(d){void 0!==d&&(this._ref+=d);return this._ref};a.prototype.setRef= function(d){d>=this._ref&&(this._ref=d);return this._ref};a.prototype.setData=function(d){this._userdata=d};a.prototype.getData=function(){return this._userdata};a.prototype.hasChanges=function(){return-1!=this._lastTx};a.prototype.lastChange=function(){return this._lastTx};a.prototype.setLastChange=function(d){this._lastTx=d};a.prototype.addNew=function(d,a,b){c.utils.dassert(h(d)===this);this._lastTx=this.tc().addNew(d,a,b,this._lastTx)};a.prototype.addWrite=function(d,a,b,e){c.utils.dassert(h(d)=== this);this._lastTx=this.tc().addWrite(d,a,b,e,this._lastTx)};a.prototype.addDelete=function(d,a){c.utils.dassert(h(d)===this);this._lastTx=this.tc().addDelete(d,a,this._lastTx)};a.prototype.addReverse=function(d){c.utils.dassert(h(d)===this);this._lastTx=this.tc().addReverse(d,this._lastTx)};a.prototype.addSort=function(d){c.utils.dassert(h(d)===this);this._lastTx=this.tc().addSort(d,this._lastTx)};a.prototype.addShift=function(d,a,b){c.utils.dassert(h(d)===this);this._lastTx=this.tc().addShift(d, a,b,this._lastTx)};a.prototype.addUnshift=function(d,a,b){c.utils.dassert(h(d)===this);this._lastTx=this.tc().addUnshift(d,a,b,this._lastTx)};a.prototype.retrack=function(d){c.utils.dassert(h(d)===this);for(var a in d)l(d,a)||this.track(d,a);this._type=c.types.TypeStore.instance().type(d)};a.prototype.track=function(d,a){c.utils.dassert(h(d)===this);if(d.hasOwnProperty(a)){var b=d[a];if(delete d[a]){var g=b,f=h(d);Object.defineProperty(d,a,{enumerable:!0,configurable:!0,get:function(){if(0===f.tc().disable&& null!==g&&"object"===typeof g){if(g instanceof c.serial.Reference){var d=g;throw new e(f.id(),a,d.id());}d=j(g);if(null!==d){if(d.isDead())throw new e(f.id(),a,d.id());f.tc().markRead(g)}}return g},set:function(b){0===f.tc().disable&&(f.tc().disable++,f.addWrite(d,a,b,g),f.tc().disable--);g=b}})}else throw Error("Unwrappable property found: "+a);}};a.prototype.uprev=function(d){c.utils.dassert(h(d)===this);this._rev+=1;this._type=c.types.TypeStore.instance().type(d)};a.prototype.downrev=function(d){c.utils.dassert(h(d)=== this);-1!==this._lastTx&&(this._lastTx=-1,this._rev-=1,this._type=c.types.TypeStore.instance().type(d))};f.Tracker=a;f.isPropTracked=l})(shared||(shared={})); (function(c){var f=c.mtx||(c.mtx={}),j=function(){this._map=new c.utils.IdMap};j.prototype.size=function(){return this._map.size()};j.prototype.find=function(b){return this._map.find(b)};j.prototype.insert=function(b,c){return this._map.insert(b,c)};j.prototype.remove=function(b){return this._map.remove(b)};j.prototype.apply=function(b){return this._map.apply(function(c,a){return b(c,a)})};j.prototype.removeAll=function(){this._map.removeAll()};j.prototype.toString=function(){var b="";this._map.apply(function(c, a){b+=c;b+=" ";b+=a;b+="\n";return!0});return b};f.ReadMap=j;var h=function(b){"undefined"===typeof b&&(b=new c.utils.Queue);this._queue=b};h.prototype.size=function(){return this._queue.size()};h.prototype.empty=function(){return this._queue.empty()};h.prototype.front=function(){return this._queue.front()};h.prototype.back=function(){return this._queue.back()};h.prototype.at=function(b){return this._queue.at(b)};h.prototype.setAt=function(b,c){this._queue.setAt(b,c)};h.prototype.push=function(b){this._queue.push(b)}; h.prototype.pop=function(){return this._queue.pop()};h.prototype.unshift=function(b){this._queue.unshift(b)};h.prototype.shift=function(){return this._queue.shift()};h.prototype.array=function(){return this._queue.array()};h.prototype.first=function(b){return this._queue.first(function(c){return b(c)})};h.prototype.filter=function(b){var c=this._queue.filter(function(a){return b(a)});return new h(c)};h.prototype.apply=function(b){this._queue.apply(function(c){return b(c)})};h.prototype.toString=function(){var b= "";this._queue.apply(function(c){b+=c.id;b+=" ";b+=JSON.stringify(c.obj);b+="\n"});return b};f.NewQueue=h;var g=function(b){"undefined"===typeof b&&(b=new c.utils.Queue);this._queue=b};g.prototype.size=function(){return this._queue.size()};g.prototype.empty=function(){return this._queue.empty()};g.prototype.front=function(){return this._queue.front()};g.prototype.back=function(){return this._queue.back()};g.prototype.at=function(b){return this._queue.at(b)};g.prototype.setAt=function(b,c){this._queue.setAt(b, c)};g.prototype.push=function(b){this._queue.push(b)};g.prototype.pop=function(){return this._queue.pop()};g.prototype.unshift=function(b){this._queue.unshift(b)};g.prototype.shift=function(){return this._queue.shift()};g.prototype.array=function(){return this._queue.array()};g.prototype.first=function(b){return this._queue.first(function(c){return b(c)})};g.prototype.filter=function(b){var c=this._queue.filter(function(a){return b(a)});return new g(c)};g.prototype.apply=function(b){this._queue.apply(function(c){return b(c)})}; g.prototype.toString=function(){var b="";this._queue.apply(function(e){b+=c.tracker.getTracker(e.obj).id();b+=" ";void 0!==e.write?(b+="write "+e.write+" = "+JSON.stringify(e.value),void 0!==e.last&&(b+=" last "+JSON.stringify(e.last))):b=void 0!==e.del?b+("delete "+e.del):void 0!==e.reinit?b+("reinit "+e.reinit):void 0!==e.reverse?b+"reverse":void 0!==e.shift?b+("shift "+e.shift+" by "+e.size):void 0!==e.unshift?b+("unshift "+e.unshift+" by "+e.size):b+("**UNKNOWN** "+JSON.stringify(e));b+="\n"}); return b};f.ChangeQueue=g;var l=function(){this.reset()};l.prototype.reset=function(){this.rset=new j;this.nset=new h;this.cset=new g};l.prototype.toString=function(){var b;b="Read:\n"+this.rset.toString();b+="New:\n"+this.nset.toString();return b+="Changed:\n"+this.cset.toString()};f.MTX=l})(shared||(shared={})); (function(c){var f=c.mtx||(c.mtx={}),j=function(){this._cache=new c.utils.Map(c.utils.hash)};j.prototype.find=function(c){return this._cache.find(c.toString())};j.prototype.insert=function(c,f){return this._cache.insert(c.toString(),f)};j.prototype.remove=function(c){return this._cache.remove(c.toString())};f.ObjectCache=j;var h=c.utils.UniqueObject,j=function(){h.call(this);this.disable=0;this._mtx=new f.MTX;this._collected=!1};__extends(j,h);j.prototype.cset=function(){return this._mtx.cset.array()}; j.prototype.markRead=function(g){g=c.tracker.getTracker(g);c.utils.dassert(g.tc()===this);this._mtx.rset.insert(g.id(),g.rev())};j.prototype.readsetSize=function(){return this._mtx.rset.size()};j.prototype.readsetObject=function(c){return this._mtx.rset.find(c.toString())};j.prototype.newsetSize=function(){return this._mtx.nset.size()};j.prototype.newsetObject=function(c){var f=this._mtx.nset.first(function(b){return b.id.toString()===c.toString()});return f?f.obj:null};j.prototype.addNew=function(g, f,b,e){c.utils.isObjectOrArray(b)&&this.valueId(b);"function"===typeof b&&(b=null);this._mtx.cset.push({obj:g,write:f,value:b,lasttx:e});return this._mtx.cset.size()-1};j.prototype.addWrite=function(g,f,b,e,a){c.utils.isObjectOrArray(b)&&this.valueId(b);"function"===typeof b&&(b=null);this._mtx.cset.push({obj:g,write:f,value:b,last:e,lasttx:a});return this._mtx.cset.size()-1};j.prototype.addDelete=function(c,f,b){this._mtx.cset.push({obj:c,del:f,lasttx:b});return this._mtx.cset.size()-1};j.prototype.addReverse= function(c,f){this._mtx.cset.push({obj:c,reverse:!0,lasttx:f});return this._mtx.cset.size()-1};j.prototype.addSort=function(c,f){this._mtx.cset.push({obj:c,sort:!0,lasttx:f});return this._mtx.cset.size()-1};j.prototype.addShift=function(c,f,b,e){this._mtx.cset.push({obj:c,shift:f,size:b,lasttx:e});return this._mtx.cset.size()-1};j.prototype.addUnshift=function(c,f,b,e){this._mtx.cset.push({obj:c,unshift:f,size:b,lasttx:e});return this._mtx.cset.size()-1};j.prototype.replaceSort=function(g,f,b){c.utils.dassert(void 0!== this._mtx.cset.at(g).sort);g=c.tracker.getTracker(f);for(var e=g.lastChange();-1!==e;){var a=e,e=this._mtx.cset.at(e).lasttx;this._mtx.cset.setAt(a,null)}this._mtx.cset.push({obj:f,reinit:b,lasttx:-1});g.setLastChange(this._mtx.cset.size()-1)};j.prototype.mtx=function(g){c.utils.dassert(!1===this._collected);this._collected=!0;this.collect(g);return this._mtx};j.prototype.resetMtx=function(){this._mtx=new f.MTX;this._collected=!1};j.prototype.okMtx=function(){this._mtx.cset.apply(function(g){c.tracker.getTracker(g.obj).setLastChange(-1)}); this.resetMtx()};j.prototype.undoMtx=function(g){this.disable++;this._collected||this.collect(g);for(var f=this._mtx.cset.size()-1;0<=f;){var b=this._mtx.cset.at(f);if(null!==b){var e=c.tracker.getTracker(b.obj);e.isDead()||(void 0!==b.write?void 0!==b.last?b.obj[b.write]=b.last:c.utils.isArray(b.obj)?b.obj.splice(parseInt(b.write),1):delete b.obj[b.write]:(e.kill(),g.remove(e.id())))}f--}for(f=this._mtx.cset.size()-1;0<=f;)b=this._mtx.cset.at(f),null!==b&&(e=c.tracker.getTracker(b.obj),e.downrev(b.obj)), f--;this.resetMtx();this.disable--};j.prototype.valueId=function(f){c.utils.dassert(c.utils.isObjectOrArray(f));var j=c.tracker.getTrackerUnsafe(f);if(null===j){if(void 0===f._pid){for(var j=Object.keys(f),b=0;b<j.length;b++){var e=j[b];c.utils.isObjectOrArray(f[e])&&this.valueId(f[e])}Object.defineProperty(f,"_pid",{value:c.utils.UID()});this._mtx.nset.push({id:f._pid,obj:f})}return f._pid}j.tc()!==this&&c.utils.defaultLogger().fatal("Objects can not be used in multiple stores");return f._tracker.id()}; j.prototype.valueRev=function(c){return void 0===c._tracker?0:c._tracker.rev()};j.prototype.collect=function(f){var j=this;this._mtx.rset.apply(function(b){b=f.find(b);c.utils.dassert(null!=b);j.collectObject(b);return!0})};j.prototype.collectObject=function(f){c.utils.dassert(c.tracker.isTracked(f));f instanceof Array?this.arrayChanges(f):this.objectChanges(f)};j.prototype.objectChanges=function(f){var j=c.tracker.getTracker(f);j.tc().disable++;for(var b=c.utils.cloneArray(j.type().props()),e=Object.keys(f), a=0;a<b.length;a++)if(!f.hasOwnProperty(b[a])||!c.tracker.isPropTracked(f,b[a]))j.addDelete(f,b[a]);else{var d=e.indexOf(b[a]);e[d]=null}for(a=0;a<e.length;a++)null!==e[a]&&(j.addNew(f,e[a],f[e[a]]),j.track(f,e[a]));j.hasChanges()&&j.uprev(f);j.tc().disable--};j.prototype.arrayChanges=function(f){var j=c.tracker.getTracker(f);j.tc().disable++;for(var b=j.lastChange(),e=[];-1!==b;){if(void 0!==this._mtx.cset.at(b).sort){var a=c.serial.writeObject(j.tc(),f,"");this.replaceSort(b,f,a);j.uprev(f);j.tc().disable--; return}e.unshift(this._mtx.cset.at(b));b=this._mtx.cset.at(b).lasttx}for(var a=c.utils.cloneArray(j.type().props()),d=0;d<e.length;d++)if(void 0!=e[d].shift)for(var b=e[d].shift,k=e[d].size,m=0;m!==a.length;){var n=+a[m];n>=b&&n<b+k?a.splice(m,1):(n>=b+k&&(a[m]=n-k+""),m++)}else if(void 0!=e[d].unshift){for(var b=e[d].unshift,k=e[d].size,m=0,r=!1;m!==a.length;)if(n=+a[m],r)a[m]=n+k+"",m++;else if(n>=b){for(n=k-1;0<=n;n--)a.splice(m,0,b+n+"");r=!0;m+=k}else m++;if(!r)for(n=0;n<k;n++)a.push(b+n+"")}b= 0;for(d=a.length-1;0<=d;d--)if(+a[d]>=f.length)b++;else break;if(0<b)for(j.addShift(f,-1,+a[a.length-1]-f.length+1);0<b;)a.pop(),b--;for(d=0;d<a.length;d++)f.hasOwnProperty(a[d])?c.tracker.isPropTracked(f,a[d])||(j.addNew(f,a[d],f[a[d]]),j.track(f,a[d])):j.addDelete(f,a[d]);b=Object.keys(f);for(d=0;d<b.length;d++)n=a.indexOf(b[d]),-1===n&&(j.addNew(f,b[d],f[b[d]]),j.track(f,b[d]));j.hasChanges()&&j.uprev(f);j.tc().disable--};f.mtxFactory=j})(shared||(shared={})); (function(c){var f=c.store||(c.store={});f.rootUID=c.utils.makeUID("000000000000000000000001");f.createStore=function(c){return new f.MongoStore(c)}})(shared||(shared={})); (function(c){var f=c.store||(c.store={});require("util");var j=require("rsvp"),h=require("mongodb"),g=require("bson"),l=c.utils.makeUID("000000000000000000000000"),b=c.mtx.mtxFactory,e=function(a){"undefined"===typeof a&&(a={});b.call(this);this._logger=c.utils.defaultLogger();this._collection=null;this._pending=[];this._root=null;this._cache=new c.mtx.ObjectCache;this._host=a.host||"localhost";this._port=a.port||27017;this._dbName=a.db||"shared";this._collectionName=a.collection||"shared";this._safe= a.safe||"false";this._logger.debug("STORE","%s: Store created",this.id())};__extends(e,b);e.prototype.close=function(){this._pending.push({close:!0});this.processPending()};e.prototype.apply=function(a,d){"undefined"===typeof d&&(d=function(){});this._pending.push({handler:a,callback:d});this.processPending()};e.prototype.processPending=function(a){"undefined"===typeof a&&(a=!1);var d=this;if(a&&0<d._pending.length||!a&&1===d._pending.length){var b=d._pending[0];b.close?(d._db&&(d._db.close(),d._collection= null,d._db=null,d._logger.debug("STORE","%s: Database has been closed",d.id())),d._pending.shift()):d.getRoot().then(function(){d.tryHandler(b.handler).then(function(a){d._logger.debug("STORE","%s: Invoking user callback",d.id());b.callback(null,a);d._pending.shift();d.processPending(!0)},function(a){a&&(d._logger.debug("STORE","%s: Invoking user callback with error %j",d.id(),a),b.callback(a,null),d._pending.shift());d.processPending(!0)})},function(a){d._logger.debug("STORE","%s: Invoking user callback with error %j", d.id(),a);b.callback(a,null);d._pending.shift();d.processPending(!0)})}};e.prototype.tryHandler=function(a,d){"undefined"===typeof d&&(d=new j.Promise);var b=this;try{b._logger.debug("STORE","%s: Invoking user handler",b.id());b.markRead(b._root);var f=a(b._root);try{b._logger.debug("STORE","%s: Attempting commit",b.id()),b.commitMtx(b.mtx(b._cache)).then(function(){b._logger.debug("STORE","%s: Update completed successfully",b.id());b.okMtx(b._cache);d.resolve(f)},function(a){c.utils.isArray(a)?0!== a.length&&(b._logger.debug("STORE","Objects need refresh after commit failure"),b.undo(),b.locked(function(){return b.refreshSet(a)}).then(function(){b._logger.debug("STORE","Starting re-try");d.reject(null)},function(a){d.reject(a)})):d.reject(a)})}catch(e){b._logger.fatal("Unhandled exception",c.utils.exceptionInfo(e))}}catch(g){if(b._logger.debug("STORE","Exception during try: ",c.utils.exceptionInfo(g)),b.undo(),g instanceof c.tracker.UnknownReference){var t=b._cache.find(g.missing());if(null=== t)t=b.getCollection(),t=b.wait(t,function(){return b.locked(function(){var a=b.getObject(g.missing());return a=b.wrap(a,function(a){if(void 0!==g.id()){var c=b._cache.find(g.id());null!==c&&(b.disable++,c[g.prop()]=a,b.disable--,d.reject(null))}})})});else{var h=this._cache.find(g.id());b.disable++;h[g.prop()]=t;b.disable--;d.reject(null)}}else d.reject(g)}return d};e.prototype.commitMtx=function(a){c.utils.dassert(c.utils.isValue(a));this._logger.debug("STORE","%s: commitMtx()",this.id(),a.toString()); var d=this;return d.locked(function(){return d.applyMtx(a)})};e.prototype.applyMtx=function(a){var d=this,b=new j.Promise;d.checkReadset(a.rset).then(function(a){a=a.filter(function(a){return null!==a});0<a.length?(d._logger.debug("STORE","%s: checkReadset failures",d.id(),a),b.reject(a)):b.resolve()},function(a){d._logger.debug("STORE","%s: checkReadset failed",d.id());b.reject(a)});return d.wait(b,function(){return d.makeChanges(a)})};e.prototype.makeChanges=function(a){var d=this,b=new j.Promise; b.resolve();for(var f=new c.utils.IdMap,e=a.nset,g=0;g<e.size();g++){var h=e.at(g);c.utils.dassert(null===this._cache.find(h.id));for(var q=Object.keys(h.obj),l=0;l<q.length;l++){var p=h.obj[q[l]];c.utils.isObjectOrArray(p)&&null===c.tracker.getTrackerUnsafe(p)&&(p=this.valueId(p),p=f.findOrInsert(p,{uprev:!1,ref:-1,reinit:!1}),p.ref++)}}for(g=0;g<e.size();g++)h=e.at(g),c.utils.dassert(null===this._cache.find(h.id)),b=d.wait(b,function(a,b){return function(){return d.writeObject(a,b,0,1)}}(h.id,h.obj)), p={uprev:!1,ref:-1,reinit:!1},f.findOrInsert(h.id,{uprev:!1,ref:-1,reinit:!1}),new c.tracker.Tracker(d,h.obj,h.id,0),d._cache.insert(h.id,h.obj);a=a.cset;for(g=0;g<a.size();g++){var h=a.at(g),q=c.tracker.getTracker(h.obj),e=q.id(),u=q.getData(),p=f.findOrInsert(q.id(),{uprev:!0,ref:0,reinit:!1});p.uprev=!0;if(void 0!==h.write)c.utils.isObjectOrArray(h.last)&&(p=this.objectID(h.last),f.findOrInsert(p,{uprev:!0,ref:0,reinit:!1}).ref--,u.rout--),q=h.value,c.utils.isObjectOrArray(q)&&(p=this.objectID(q), q=new c.serial.Reference(p),f.findOrInsert(p,{uprev:!0,ref:0,reinit:!1}).ref++,u.rout++),b=d.wait(b,function(a,b,c){return function(){return d.writeProp(a,b,c)}}(e,h.write,q));else if(void 0!==h.del)0<u.rout&&(b=d.wait(b,function(a,b){return function(){return d.readProp(a,b)}}(q.id(),h.del)),b=d.wrap(b,function(a){if(c.utils.isObject(a)){var d=Object.keys(a);1===d.length&&"_id"===d[0]&&(f.findOrInsert(a._id,{uprev:!1,ref:0,reinit:!1}).ref--,u.rout--)}})),b=d.wait(b,function(a,b){return function(){return d.deleteProp(a, b)}}(q.id(),h.del));else if(void 0!==h.shift)if(0===h.shift||-1===h.shift){p=h.size;h=0===h.shift;for(q=function(a,b){return function(){return d.arrayPop(a,b)}};p--;)b=d.wait(b,q(e,h))}else p.reinit=!0;else void 0!==h.unshift?p.reinit=!0:void 0!==h.reinit?p.reinit=!0:void 0!==h.reverse?p.reinit=!0:this._logger.fatal("%s: cset contains unexpected command",q.id())}var v=new j.Promise;b.then(function(){var a=new j.Promise;a.resolve();f.apply(function(b,f){if(f.reinit){var e=d._cache.find(b),k=c.tracker.getTracker(e), g=k.getData();a=d.wait(a,function(a,b,c,f){return function(){return d.writeObject(a,b,c,f)}}(b,e,k.rev(),g.rin+f.ref))}else if(f.uprev||0!==f.ref)a=d.wait(a,function(a,b,c){return function(){return d.changeRevAndRef(a,b,c)}}(b,f.uprev,f.ref))});a.then(function(){v.resolve()},function(a){v.reject(a)})},function(a){v.reject(a)});return v};e.prototype.undo=function(){this.undoMtx(this._cache);c.tracker.getTracker(this._root).isDead()&&(this._root=null)};e.prototype.objectID=function(a){c.utils.dassert(c.utils.isObjectOrArray(a)); if(a instanceof c.serial.Reference)return a.id();var d=c.tracker.getTrackerUnsafe(a);return d?d.id():this.valueId(a)};e.prototype.fail=function(a,d){for(var b=[],f=0;f<arguments.length-2;f++)b[f]=arguments[f+2];b=c.utils.format("",d,b);this._logger.debug("STORE",b);a.reject(Error(b))};e.prototype.updateObject=function(a,d){"Object"===a._type?c.utils.isValue(d)?c.utils.dassert(c.utils.isObject(d)):d={}:"Array"===a._type?c.utils.isValue(d)?(c.utils.dassert(c.utils.isArray(d)),d.length=0):d=[]:this._logger.fatal("%s: Unexpected document type: %j", this.id(),a._type);this.disable++;for(var b=Object.keys(a._data),f=0,e=Object.keys(d),g=0,j=0;f!==b.length;){var h=b[f];if(-1!==g&&h!=e[g]){for(;g<e.length;g++)delete d[e[g]];g=-1}var l=a._data[b[f]];if(c.utils.isObject(l)){var p=Object.keys(l);1===p.length&&"_id"===p[0]&&(l=new c.serial.Reference(l._id),j++)}d[h]=l;f++}this.disable--;return{obj:d,id:a._id,rev:a._rev,ref:a._ref,out:j}};e.prototype.wait=function(a,d){var b=this,c=new j.Promise;a.then(function(){d.apply(b,arguments).then(function(){c.resolve.apply(c, arguments)},function(a){c.reject(a)})},function(a){c.reject(a)});return c};e.prototype.wrap=function(a,d){var b=this,c=new j.Promise;a.then(function(){c.resolve(d.apply(b,arguments))});return c};e.prototype.locked=function(a){var d=this,b=new j.Promise;d.lock().then(function(){a().then(function(){var a=arguments;d.removeLock().then(function(){b.resolve(a)},function(a){b.reject(a)})},function(a){d.removeLock().then(function(){b.reject(a)},function(a){b.reject(a)})})},function(a){b.reject(a)});return b}; e.prototype.getCollection=function(){var a=this,d=new j.Promise;if(null!==a._collection)return d.resolve(a._collection),d;a._logger.debug("STORE","%s: Connecting to database - %s",a.id(),a._dbName);a._db=new h.Db(a._dbName,new h.Server(a._host,a._port,{poolSize:1}),{w:1});a._db.open(function(b){b?a.fail(d,"%s: Unable to open db: %s : %s",a.id(),a._dbName,b.message):(a._logger.debug("STORE","%s: Opening collection - %s",a.id(),a._collectionName),a._db.createCollection(a._collectionName,function(b, c){if(b)a.fail(d,"%s: Unable to open collection: %s : %s",a.id(),a._collectionName,b.message);else{a._collection=c;var e=a.ensureExists(l,{locked:!1},null),e=a.wait(e,function(){return a.ensureExists(f.rootUID,{_rev:0,_ref:1,_type:"Object",_data:{}},c)});e.then(function(){d.resolve()},function(a){d.resolve(a)})}}))});return d};e.prototype.lock=function(a){"undefined"===typeof a&&(a=1);var d=this,b=new j.Promise;d._logger.debug("STORE","%s: Trying to acquire lock",d.id());var f=c.utils.toObjectID(l), e=(new g.ObjectId).toString();d._collection.findAndModify({_id:f,locked:!1},[],{_id:f,owner:d.id().toString(),host:c.utils.hostInfo(),pid:process.pid,rand:e,locked:!0},{safe:!0,upsert:!1,remove:!1,"new":!1},function(c,e){c?d.fail(b,"%s: Unable query lock : %s",d.id(),c.message):e?(d._logger.debug("STORE","%s: Acquired lock",d.id()),b.resolve()):100<a?d._collection.findOne({_id:f},function(c,f){c?d.fail(b,"%s: Unable query lock : %s",d.id(),c.message):(d._logger.debug("STORE","%s: Locked by: %s",d.id(), f.host),f&&(void 0!==f.rand&&d._lockRand!==f.rand)&&(d._lockRand&&d._logger.debug("STORE","%s: Lock rand has changed, %s to %s, reseting timeout",d.id(),d._lockRand,f.rand),d._lockRand=f.rand,a=100),1E4<a?(d._logger.debug("STORE","%s: Lock owner must be dead, trying to remove",d.id()),d.removeLock().then(function(){d.lock().then(function(){b.resolve()},function(a){b.reject(a)})},function(a){b.resolve(a)})):setTimeout(function(){d.lock(2*a).then(function(){b.resolve()},function(a){b.reject(a)})},a))}): setTimeout(function(){d.lock(2*a).then(function(){b.resolve()},function(a){b.reject(a)})},a)});return b};e.prototype.removeLock=function(){var a=this,d=new j.Promise,b=c.utils.toObjectID(l);a._collection.update({_id:b},{_id:b,locked:!1},{safe:a._safe,upsert:!0},function(b){b?a.fail(d,"%s: Unable remove lock : %s",a.id(),b.message):(a._logger.debug("STORE","%s: Released lock",a.id()),a._lockRand=null,d.resolve())});return d};e.prototype.getRoot=function(){var a=this,b=new j.Promise;null!==a._root? b.resolve(a._root):a.getCollection().then(function(){a.lock().then(function(){a.getObject(f.rootUID).then(function(c){a.removeLock().then(function(){a._root=c;b.resolve(c)},function(a){b.reject(a)})},function(c){a.removeLock().then(function(){b.reject(c)})})},function(a){b.reject(a)})},function(a){b.reject(a)});return b};e.prototype.getObject=function(a){var b=new j.Promise,e=this;e.getCollection().then(function(g){e._logger.debug("STORE","%s: Searching for object: %s",e.id(),a);g.findOne({_id:c.utils.toObjectID(a)}, function(g,j){if(g)e.fail(b,"%s: Unable to search collection: %s : %s",e.id(),e._collectionName,g.message);else if(null===j)e.fail(b,"%s: Object missing in store: %s",e.id(),a);else{e._logger.debug("STORE","%s: Loading object: %s:%d",e.id(),a,j._rev);var h=e._cache.find(a),h=e.updateObject(j,h),m=c.tracker.getTrackerUnsafe(h.obj);null===m?(m=new c.tracker.Tracker(e,h.obj,h.id,h.rev),e._cache.insert(m.id(),h.obj)):(m.setRev(h.rev),m.retrack(h.obj));m.setData({rout:h.out,rin:j._ref});m.id().toString()=== f.rootUID.toString()&&(e._root=h.obj);b.resolve(h.obj)}})});return b};e.prototype.refreshSet=function(a){for(var b=[],c=0;c<a.length;c++)b.push(this.getObject(a[c]));return j.all(b)};e.prototype.writeObject=function(a,b,f,e){c.utils.dassert(c.utils.isValue(a)&&c.utils.isObjectOrArray(b));var g=this,h={};h._data=c.utils.clone(b);for(var l=Object.keys(b),q=0;q<l.length;q++)if(c.utils.isObjectOrArray(b[l[q]])){var w=g.valueId(b[l[q]]);h._data[l[q]]={_id:w.toString()}}h._id=c.utils.toObjectID(a);h._rev= f;h._ref=e;h._type=c.utils.isObject(b)?"Object":"Array";var p=new j.Promise;g._logger.debug("STORE","%s: Updating object: %s %j",g.id(),a,b);g._collection.update({_id:h._id},h,{safe:g._safe,upsert:!0},function(a,c){a?g.fail(p,"%s: Update failed on new object %s=%j error %s",g.id(),w,b,a.message):g._safe&&1!==c?g.fail(p,"%s: Update failed on new object %s=%j count %d",g.id(),w,b,c):p.resolve()});return p};e.prototype.ensureExists=function(a,b,f){var e=this,g=new j.Promise;e._logger.debug("STORE","%s: Checking/inserting for object: %s", e.id(),a);b._id=c.utils.toObjectID(a);e._collection.findOne({_id:c.utils.toObjectID(a)},function(c,j){c?e.fail(g,"%s: Unable to search collection: %s : %s",e.id(),e._collectionName,c.message):null===j?e._collection.insert(b,{safe:!0},function(b){b?e._logger.debug("STORE","%s: Unable to insert %s (ignoring as maybe race)",e.id(),a):e._logger.debug("STORE","%s: Object %s inserted",e.id(),a);g.resolve(f)}):(e._logger.debug("STORE","%s: Object %s already exists",e.id(),a),g.resolve(f))});return g};e.prototype.changeRevAndRef= function(a,b,e){var f=this,g=new j.Promise;f._logger.debug("STORE","%s: Updating object rev & ref: %s uprev: %s, upref %d",f.id(),a,b,e);var h=0;b&&(h=1);f._collection.findAndModify({_id:c.utils.toObjectID(a)},[],{$inc:{_rev:h,_ref:e}},{safe:!0,remove:!1,upsert:!1,"new":!0},function(b,d){b?f.fail(g,"%s: Update failed on object ref for %s error %s",f.id(),a,b.message):null===d?f.fail(g,"%s: Update failed on object ref for %s empty doc",f.id(),a):0===d._ref?f.deleteObject(a).then(function(){g.resolve()}, function(a){g.reject(a)}):g.resolve()});return g};e.prototype.deleteObject=function(a){var b=this,e=new j.Promise;b._logger.debug("STORE","%s: Deleting object: %s",b.id(),a);b._collection.remove({_id:c.utils.toObjectID(a)},{safe:b._safe},function(c,f){c?b.fail(e,"%s: Deleting failed on %s error %s",b.id(),a,c.message):b._safe&&1!==f?b.fail(e,"%s: Deleting failed on %s count %d",b.id(),a,f):e.resolve()});return e};e.prototype.readProp=function(a,b){var e=this,f=new j.Promise,g={};g["_data."+b]=!0; e._logger.debug("STORE","%s: Reading prop for object: %s[%s]",e.id(),a,b);e._collection.findOne({_id:c.utils.toObjectID(a)},g,function(c,g){c?e.fail(f,"%s: Unable to search collection: %s : %s",e.id(),e._collectionName,c.message):null===g?e.fail(f,"%s: Object missing in store: %s : %s",e.id(),a):f.resolve(g._data[b])});return f};e.prototype.writeProp=function(a,b,e){var f=this,g=new j.Promise;e instanceof c.serial.Reference&&(e={_id:e.id()});var h={};h["_data."+b]=e;f._logger.debug("STORE","%s: Updating property: %s[%s] %j", f.id(),a,b,e);f._collection.update({_id:c.utils.toObjectID(a)},{$set:h},{safe:f._safe},function(c,j){c?f.fail(g,"%s: Update failed on %s[%s] %j error %s",f.id(),a,b,e,c.message):f._safe&&1!==j?f.fail(g,"%s: Update failed on %s[%s] %j count %d",f.id(),a,b,e,j):g.resolve()});return g};e.prototype.deleteProp=function(a,b){var e=this,f=new j.Promise,g={};g["_data."+b]="";e._logger.debug("STORE","%s: Deleting property: %s[%s]",e.id(),a,b);e._collection.update({_id:c.utils.toObjectID(a)},{$unset:g},{safe:e._safe}, function(c,g){c?e.fail(f,"%s: Deleting failed on %s[%s] error %s",e.id(),a,b,c.message):e._safe&&1!==g?e.fail(f,"%s: Deleting failed on %s[%s] count %d",e.id(),a,b,g):f.resolve()});return f};e.prototype.arrayPop=function(a,b){var e=this,f=new j.Promise,g=1,h="back";b&&(g=-1,h="front");e._logger.debug("STORE","%s: Array pop: %s[%s]",e.id(),a,h);e._collection.update({_id:c.utils.toObjectID(a)},{$pop:{_data:g}},{safe:e._safe},function(b,d){b?e.fail(f,"%s: Array pop failed on %s[%s] error %s",e.id(), a,h,b.message):e._safe&&1!==d?e.fail(f,"%s: Array pop failed on %s[%s] count %d",e.id(),a,h,d):f.resolve()});return f};e.prototype.checkReadset=function(a){this._logger.debug("STORE","%s: checkReadset(%d)",this.id(),a.size());var b=this;c.utils.dassert(0!==a.size());var e=[];a.apply(function(a,c){e.push(b.revisionCheck(a,c));return!0});return j.all(e)};e.prototype.revisionCheck=function(a,b){this._logger.debug("STORE","%s: revisionCheck(%s,%s)",this.id(),a,b);var e=new j.Promise;this._collection.find({_id:c.utils.toObjectID(a), _rev:b}).count(function(b,d){b?e.reject(b.message):1===d?e.resolve(null):e.resolve(a)});return e};f.MongoStore=e})(shared||(shared={})); (function(c){var f=c.message||(c.message={}),j=function(){var d=a;null!=d?(a=a.next,d.next=null):d=new b;return d},h=require("cluster"),g=h.worker?h.worker.uniqueID:0,l=function(b,a){this.rid=b;this.worker=c.utils.isValue(a)?a:g};l._network=null;l.networkAddress=function(){null===l._network&&(l._network=new l(null,0));return l._network};f.Address=l;var b=function(){this.body=this.from_worker=this.from_rid=this.to_worker=this.to_rid=this.next=null},e=null;f.isMessage=function(a){a=c.types.TypeStore.instance().type(a); null===e&&(e=c.types.TypeStore.instance().type(new b));return a===e};f.setTo=function(a,b){c.utils.dassert(c.utils.isObject(a));c.utils.dassert(c.utils.isObject(b));a.to_rid=b.rid;a.to_worker=b.worker};f.setFrom=function(a,b){c.utils.dassert(c.utils.isObject(a));c.utils.dassert(c.utils.isObject(b));a.from_rid=b.rid;a.from_worker=b.worker};f.replyTo=function(a,b){c.utils.dassert(c.utils.isObject(a));c.utils.dassert(c.utils.isObject(b));a.to_rid=b.from_rid;a.to_worker=b.from_worker};var a=null;f.getMessage= j;f.getMessageFor=function(a){var b=j();f.setFrom(b,a);return b};f.returnMessage=function(b){b.next=a;a=b}})(shared||(shared={}));var ver="0.2.0";exports.version=function(){return ver};exports.info=function(){return"Shared "+ver+" Copyright(c) Kevin Jones @hutkev"};exports.createStore=shared.store.createStore;exports.debug={};exports.debug.log=function(c){shared.utils.defaultLogger().enableDebugLogging(c)};exports.debug.assert=shared.utils.enableAsserts;exports.tests={};exports.tests.utils=shared.utils; exports.tests.types=shared.types;exports.tests.tracker=shared.tracker;exports.tests.store=shared.store;