Skip to content

Instantly share code, notes, and snippets.

@neagle
Last active February 8, 2016 04:20
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 neagle/c63d06baa4691641b555 to your computer and use it in GitHub Desktop.
Save neagle/c63d06baa4691641b555 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
var mongoose = require('mongoose');
var _ = require('lodash');
// Set up a Schema with some required elements, and a field with an array
var ThingSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
quantity: {
type: Number,
required: true
},
age: {
type: Number,
required: true
},
// NOTE! Quantity ane Name share the same name as fields in their parent
things: [{
quantity: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
weight: {
type: Number,
required: true
}
}]
});
// Try to validate a document with none of the required fields
var doc1 = new mongoose.Document({
things: [{}]
}, ThingSchema);
// The results don't display messages for things.name or things.quntity, but they DO for things.weight
doc1.validate(function (result) {
document.getElementById('log1').innerHTML = '<ul>' + _.map(Object.keys(result.errors), function (key) { return '<li>' + key + '</li>'; }).join('') + '</ul>';
console.log(result.errors);
});
// With values put in for name and quantity on the main doc, validation errors show up for things.name and things.quantity
var doc2 = new mongoose.Document({
name: 'Thingamajig',
quantity: 2,
things: [{}]
}, ThingSchema);
doc2.validate(function (result) {
document.getElementById('log2').innerHTML = '<ul>' + _.map(Object.keys(result.errors), function (key) { return '<li>' + key + '</li>'; }).join('') + '</ul>';
console.log(result.errors);
});
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){function ES6Promise(){throw new Error("Can't use ES6 promise with mpromise style constructor")}ES6Promise.use=function(Promise){ES6Promise.ES6=Promise};module.exports=ES6Promise},{}],2:[function(require,module,exports){var NodeJSDocument=require("./document"),EventEmitter=require("events").EventEmitter,MongooseError=require("./error"),Schema=require("./schema"),ObjectId=require("./types/objectid"),utils=require("./utils"),ValidationError=MongooseError.ValidationError,InternalCache=require("./internal");function Document(obj,schema,fields,skipId,skipInit){if(!(this instanceof Document)){return new Document(obj,schema,fields,skipId,skipInit)}if(utils.isObject(schema)&&!schema.instanceOfSchema){schema=new Schema(schema)}schema=this.schema||schema;if(!this.schema&&schema.options._id){obj=obj||{};if(obj._id===undefined){obj._id=new ObjectId}}if(!schema){throw new MongooseError.MissingSchemaError}this.$__setSchema(schema);this.$__=new InternalCache;this.$__.emitter=new EventEmitter;this.isNew=true;this.errors=undefined;if(typeof fields==="boolean"){this.$__.strictMode=fields;fields=undefined}else{this.$__.strictMode=this.schema.options&&this.schema.options.strict;this.$__.selected=fields}var required=this.schema.requiredPaths();for(var i=0;i<required.length;++i){this.$__.activePaths.require(required[i])}this.$__.emitter.setMaxListeners(0);this._doc=this.$__buildDoc(obj,fields,skipId);if(!skipInit&&obj){this.init(obj)}this.$__registerHooksFromSchema();for(var m in schema.methods){this[m]=schema.methods[m]}for(var s in schema.statics){this[s]=schema.statics[s]}}Document.prototype=Object.create(NodeJSDocument.prototype);Document.prototype.constructor=Document;Document.ValidationError=ValidationError;module.exports=exports=Document},{"./document":4,"./error":11,"./internal":22,"./schema":25,"./types/objectid":45,"./utils":47,events:94}],3:[function(require,module,exports){var utils=require("./utils");var Types=require("./schema/index");module.exports=function cast(schema,obj){var paths=Object.keys(obj),i=paths.length,any$conditionals,schematype,nested,path,type,val;while(i--){path=paths[i];val=obj[path];if(path==="$or"||path==="$nor"||path==="$and"){var k=val.length;while(k--){val[k]=cast(schema,val[k])}}else if(path==="$where"){type=typeof val;if(type!=="string"&&type!=="function"){throw new Error("Must have a string or function for $where")}if(type==="function"){obj[path]=val.toString()}continue}else if(path==="$elemMatch"){val=cast(schema,val)}else{if(!schema){continue}schematype=schema.path(path);if(!schematype){var split=path.split("."),j=split.length,pathFirstHalf,pathLastHalf,remainingConds;while(j--){pathFirstHalf=split.slice(0,j).join(".");schematype=schema.path(pathFirstHalf);if(schematype){break}}if(schematype){if(schematype.caster&&schematype.caster.schema){remainingConds={};pathLastHalf=split.slice(j).join(".");remainingConds[pathLastHalf]=val;obj[path]=cast(schematype.caster.schema,remainingConds)[pathLastHalf]}else{obj[path]=val}continue}if(utils.isObject(val)){var geo=val.$near?"$near":val.$nearSphere?"$nearSphere":val.$within?"$within":val.$geoIntersects?"$geoIntersects":"";if(!geo){continue}var numbertype=new Types.Number("__QueryCasting__");var value=val[geo];if(val.$maxDistance){val.$maxDistance=numbertype.castForQuery(val.$maxDistance)}if(geo==="$within"){var withinType=value.$center||value.$centerSphere||value.$box||value.$polygon;if(!withinType){throw new Error("Bad $within paramater: "+JSON.stringify(val))}value=withinType}else if(geo==="$near"&&typeof value.type==="string"&&Array.isArray(value.coordinates)){value=value.coordinates}else if((geo==="$near"||geo==="$nearSphere"||geo==="$geoIntersects")&&value.$geometry&&typeof value.$geometry.type==="string"&&Array.isArray(value.$geometry.coordinates)){value=value.$geometry.coordinates}_cast(value,numbertype)}}else if(val===null||val===undefined){obj[path]=null;continue}else if(val.constructor.name==="Object"){any$conditionals=Object.keys(val).some(function(k){return k.charAt(0)==="$"&&k!=="$id"&&k!=="$ref"});if(!any$conditionals){obj[path]=schematype.castForQuery(val)}else{var ks=Object.keys(val),$cond;k=ks.length;while(k--){$cond=ks[k];nested=val[$cond];if($cond==="$exists"){if(typeof nested!=="boolean"){throw new Error("$exists parameter must be Boolean")}continue}if($cond==="$type"){if(typeof nested!=="number"){throw new Error("$type parameter must be Number")}continue}if($cond==="$not"){cast(schema,nested)}else{val[$cond]=schematype.castForQuery($cond,nested)}}}}else{obj[path]=schematype.castForQuery(val)}}}return obj};function _cast(val,numbertype){if(Array.isArray(val)){val.forEach(function(item,i){if(Array.isArray(item)||utils.isObject(item)){return _cast(item,numbertype)}val[i]=numbertype.castForQuery(item)})}else{var nearKeys=Object.keys(val);var nearLen=nearKeys.length;while(nearLen--){var nkey=nearKeys[nearLen];var item=val[nkey];if(Array.isArray(item)||utils.isObject(item)){_cast(item,numbertype);val[nkey]=item}else{val[nkey]=numbertype.castForQuery(item)}}}}},{"./schema/index":32,"./utils":47}],4:[function(require,module,exports){(function(process,Buffer){var EventEmitter=require("events").EventEmitter,MongooseError=require("./error"),MixedSchema=require("./schema/mixed"),Schema=require("./schema"),ObjectExpectedError=require("./error/objectExpected"),StrictModeError=require("./error/strict"),ValidatorError=require("./schematype").ValidatorError,utils=require("./utils"),clone=utils.clone,isMongooseObject=utils.isMongooseObject,inspect=require("util").inspect,ValidationError=MongooseError.ValidationError,InternalCache=require("./internal"),deepEqual=utils.deepEqual,hooks=require("hooks-fixed"),PromiseProvider=require("./promise_provider"),DocumentArray,MongooseArray,Embedded;function Document(obj,fields,skipId){this.$__=new InternalCache;this.$__.emitter=new EventEmitter;this.isNew=true;this.errors=undefined;var schema=this.schema;if(typeof fields==="boolean"){this.$__.strictMode=fields;fields=undefined}else{this.$__.strictMode=schema.options&&schema.options.strict;this.$__.selected=fields}var required=schema.requiredPaths(true);for(var i=0;i<required.length;++i){this.$__.activePaths.require(required[i])}this.$__.emitter.setMaxListeners(0);this._doc=this.$__buildDoc(obj,fields,skipId);if(obj){this.set(obj,undefined,true)}if(!schema.options.strict&&obj){var _this=this,keys=Object.keys(this._doc);keys.forEach(function(key){if(!(key in schema.tree)){defineKey(key,null,_this)}})}this.$__registerHooksFromSchema()}utils.each(["on","once","emit","listeners","removeListener","setMaxListeners","removeAllListeners","addListener"],function(emitterFn){Document.prototype[emitterFn]=function(){return this.$__.emitter[emitterFn].apply(this.$__.emitter,arguments)}});Document.prototype.constructor=Document;Document.prototype.schema;Document.prototype.isNew;Document.prototype.id;Document.prototype.errors;Document.prototype.$__buildDoc=function(obj,fields,skipId){var doc={};var exclude=null;var keys;var ki;var _this=this;if(fields&&utils.getFunctionName(fields.constructor)==="Object"){keys=Object.keys(fields);ki=keys.length;if(ki===1&&keys[0]==="_id"){exclude=!!fields[keys[ki]]}else{while(ki--){if(keys[ki]!=="_id"&&(!fields[keys[ki]]||typeof fields[keys[ki]]!=="object")){exclude=!fields[keys[ki]];break}}}}var paths=Object.keys(this.schema.paths),plen=paths.length,ii=0;for(;ii<plen;++ii){var p=paths[ii];if(p==="_id"){if(skipId){continue}if(obj&&"_id"in obj){continue}}var type=this.schema.paths[p];var path=p.split(".");var len=path.length;var last=len-1;var curPath="";var doc_=doc;var i=0;var included=false;for(;i<len;++i){var piece=path[i],def;curPath+=piece;if(exclude===true){if(curPath in fields){break}}else if(fields&&curPath in fields){included=true}if(i===last){if(fields&&exclude!==null){if(exclude===true){if(p in fields){continue}def=type.getDefault(_this,true);if(typeof def!=="undefined"){doc_[piece]=def;_this.$__.activePaths.default(p)}}else if(included){def=type.getDefault(_this,true);if(typeof def!=="undefined"){doc_[piece]=def;_this.$__.activePaths.default(p)}}}else{def=type.getDefault(_this,true);if(typeof def!=="undefined"){doc_[piece]=def;_this.$__.activePaths.default(p)}}}else{doc_=doc_[piece]||(doc_[piece]={});curPath+="."}}}return doc};Document.prototype.init=function(doc,opts,fn){if(typeof opts==="function"){fn=opts;opts=null}this.isNew=false;if(doc._id!==null&&doc._id!==undefined&&opts&&opts.populated&&opts.populated.length){var id=String(doc._id);for(var i=0;i<opts.populated.length;++i){var item=opts.populated[i];this.populated(item.path,item._docs[id],item)}}init(this,doc,this._doc);this.$__storeShard();this.emit("init",this);if(fn){fn(null)}return this};function init(self,obj,doc,prefix){prefix=prefix||"";var keys=Object.keys(obj),len=keys.length,schema,path,i;while(len--){i=keys[len];path=prefix+i;schema=self.schema.path(path);if(!schema&&utils.isObject(obj[i])&&(!obj[i].constructor||utils.getFunctionName(obj[i].constructor)==="Object")){if(!doc[i]){doc[i]={}}init(self,obj[i],doc[i],path+".")}else{if(obj[i]===null){doc[i]=null}else if(obj[i]!==undefined){if(schema){try{doc[i]=schema.cast(obj[i],self,true)}catch(e){self.invalidate(e.path,new ValidatorError({path:e.path,message:e.message,type:"cast",value:e.value}))}}else{doc[i]=obj[i]}}if(!self.isModified(path)){self.$__.activePaths.init(path)}}}}Document.prototype.$__storeShard=function(){var key=this.schema.options.shardKey||this.schema.options.shardkey;if(!(key&&utils.getFunctionName(key.constructor)==="Object")){return}var orig=this.$__.shardval={},paths=Object.keys(key),len=paths.length,val;for(var i=0;i<len;++i){val=this.getValue(paths[i]);if(isMongooseObject(val)){orig[paths[i]]=val.toObject({depopulate:true})}else if(val!==null&&val!==undefined&&val.valueOf&&(!val.constructor||utils.getFunctionName(val.constructor)!=="Date")){orig[paths[i]]=val.valueOf()}else{orig[paths[i]]=val}}};for(var k in hooks){Document.prototype[k]=Document[k]=hooks[k]}Document.prototype.update=function update(){var args=utils.args(arguments);args.unshift({_id:this._id});return this.constructor.update.apply(this.constructor,args)};Document.prototype.set=function(path,val,type,options){if(type&&utils.getFunctionName(type.constructor)==="Object"){options=type;type=undefined}var merge=options&&options.merge,adhoc=type&&type!==true,constructing=type===true,adhocs;var strict=options&&"strict"in options?options.strict:this.$__.strictMode;if(adhoc){adhocs=this.$__.adhocPaths||(this.$__.adhocPaths={});adhocs[path]=Schema.interpretAsType(path,type,this.schema.options)}if(typeof path!=="string"){if(path===null||path===void 0){var _=path;path=val;val=_}else{var prefix=val?val+".":"";if(path instanceof Document){if(path.$__isNested){path=path.toObject()}else{path=path._doc}}var keys=Object.keys(path),i=keys.length,pathtype,key;while(i--){key=keys[i];var pathName=prefix+key;pathtype=this.schema.pathType(pathName);if(path[key]!==null&&path[key]!==undefined&&utils.isObject(path[key])&&(!path[key].constructor||utils.getFunctionName(path[key].constructor)==="Object")&&pathtype!=="virtual"&&pathtype!=="real"&&!(this.$__path(pathName)instanceof MixedSchema)&&!(this.schema.paths[pathName]&&this.schema.paths[pathName].options&&this.schema.paths[pathName].options.ref)){this.set(path[key],prefix+key,constructing)}else if(strict){if(pathtype==="real"||pathtype==="virtual"){if(this.schema.paths[pathName]&&this.schema.paths[pathName].$isSingleNested&&path[key]instanceof Document){path[key]=path[key].toObject({virtuals:false})}this.set(prefix+key,path[key],constructing)}else if(pathtype==="nested"&&path[key]instanceof Document){this.set(prefix+key,path[key].toObject({virtuals:false}),constructing)}else if(strict==="throw"){if(pathtype==="nested"){throw new ObjectExpectedError(key,path[key])}else{throw new StrictModeError(key)}}}else if(undefined!==path[key]){this.set(prefix+key,path[key],constructing)}}return this}}var pathType=this.schema.pathType(path);if(pathType==="nested"&&val){if(utils.isObject(val)&&(!val.constructor||utils.getFunctionName(val.constructor)==="Object")){if(!merge){this.setValue(path,null)}this.set(val,path,constructing);return this}this.invalidate(path,new MongooseError.CastError("Object",val,path));return this}var schema;var parts=path.split(".");if(pathType==="adhocOrUndefined"&&strict){var mixed;for(i=0;i<parts.length;++i){var subpath=parts.slice(0,i+1).join(".");schema=this.schema.path(subpath);if(schema instanceof MixedSchema){mixed=true;break}}if(!mixed){if(strict==="throw"){throw new StrictModeError(path)}return this}}else if(pathType==="virtual"){schema=this.schema.virtualpath(path);schema.applySetters(val,this);return this}else{schema=this.$__path(path)}var pathToMark;if(parts.length<=1){pathToMark=path}else{for(i=0;i<parts.length;++i){subpath=parts.slice(0,i+1).join(".");if(this.isDirectModified(subpath)||this.get(subpath)===null){pathToMark=subpath;break}}if(!pathToMark){pathToMark=path}}var priorVal=constructing?undefined:this.getValue(path);if(!schema){this.$__set(pathToMark,path,constructing,parts,schema,val,priorVal);return this}var shouldSet=true;try{var didPopulate=false;if(schema.options&&schema.options.ref&&val instanceof Document&&schema.options.ref===val.constructor.modelName){if(this.ownerDocument){this.ownerDocument().populated(this.$__fullPath(path),val._id,{model:val.constructor})}else{this.populated(path,val._id,{model:val.constructor})}didPopulate=true}if(schema.options&&Array.isArray(schema.options.type)&&schema.options.type.length&&schema.options.type[0].ref&&Array.isArray(val)&&val.length>0&&val[0]instanceof Document&&val[0].constructor.modelName&&schema.options.type[0].ref===val[0].constructor.modelName){if(this.ownerDocument){this.ownerDocument().populated(this.$__fullPath(path),val.map(function(v){return v._id}),{model:val[0].constructor})}else{this.populated(path,val.map(function(v){return v._id}),{model:val[0].constructor})}didPopulate=true}val=schema.applySetters(val,this,false,priorVal);if(!didPopulate&&this.$__.populated){delete this.$__.populated[path]}this.$markValid(path)}catch(e){var reason;if(!(e instanceof MongooseError.CastError)){reason=e}this.invalidate(path,new MongooseError.CastError(schema.instance,val,path,reason));shouldSet=false}if(shouldSet){this.$__set(pathToMark,path,constructing,parts,schema,val,priorVal)}return this};Document.prototype.$__shouldModify=function(pathToMark,path,constructing,parts,schema,val,priorVal){if(this.isNew){return true}if(undefined===val&&!this.isSelected(path)){return true}if(undefined===val&&path in this.$__.activePaths.states.default){return false}if(!deepEqual(val,priorVal||this.get(path))){return true}if(!constructing&&val!==null&&val!==undefined&&path in this.$__.activePaths.states.default&&deepEqual(val,schema.getDefault(this,constructing))){return true}return false};Document.prototype.$__set=function(pathToMark,path,constructing,parts,schema,val,priorVal){Embedded=Embedded||require("./types/embedded");var shouldModify=this.$__shouldModify(pathToMark,path,constructing,parts,schema,val,priorVal);var _this=this;if(shouldModify){this.markModified(pathToMark,val);MongooseArray||(MongooseArray=require("./types/array"));if(val&&val.isMongooseArray){val._registerAtomic("$set",val);this.$__.activePaths.forEach(function(modifiedPath){if(modifiedPath.indexOf(path+".")===0){_this.$__.activePaths.ignore(modifiedPath)}})}}var obj=this._doc,i=0,l=parts.length;for(;i<l;i++){var next=i+1,last=next===l;if(last){obj[parts[i]]=val}else{if(obj[parts[i]]&&utils.getFunctionName(obj[parts[i]].constructor)==="Object"){obj=obj[parts[i]]}else if(obj[parts[i]]&&obj[parts[i]]instanceof Embedded){obj=obj[parts[i]]}else if(obj[parts[i]]&&obj[parts[i]].$isSingleNested){obj=obj[parts[i]]}else if(obj[parts[i]]&&Array.isArray(obj[parts[i]])){obj=obj[parts[i]]}else{obj=obj[parts[i]]={}}}}};Document.prototype.getValue=function(path){return utils.getValue(path,this._doc)};Document.prototype.setValue=function(path,val){utils.setValue(path,val,this._doc);return this};Document.prototype.get=function(path,type){var adhoc;if(type){adhoc=Schema.interpretAsType(path,type,this.schema.options)}var schema=this.$__path(path)||this.schema.virtualpath(path),pieces=path.split("."),obj=this._doc;for(var i=0,l=pieces.length;i<l;i++){obj=obj===null||obj===void 0?undefined:obj[pieces[i]]}if(adhoc){obj=adhoc.cast(obj)}if(schema&&!this.populated(path)){obj=schema.applyGetters(obj,this)}return obj};Document.prototype.$__path=function(path){var adhocs=this.$__.adhocPaths,adhocType=adhocs&&adhocs[path];if(adhocType){return adhocType}return this.schema.path(path)};Document.prototype.markModified=function(path){this.$__.activePaths.modify(path)};Document.prototype.modifiedPaths=function(){var directModifiedPaths=Object.keys(this.$__.activePaths.states.modify);return directModifiedPaths.reduce(function(list,path){var parts=path.split(".");return list.concat(parts.reduce(function(chains,part,i){return chains.concat(parts.slice(0,i).concat(part).join("."))},[]))},[])};Document.prototype.isModified=function(path){return path?!!~this.modifiedPaths().indexOf(path):this.$__.activePaths.some("modify")};Document.prototype.$isDefault=function(path){return path in this.$__.activePaths.states.default};Document.prototype.isDirectModified=function(path){return path in this.$__.activePaths.states.modify};Document.prototype.isInit=function(path){return path in this.$__.activePaths.states.init};Document.prototype.isSelected=function isSelected(path){if(this.$__.selected){if(path==="_id"){return this.$__.selected._id!==0}var paths=Object.keys(this.$__.selected),i=paths.length,inclusive=false,cur;if(i===1&&paths[0]==="_id"){return this.$__.selected._id===0}while(i--){cur=paths[i];if(cur==="_id"){continue}inclusive=!!this.$__.selected[cur];break}if(path in this.$__.selected){return inclusive}i=paths.length;var pathDot=path+".";while(i--){cur=paths[i];if(cur==="_id"){continue}if(cur.indexOf(pathDot)===0){return inclusive}if(pathDot.indexOf(cur+".")===0){return inclusive}}return!inclusive}return true};Document.prototype.validate=function(options,callback){var _this=this;var Promise=PromiseProvider.get();if(typeof options==="function"){callback=options;options=null}if(options&&options.__noPromise){this.$__validate(callback);return}return new Promise.ES6(function(resolve,reject){_this.$__validate(function(error){callback&&callback(error);if(error){reject(error);return}resolve()})})};Document.prototype.$__validate=function(callback){var _this=this;var _complete=function(){var err=_this.$__.validationError;_this.$__.validationError=undefined;_this.emit("validate",_this);if(err){for(var key in err.errors){if(!_this.__parent&&err.errors[key]instanceof MongooseError.CastError){_this.invalidate(key,err.errors[key])}}return err}};var paths=Object.keys(this.$__.activePaths.states.require).filter(function(path){if(!_this.isSelected(path)&&!_this.isModified(path)){return false}return true});paths=paths.concat(Object.keys(this.$__.activePaths.states.init));paths=paths.concat(Object.keys(this.$__.activePaths.states.modify));paths=paths.concat(Object.keys(this.$__.activePaths.states.default));if(paths.length===0){process.nextTick(function(){var err=_complete();if(err){callback(err);return}callback()})}var validating={},total=0;for(var i=0;i<paths.length;++i){var path=paths[i];var val=_this.getValue(path);if(val&&val.isMongooseArray&&!Buffer.isBuffer(val)&&!val.isMongooseDocumentArray){var numElements=val.length;for(var j=0;j<numElements;++j){paths.push(path+"."+j)}}}var complete=function(){var err=_complete();if(err){callback(err);return}callback()};var validatePath=function(path){if(validating[path]){return}validating[path]=true;total++;process.nextTick(function(){var p=_this.schema.path(path);if(!p){return--total||complete()}if(!_this.$isValid(path)){--total||complete();return}var val=_this.getValue(path);p.doValidate(val,function(err){if(err){_this.invalidate(path,err,undefined,true)}--total||complete()},_this)})};paths.forEach(validatePath)};Document.prototype.validateSync=function(pathsToValidate){var _this=this;if(typeof pathsToValidate==="string"){pathsToValidate=pathsToValidate.split(" ")}var paths=Object.keys(this.$__.activePaths.states.require).filter(function(path){if(!_this.isSelected(path)&&!_this.isModified(path)){return false}return true});paths=paths.concat(Object.keys(this.$__.activePaths.states.init));paths=paths.concat(Object.keys(this.$__.activePaths.states.modify));paths=paths.concat(Object.keys(this.$__.activePaths.states.default));if(pathsToValidate&&pathsToValidate.length){var tmp=[];for(var i=0;i<paths.length;++i){if(pathsToValidate.indexOf(paths[i])!==-1){tmp.push(paths[i])}}paths=tmp}var validating={};paths.forEach(function(path){if(validating[path]){return}validating[path]=true;var p=_this.schema.path(path);if(!p){return}if(!_this.$isValid(path)){return}var val=_this.getValue(path);var err=p.doValidateSync(val,_this);if(err){_this.invalidate(path,err,undefined,true)}});var err=_this.$__.validationError;_this.$__.validationError=undefined;_this.emit("validate",_this);if(err){for(var key in err.errors){if(err.errors[key]instanceof MongooseError.CastError){_this.invalidate(key,err.errors[key])}}}return err};Document.prototype.invalidate=function(path,err,val){if(!this.$__.validationError){this.$__.validationError=new ValidationError(this)}if(this.$__.validationError.errors[path]){return}if(!err||typeof err==="string"){err=new ValidatorError({path:path,message:err,type:"user defined",value:val})}if(this.$__.validationError===err){return}this.$__.validationError.errors[path]=err};Document.prototype.$markValid=function(path){if(!this.$__.validationError||!this.$__.validationError.errors[path]){return}delete this.$__.validationError.errors[path];if(Object.keys(this.$__.validationError.errors).length===0){this.$__.validationError=null}};Document.prototype.$isValid=function(path){return!this.$__.validationError||!this.$__.validationError.errors[path]};Document.prototype.$__reset=function reset(){var _this=this;DocumentArray||(DocumentArray=require("./types/documentarray"));this.$__.activePaths.map("init","modify",function(i){return _this.getValue(i)}).filter(function(val){return val&&val instanceof Array&&val.isMongooseDocumentArray&&val.length}).forEach(function(array){var i=array.length;while(i--){var doc=array[i];if(!doc){continue}doc.$__reset()}});this.$__dirty().forEach(function(dirt){var type=dirt.value;if(type&&type._atomics){type._atomics={}}});this.$__.activePaths.clear("modify");this.$__.activePaths.clear("default");this.$__.validationError=undefined;this.errors=undefined;_this=this;this.schema.requiredPaths().forEach(function(path){_this.$__.activePaths.require(path)});return this};Document.prototype.$__dirty=function(){var _this=this;var all=this.$__.activePaths.map("modify",function(path){return{path:path,value:_this.getValue(path),schema:_this.$__path(path)}});all=all.concat(this.$__.activePaths.map("default",function(path){if(path==="_id"||!_this.getValue(path)){return}return{path:path,value:_this.getValue(path),schema:_this.$__path(path)}}));all.sort(function(a,b){return a.path<b.path?-1:a.path>b.path?1:0});var minimal=[],lastPath,top;all.forEach(function(item){if(!item){return}if(item.path.indexOf(lastPath)!==0){lastPath=item.path+".";minimal.push(item);top=item}else{if(top.value&&top.value._atomics&&top.value.hasAtomics()){top.value._atomics={};top.value._atomics.$set=top.value}}});top=lastPath=null;return minimal};function compile(tree,proto,prefix,options){var keys=Object.keys(tree),i=keys.length,limb,key;while(i--){key=keys[i];limb=tree[key];defineKey(key,utils.getFunctionName(limb.constructor)==="Object"&&Object.keys(limb).length&&(!limb[options.typeKey]||options.typeKey==="type"&&limb.type.type)?limb:null,proto,prefix,keys,options)}}function getOwnPropertyDescriptors(object){var result={};Object.getOwnPropertyNames(object).forEach(function(key){result[key]=Object.getOwnPropertyDescriptor(object,key);result[key].enumerable=true});return result}function defineKey(prop,subprops,prototype,prefix,keys,options){var path=(prefix?prefix+".":"")+prop;prefix=prefix||"";if(subprops){Object.defineProperty(prototype,prop,{enumerable:true,configurable:true,get:function(){var _this=this;if(!this.$__.getters){this.$__.getters={}}if(!this.$__.getters[path]){var nested=Object.create(Object.getPrototypeOf(this),getOwnPropertyDescriptors(this));if(!prefix){nested.$__.scope=this}var i=0,len=keys.length;for(;i<len;++i){Object.defineProperty(nested,keys[i],{enumerable:false,writable:true,configurable:true,value:undefined})}Object.defineProperty(nested,"toObject",{enumerable:true,configurable:true,writable:false,value:function(){return _this.get(path)}});Object.defineProperty(nested,"toJSON",{enumerable:true,configurable:true,writable:false,value:function(){return _this.get(path)}});Object.defineProperty(nested,"$__isNested",{enumerable:true,configurable:true,writable:false,value:true});compile(subprops,nested,path,options);this.$__.getters[path]=nested}return this.$__.getters[path]},set:function(v){if(v instanceof Document){v=v.toObject()}return(this.$__.scope||this).set(path,v)}})}else{Object.defineProperty(prototype,prop,{enumerable:true,configurable:true,get:function(){return this.get.call(this.$__.scope||this,path)},set:function(v){return this.set.call(this.$__.scope||this,path,v)}})}}Document.prototype.$__setSchema=function(schema){compile(schema.tree,this,undefined,schema.options);this.schema=schema};Document.prototype.$__getArrayPathsToValidate=function(){DocumentArray||(DocumentArray=require("./types/documentarray"));return this.$__.activePaths.map("init","modify",function(i){return this.getValue(i)}.bind(this)).filter(function(val){return val&&val instanceof Array&&val.isMongooseDocumentArray&&val.length}).reduce(function(seed,array){return seed.concat(array)},[]).filter(function(doc){return doc})};Document.prototype.$__getAllSubdocs=function(){DocumentArray||(DocumentArray=require("./types/documentarray"));Embedded=Embedded||require("./types/embedded");function docReducer(seed,path){var val=this[path];if(val instanceof Embedded){seed.push(val)}if(val&&val.$isSingleNested){seed=Object.keys(val._doc).reduce(docReducer.bind(val._doc),seed);seed.push(val)}if(val&&val.isMongooseDocumentArray){val.forEach(function _docReduce(doc){if(!doc||!doc._doc){return}if(doc instanceof Embedded){seed.push(doc)}seed=Object.keys(doc._doc).reduce(docReducer.bind(doc._doc),seed)})}else if(val instanceof Document&&val.$__isNested){val=val.toObject();if(val){seed=Object.keys(val).reduce(docReducer.bind(val),seed)}}return seed}var subDocs=Object.keys(this._doc).reduce(docReducer.bind(this),[]);return subDocs};Document.prototype.$__registerHooksFromSchema=function(){Embedded=Embedded||require("./types/embedded");var Promise=PromiseProvider.get();var _this=this;var q=_this.schema&&_this.schema.callQueue;if(!q.length){return _this}var toWrap=q.reduce(function(seed,pair){if(pair[0]!=="pre"&&pair[0]!=="post"&&pair[0]!=="on"){_this[pair[0]].apply(_this,pair[1]);return seed}var args=[].slice.call(pair[1]);var pointCut=pair[0]==="on"?"post":args[0];if(!(pointCut in seed)){seed[pointCut]={post:[],pre:[]}}if(pair[0]==="post"){seed[pointCut].post.push(args)}else if(pair[0]==="on"){seed[pointCut].push(args)}else{seed[pointCut].pre.push(args)}return seed},{post:[]});toWrap.post.forEach(function(args){_this.on.apply(_this,args)});delete toWrap.post;if(toWrap.init&&_this instanceof Embedded){if(toWrap.init.pre){toWrap.init.pre.forEach(function(args){_this.pre.apply(_this,args)})}if(toWrap.init.post){toWrap.init.post.forEach(function(args){_this.post.apply(_this,args)})}delete toWrap.init}else if(toWrap.set){if(toWrap.set.pre){toWrap.set.pre.forEach(function(args){_this.pre.apply(_this,args)})}if(toWrap.set.post){toWrap.set.post.forEach(function(args){_this.post.apply(_this,args)})}delete toWrap.set}Object.keys(toWrap).forEach(function(pointCut){var newName="$__original_"+pointCut;if(!_this[pointCut]){return}_this[newName]=_this[pointCut];_this[pointCut]=function wrappedPointCut(){var args=[].slice.call(arguments);var lastArg=args.pop();var fn;return new Promise.ES6(function(resolve,reject){if(lastArg&&typeof lastArg!=="function"){args.push(lastArg)}else{fn=lastArg}args.push(function(error,result){if(error){_this.$__handleReject(error);fn&&fn(error);reject(error);return}fn&&fn.apply(null,[null].concat(Array.prototype.slice.call(arguments,1)));resolve(result)});_this[newName].apply(_this,args)})};toWrap[pointCut].pre.forEach(function(args){args[0]=newName;_this.pre.apply(_this,args)});toWrap[pointCut].post.forEach(function(args){args[0]=newName;_this.post.apply(_this,args)})});return _this};Document.prototype.$__handleReject=function handleReject(err){if(this.listeners("error").length){this.emit("error",err)}else if(this.constructor.listeners&&this.constructor.listeners("error").length){this.constructor.emit("error",err)}else if(this.listeners&&this.listeners("error").length){this.emit("error",err)}};Document.prototype.$toObject=function(options,json){var defaultOptions={transform:true,json:json};if(options&&options.depopulate&&!options._skipDepopulateTopLevel&&this.$__.wasPopulated){return clone(this._id,options)}if(options&&options._skipDepopulateTopLevel){options._skipDepopulateTopLevel=false}if(!(options&&utils.getFunctionName(options.constructor)==="Object")||options&&options._useSchemaOptions){if(json){options=this.schema.options.toJSON?clone(this.schema.options.toJSON):{};options.json=true;options._useSchemaOptions=true}else{options=this.schema.options.toObject?clone(this.schema.options.toObject):{};options.json=false;options._useSchemaOptions=true}}for(var key in defaultOptions){if(options[key]===undefined){options[key]=defaultOptions[key]}}"minimize"in options||(options.minimize=this.schema.options.minimize);var originalTransform=options.transform;var ret=clone(this._doc,options)||{};if(options.getters){applyGetters(this,ret,"paths",options);if(options.minimize){ret=minimize(ret)||{}}}if(options.virtuals||options.getters&&options.virtuals!==false){applyGetters(this,ret,"virtuals",options)}if(options.versionKey===false&&this.schema.options.versionKey){delete ret[this.schema.options.versionKey]}var transform=options.transform;if(transform===true||this.schema.options.toObject&&transform){var opts=options.json?this.schema.options.toJSON:this.schema.options.toObject;if(opts){transform=typeof options.transform==="function"?options.transform:opts.transform}}else{options.transform=originalTransform}if(typeof transform==="function"){var xformed=transform(this,ret,options);if(typeof xformed!=="undefined"){ret=xformed}}return ret};Document.prototype.toObject=function(options){return this.$toObject(options)};function minimize(obj){var keys=Object.keys(obj),i=keys.length,hasKeys,key,val;while(i--){key=keys[i];val=obj[key];if(utils.isObject(val)){obj[key]=minimize(val)}if(undefined===obj[key]){delete obj[key];continue}hasKeys=true}return hasKeys?obj:undefined}function applyGetters(self,json,type,options){var schema=self.schema,paths=Object.keys(schema[type]),i=paths.length,path;while(i--){path=paths[i];var parts=path.split("."),plen=parts.length,last=plen-1,branch=json,part;for(var ii=0;ii<plen;++ii){part=parts[ii];if(ii===last){branch[part]=clone(self.get(path),options)}else{branch=branch[part]||(branch[part]={})}}}return json}Document.prototype.toJSON=function(options){return this.$toObject(options,true)};Document.prototype.inspect=function(options){
var opts=options&&utils.getFunctionName(options.constructor)==="Object"?options:{};opts.minimize=false;opts.retainKeyOrder=true;return this.toObject(opts)};Document.prototype.toString=function(){return inspect(this.inspect())};Document.prototype.equals=function(doc){var tid=this.get("_id");var docid=doc.get?doc.get("_id"):doc;if(!tid&&!docid){return deepEqual(this,doc)}return tid&&tid.equals?tid.equals(docid):tid===docid};Document.prototype.populate=function populate(){if(arguments.length===0){return this}var pop=this.$__.populate||(this.$__.populate={});var args=utils.args(arguments);var fn;if(typeof args[args.length-1]==="function"){fn=args.pop()}if(args.length){var res=utils.populate.apply(null,args);for(var i=0;i<res.length;++i){pop[res[i].path]=res[i]}}if(fn){var paths=utils.object.vals(pop);this.$__.populate=undefined;paths.__noPromise=true;this.constructor.populate(this,paths,fn)}return this};Document.prototype.execPopulate=function(){var Promise=PromiseProvider.get();var _this=this;return new Promise.ES6(function(resolve,reject){_this.populate(function(error,res){if(error){reject(error)}else{resolve(res)}})})};Document.prototype.populated=function(path,val,options){if(val===null||val===void 0){if(!this.$__.populated){return undefined}var v=this.$__.populated[path];if(v){return v.value}return undefined}if(val===true){if(!this.$__.populated){return undefined}return this.$__.populated[path]}this.$__.populated||(this.$__.populated={});this.$__.populated[path]={value:val,options:options};return val};Document.prototype.depopulate=function(path){var populatedIds=this.populated(path);if(!populatedIds){return}delete this.$__.populated[path];this.set(path,populatedIds)};Document.prototype.$__fullPath=function(path){return path||""};Document.ValidationError=ValidationError;module.exports=exports=Document}).call(this,require("_process"),require("buffer").Buffer)},{"./error":11,"./error/objectExpected":16,"./error/strict":18,"./internal":22,"./promise_provider":24,"./schema":25,"./schema/mixed":33,"./schematype":38,"./types/array":40,"./types/documentarray":42,"./types/embedded":43,"./utils":47,_process:96,buffer:91,events:94,"hooks-fixed":68,util:98}],5:[function(require,module,exports){"use strict";var Document=require("./document.js");var BrowserDocument=require("./browserDocument.js");module.exports=function(){if(typeof window!=="undefined"&&typeof document!=="undefined"&&document===window.document){return BrowserDocument}return Document}},{"./browserDocument.js":2,"./document.js":4}],6:[function(require,module,exports){module.exports=function(){}},{}],7:[function(require,module,exports){var Binary=require("bson").Binary;module.exports=exports=Binary},{bson:52}],8:[function(require,module,exports){exports.Binary=require("./binary");exports.ObjectId=require("./objectid");exports.ReadPreference=require("./ReadPreference")},{"./ReadPreference":6,"./binary":7,"./objectid":9}],9:[function(require,module,exports){var ObjectId=require("bson").ObjectID;module.exports=exports=ObjectId},{bson:52}],10:[function(require,module,exports){(function(global){var driver;if(typeof window==="undefined"){driver=require(global.MONGOOSE_DRIVER_PATH||"./node-mongodb-native")}else{driver=require("./browser")}module.exports=driver}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./browser":8}],11:[function(require,module,exports){function MongooseError(msg){Error.call(this);if(Error.captureStackTrace){Error.captureStackTrace(this)}else{this.stack=(new Error).stack}this.message=msg;this.name="MongooseError"}MongooseError.prototype=Object.create(Error.prototype);MongooseError.prototype.constructor=Error;module.exports=exports=MongooseError;MongooseError.messages=require("./error/messages");MongooseError.Messages=MongooseError.messages;MongooseError.CastError=require("./error/cast");MongooseError.ValidationError=require("./error/validation");MongooseError.ValidatorError=require("./error/validator");MongooseError.VersionError=require("./error/version");MongooseError.OverwriteModelError=require("./error/overwriteModel");MongooseError.MissingSchemaError=require("./error/missingSchema");MongooseError.DivergentArrayError=require("./error/divergentArray")},{"./error/cast":12,"./error/divergentArray":13,"./error/messages":14,"./error/missingSchema":15,"./error/overwriteModel":17,"./error/validation":19,"./error/validator":20,"./error/version":21}],12:[function(require,module,exports){var MongooseError=require("../error.js");function CastError(type,value,path,reason){MongooseError.call(this,"Cast to "+type+' failed for value "'+value+'" at path "'+path+'"');if(Error.captureStackTrace){Error.captureStackTrace(this)}else{this.stack=(new Error).stack}this.name="CastError";this.kind=type;this.value=value;this.path=path;this.reason=reason}CastError.prototype=Object.create(MongooseError.prototype);CastError.prototype.constructor=MongooseError;module.exports=CastError},{"../error.js":11}],13:[function(require,module,exports){var MongooseError=require("../error.js");function DivergentArrayError(paths){var msg="For your own good, using `document.save()` to update an array "+"which was selected using an $elemMatch projection OR "+"populated using skip, limit, query conditions, or exclusion of "+"the _id field when the operation results in a $pop or $set of "+"the entire array is not supported. The following "+"path(s) would have been modified unsafely:\n"+" "+paths.join("\n ")+"\n"+"Use Model.update() to update these arrays instead.";MongooseError.call(this,msg);Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee);this.name="DivergentArrayError"}DivergentArrayError.prototype=Object.create(MongooseError.prototype);DivergentArrayError.prototype.constructor=MongooseError;module.exports=DivergentArrayError},{"../error.js":11}],14:[function(require,module,exports){var msg=module.exports=exports={};msg.general={};msg.general.default="Validator failed for path `{PATH}` with value `{VALUE}`";msg.general.required="Path `{PATH}` is required.";msg.Number={};msg.Number.min="Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).";msg.Number.max="Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).";msg.Date={};msg.Date.min="Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).";msg.Date.max="Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).";msg.String={};msg.String.enum="`{VALUE}` is not a valid enum value for path `{PATH}`.";msg.String.match="Path `{PATH}` is invalid ({VALUE}).";msg.String.minlength="Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).";msg.String.maxlength="Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH})."},{}],15:[function(require,module,exports){var MongooseError=require("../error.js");function MissingSchemaError(name){var msg="Schema hasn't been registered for model \""+name+'".\n'+"Use mongoose.model(name, schema)";MongooseError.call(this,msg);Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee);this.name="MissingSchemaError"}MissingSchemaError.prototype=Object.create(MongooseError.prototype);MissingSchemaError.prototype.constructor=MongooseError;module.exports=MissingSchemaError},{"../error.js":11}],16:[function(require,module,exports){var MongooseError=require("../error.js");function ObjectExpectedError(path,val){MongooseError.call(this,"Tried to set nested object field `"+path+"` to primitive value `"+val+"` and strict mode is set to throw.");if(Error.captureStackTrace){Error.captureStackTrace(this)}else{this.stack=(new Error).stack}this.name="ObjectExpectedError";this.path=path}ObjectExpectedError.prototype=Object.create(MongooseError.prototype);ObjectExpectedError.prototype.constructor=MongooseError;module.exports=ObjectExpectedError},{"../error.js":11}],17:[function(require,module,exports){var MongooseError=require("../error.js");function OverwriteModelError(name){MongooseError.call(this,"Cannot overwrite `"+name+"` model once compiled.");Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee);this.name="OverwriteModelError"}OverwriteModelError.prototype=Object.create(MongooseError.prototype);OverwriteModelError.prototype.constructor=MongooseError;module.exports=OverwriteModelError},{"../error.js":11}],18:[function(require,module,exports){var MongooseError=require("../error.js");function StrictModeError(path){MongooseError.call(this,"Field `"+path+"` is not in schema and strict "+"mode is set to throw.");if(Error.captureStackTrace){Error.captureStackTrace(this)}else{this.stack=(new Error).stack}this.name="StrictModeError";this.path=path}StrictModeError.prototype=Object.create(MongooseError.prototype);StrictModeError.prototype.constructor=MongooseError;module.exports=StrictModeError},{"../error.js":11}],19:[function(require,module,exports){var MongooseError=require("../error.js");function ValidationError(instance){if(instance&&instance.constructor.name==="model"){MongooseError.call(this,instance.constructor.modelName+" validation failed")}else{MongooseError.call(this,"Validation failed")}if(Error.captureStackTrace){Error.captureStackTrace(this)}else{this.stack=(new Error).stack}this.name="ValidationError";this.errors={};if(instance){instance.errors=this.errors}}ValidationError.prototype=Object.create(MongooseError.prototype);ValidationError.prototype.constructor=MongooseError;ValidationError.prototype.toString=function(){var ret=this.name+": ";var msgs=[];Object.keys(this.errors).forEach(function(key){if(this===this.errors[key]){return}msgs.push(String(this.errors[key]))},this);return ret+msgs.join(", ")};module.exports=exports=ValidationError},{"../error.js":11}],20:[function(require,module,exports){var MongooseError=require("../error.js");var errorMessages=MongooseError.messages;function ValidatorError(properties){var msg=properties.message;if(!msg){msg=errorMessages.general.default}this.properties=properties;var message=this.formatMessage(msg,properties);MongooseError.call(this,message);if(Error.captureStackTrace){Error.captureStackTrace(this)}else{this.stack=(new Error).stack}this.name="ValidatorError";this.kind=properties.type;this.path=properties.path;this.value=properties.value}ValidatorError.prototype=Object.create(MongooseError.prototype);ValidatorError.prototype.constructor=MongooseError;ValidatorError.prototype.formatMessage=function(msg,properties){var propertyNames=Object.keys(properties);for(var i=0;i<propertyNames.length;++i){var propertyName=propertyNames[i];if(propertyName==="message"){continue}msg=msg.replace("{"+propertyName.toUpperCase()+"}",properties[propertyName])}return msg};ValidatorError.prototype.toString=function(){return this.message};module.exports=ValidatorError},{"../error.js":11}],21:[function(require,module,exports){var MongooseError=require("../error.js");function VersionError(){MongooseError.call(this,"No matching document found.");Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee);this.name="VersionError"}VersionError.prototype=Object.create(MongooseError.prototype);VersionError.prototype.constructor=MongooseError;module.exports=VersionError},{"../error.js":11}],22:[function(require,module,exports){var StateMachine=require("./statemachine");var ActiveRoster=StateMachine.ctor("require","modify","init","default","ignore");module.exports=exports=InternalCache;function InternalCache(){this.strictMode=undefined;this.selected=undefined;this.shardval=undefined;this.saveError=undefined;this.validationError=undefined;this.adhocPaths=undefined;this.removing=undefined;this.inserting=undefined;this.version=undefined;this.getters={};this._id=undefined;this.populate=undefined;this.populated=undefined;this.wasPopulated=false;this.scope=undefined;this.activePaths=new ActiveRoster;this.ownerDocument=undefined;this.fullPath=undefined}},{"./statemachine":39}],23:[function(require,module,exports){var MPromise=require("mpromise");var util=require("util");function Promise(fn){MPromise.call(this,fn)}Promise.ES6=function(resolver){var promise=new Promise;resolver(function(){promise.complete.apply(promise,arguments)},function(e){promise.error(e)});return promise};Promise.prototype=Object.create(MPromise.prototype,{constructor:{value:Promise,enumerable:false,writable:true,configurable:true}});Promise.SUCCESS="complete";Promise.FAILURE="err";Promise.prototype.error=function(err){if(!(err instanceof Error)){if(err instanceof Object){err=util.inspect(err)}err=new Error(err)}return this.reject(err)};Promise.prototype.resolve=function(err){if(err)return this.error(err);return this.fulfill.apply(this,Array.prototype.slice.call(arguments,1))};Promise.prototype.addBack=Promise.prototype.onResolve;Promise.prototype.complete=MPromise.prototype.fulfill;Promise.prototype.addCallback=Promise.prototype.onFulfill;Promise.prototype.addErrback=Promise.prototype.onReject;module.exports=Promise},{mpromise:72,util:98}],24:[function(require,module,exports){var MPromise=require("./promise");var Promise={_promise:MPromise};Promise.get=function(){return Promise._promise};Promise.set=function(lib){if(lib===MPromise){return Promise.reset()}Promise._promise=require("./ES6Promise");Promise._promise.use(lib);require("mquery").Promise=Promise._promise.ES6};Promise.reset=function(){Promise._promise=MPromise};module.exports=Promise},{"./ES6Promise":1,"./promise":23,mquery:77}],25:[function(require,module,exports){(function(Buffer){var readPref=require("./drivers").ReadPreference;var EventEmitter=require("events").EventEmitter;var VirtualType=require("./virtualtype");var utils=require("./utils");var MongooseTypes;var Kareem=require("kareem");var async=require("async");var IS_QUERY_HOOK={count:true,find:true,findOne:true,findOneAndUpdate:true,findOneAndRemove:true,update:true};function Schema(obj,options){if(!(this instanceof Schema)){return new Schema(obj,options)}this.paths={};this.subpaths={};this.virtuals={};this.singleNestedPaths={};this.nested={};this.inherits={};this.callQueue=[];this._indexes=[];this.methods={};this.statics={};this.tree={};this._requiredpaths=undefined;this.discriminatorMapping=undefined;this._indexedpaths=undefined;this.s={hooks:new Kareem,queryHooks:IS_QUERY_HOOK};this.options=this.defaultOptions(options);if(obj){this.add(obj)}var _idSubDoc=obj&&obj._id&&utils.isObject(obj._id);var auto_id=!this.paths["_id"]&&(!this.options.noId&&this.options._id)&&!_idSubDoc;if(auto_id){obj={_id:{auto:true}};obj._id[this.options.typeKey]=Schema.ObjectId;this.add(obj)}var autoid=!this.paths["id"]&&(!this.options.noVirtualId&&this.options.id);if(autoid){this.virtual("id").get(idGetter)}for(var i=0;i<this._defaultMiddleware.length;++i){var m=this._defaultMiddleware[i];this[m.kind](m.hook,!!m.isAsync,m.fn)}var timestamps=this.options.timestamps;if(timestamps){var createdAt=timestamps.createdAt||"createdAt",updatedAt=timestamps.updatedAt||"updatedAt",schemaAdditions={};schemaAdditions[updatedAt]=Date;if(!this.paths[createdAt]){schemaAdditions[createdAt]=Date}this.add(schemaAdditions);this.pre("save",function(next){var defaultTimestamp=new Date;if(!this[createdAt]){this[createdAt]=auto_id?this._id.getTimestamp():defaultTimestamp}this[updatedAt]=this.isNew?this[createdAt]:defaultTimestamp;next()});var genUpdates=function(){var now=new Date;var updates={$set:{},$setOnInsert:{}};updates.$set[updatedAt]=now;updates.$setOnInsert[createdAt]=now;return updates};this.pre("findOneAndUpdate",function(next){this.findOneAndUpdate({},genUpdates());next()});this.pre("update",function(next){this.update({},genUpdates());next()})}}function idGetter(){if(this.$__._id){return this.$__._id}this.$__._id=this._id==null?null:String(this._id);return this.$__._id}Schema.prototype=Object.create(EventEmitter.prototype);Schema.prototype.constructor=Schema;Schema.prototype.instanceOfSchema=true;Object.defineProperty(Schema.prototype,"_defaultMiddleware",{configurable:false,enumerable:false,writable:false,value:[{kind:"pre",hook:"save",fn:function(next,options){if(this.ownerDocument){return next()}var hasValidateBeforeSaveOption=options&&typeof options==="object"&&"validateBeforeSave"in options;var shouldValidate;if(hasValidateBeforeSaveOption){shouldValidate=!!options.validateBeforeSave}else{shouldValidate=this.schema.options.validateBeforeSave}if(shouldValidate){if(this.$__original_validate){this.$__original_validate({__noPromise:true},function(error){next(error)})}else{this.validate({__noPromise:true},function(error){next(error)})}}else{next()}}},{kind:"pre",hook:"save",isAsync:true,fn:function(next,done){var subdocs=this.$__getAllSubdocs();if(!subdocs.length||this.$__preSavingFromParent){done();next();return}async.each(subdocs,function(subdoc,cb){subdoc.$__preSavingFromParent=true;subdoc.save(function(err){cb(err)})},function(error){for(var i=0;i<subdocs.length;++i){delete subdocs[i].$__preSavingFromParent}if(error){done(error);return}next();done()})}}]});Schema.prototype.paths;Schema.prototype.tree;Schema.prototype.defaultOptions=function(options){if(options&&options.safe===false){options.safe={w:0}}if(options&&options.safe&&options.safe.w===0){options.versionKey=false}options=utils.options({strict:true,bufferCommands:true,capped:false,versionKey:"__v",discriminatorKey:"__t",minimize:true,autoIndex:null,shardKey:null,read:null,validateBeforeSave:true,noId:false,_id:true,noVirtualId:false,id:true,typeKey:"type"},options);if(options.read){options.read=readPref(options.read)}return options};Schema.prototype.add=function add(obj,prefix){prefix=prefix||"";var keys=Object.keys(obj);for(var i=0;i<keys.length;++i){var key=keys[i];if(obj[key]==null){throw new TypeError("Invalid value for schema path `"+prefix+key+"`")}if(Array.isArray(obj[key])&&obj[key].length===1&&obj[key][0]==null){throw new TypeError("Invalid value for schema Array path `"+prefix+key+"`")}if(utils.isObject(obj[key])&&(!obj[key].constructor||utils.getFunctionName(obj[key].constructor)==="Object")&&(!obj[key][this.options.typeKey]||this.options.typeKey==="type"&&obj[key].type.type)){if(Object.keys(obj[key]).length){this.nested[prefix+key]=true;this.add(obj[key],prefix+key+".")}else{this.path(prefix+key,obj[key])}}else{this.path(prefix+key,obj[key])}}};Schema.reserved=Object.create(null);var reserved=Schema.reserved;reserved.emit=reserved.on=reserved.once=reserved.listeners=reserved.removeListener=reserved.collection=reserved.db=reserved.errors=reserved.init=reserved.isModified=reserved.isNew=reserved.get=reserved.modelName=reserved.save=reserved.schema=reserved.set=reserved.toObject=reserved.validate=reserved._pres=reserved._posts=1;var warnings={};warnings.increment="`increment` should not be used as a schema path name "+"unless you have disabled versioning.";Schema.prototype.path=function(path,obj){if(obj===undefined){if(this.paths[path]){return this.paths[path]}if(this.subpaths[path]){return this.subpaths[path]}if(this.singleNestedPaths[path]){return this.singleNestedPaths[path]}return/\.\d+\.?.*$/.test(path)?getPositionalPath(this,path):undefined}if(reserved[path]){throw new Error("`"+path+"` may not be used as a schema pathname")}if(warnings[path]){console.log("WARN: "+warnings[path])}var subpaths=path.split(/\./),last=subpaths.pop(),branch=this.tree;subpaths.forEach(function(sub,i){if(!branch[sub]){branch[sub]={}}if(typeof branch[sub]!=="object"){var msg="Cannot set nested path `"+path+"`. "+"Parent path `"+subpaths.slice(0,i).concat([sub]).join(".")+"` already set to type "+branch[sub].name+".";throw new Error(msg)}branch=branch[sub]});branch[last]=utils.clone(obj);this.paths[path]=Schema.interpretAsType(path,obj,this.options);if(this.paths[path].$isSingleNested){for(var key in this.paths[path].schema.paths){this.singleNestedPaths[path+"."+key]=this.paths[path].schema.paths[key]}for(key in this.paths[path].schema.singleNestedPaths){this.singleNestedPaths[path+"."+key]=this.paths[path].schema.singleNestedPaths[key]}}return this};Schema.interpretAsType=function(path,obj,options){if(obj.constructor){var constructorName=utils.getFunctionName(obj.constructor);if(constructorName!=="Object"){var oldObj=obj;obj={};obj[options.typeKey]=oldObj}}var type=obj[options.typeKey]&&(options.typeKey!=="type"||!obj.type.type)?obj[options.typeKey]:{};if(utils.getFunctionName(type.constructor)==="Object"||type==="mixed"){return new MongooseTypes.Mixed(path,obj)}if(Array.isArray(type)||Array===type||type==="array"){var cast=Array===type||type==="array"?obj.cast:type[0];if(cast&&cast.instanceOfSchema){return new MongooseTypes.DocumentArray(path,cast,obj)}if(typeof cast==="string"){cast=MongooseTypes[cast.charAt(0).toUpperCase()+cast.substring(1)]}else if(cast&&(!cast[options.typeKey]||options.typeKey==="type"&&cast.type.type)&&utils.getFunctionName(cast.constructor)==="Object"&&Object.keys(cast).length){var childSchemaOptions={minimize:options.minimize};if(options.typeKey){childSchemaOptions.typeKey=options.typeKey}var childSchema=new Schema(cast,childSchemaOptions);return new MongooseTypes.DocumentArray(path,childSchema,obj)}return new MongooseTypes.Array(path,cast||MongooseTypes.Mixed,obj)}if(type&&type.instanceOfSchema){return new MongooseTypes.Embedded(type,path,obj)}var name;if(Buffer.isBuffer(type)){name="Buffer"}else{name=typeof type==="string"?type:type.schemaName||utils.getFunctionName(type)}if(name){name=name.charAt(0).toUpperCase()+name.substring(1)}if(undefined==MongooseTypes[name]){throw new TypeError("Undefined type `"+name+"` at `"+path+"`\n Did you try nesting Schemas? "+"You can only nest using refs or arrays.")}return new MongooseTypes[name](path,obj)};Schema.prototype.eachPath=function(fn){var keys=Object.keys(this.paths),len=keys.length;for(var i=0;i<len;++i){fn(keys[i],this.paths[keys[i]])}return this};Schema.prototype.requiredPaths=function requiredPaths(invalidate){if(this._requiredpaths&&!invalidate){return this._requiredpaths}var paths=Object.keys(this.paths),i=paths.length,ret=[];while(i--){var path=paths[i];if(this.paths[path].isRequired){ret.push(path)}}this._requiredpaths=ret;return this._requiredpaths};Schema.prototype.indexedPaths=function indexedPaths(){if(this._indexedpaths){return this._indexedpaths}this._indexedpaths=this.indexes();return this._indexedpaths};Schema.prototype.pathType=function(path){if(path in this.paths){return"real"}if(path in this.virtuals){return"virtual"}if(path in this.nested){return"nested"}if(path in this.subpaths){return"real"}if(path in this.singleNestedPaths){return"real"}if(/\.\d+\.|\.\d+$/.test(path)){return getPositionalPathType(this,path)}return"adhocOrUndefined"};Schema.prototype.hasMixedParent=function(path){var subpaths=path.split(/\./g);path="";for(var i=0;i<subpaths.length;++i){path=i>0?path+"."+subpaths[i]:subpaths[i];if(path in this.paths&&this.paths[path]instanceof MongooseTypes.Mixed){return true}}return false};function getPositionalPathType(self,path){var subpaths=path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);if(subpaths.length<2){return self.paths[subpaths[0]]}var val=self.path(subpaths[0]);var isNested=false;if(!val){return val}var last=subpaths.length-1,subpath,i=1;for(;i<subpaths.length;++i){isNested=false;subpath=subpaths[i];if(i===last&&val&&!val.schema&&!/\D/.test(subpath)){if(val instanceof MongooseTypes.Array){val=val.caster}else{val=undefined}break}if(!/\D/.test(subpath)){continue}if(!(val&&val.schema)){val=undefined;break}var type=val.schema.pathType(subpath);isNested=type==="nested";val=val.schema.path(subpath)}self.subpaths[path]=val;if(val){return"real"}if(isNested){return"nested"}return"adhocOrUndefined"}function getPositionalPath(self,path){getPositionalPathType(self,path);return self.subpaths[path]}Schema.prototype.queue=function(name,args){this.callQueue.push([name,args]);return this};Schema.prototype.pre=function(){var name=arguments[0];if(IS_QUERY_HOOK[name]){this.s.hooks.pre.apply(this.s.hooks,arguments);return this}return this.queue("pre",arguments)};Schema.prototype.post=function(method,fn){if(IS_QUERY_HOOK[method]){this.s.hooks.post.apply(this.s.hooks,arguments);return this}if(fn.length<2){return this.queue("on",[arguments[0],function(doc){return fn.call(doc,doc)}])}return this.queue("post",[arguments[0],function(next){var _this=this;var args=Array.prototype.slice.call(arguments,1);fn.call(this,this,function(err){return next.apply(_this,[err].concat(args))})}])};Schema.prototype.plugin=function(fn,opts){fn(this,opts);return this};Schema.prototype.method=function(name,fn){if(typeof name!=="string"){for(var i in name){this.methods[i]=name[i]}}else{this.methods[name]=fn}return this};Schema.prototype.static=function(name,fn){if(typeof name!=="string"){for(var i in name){this.statics[i]=name[i]}}else{this.statics[name]=fn}return this};Schema.prototype.index=function(fields,options){options||(options={});if(options.expires){utils.expires(options)}this._indexes.push([fields,options]);return this};Schema.prototype.set=function(key,value,_tags){if(arguments.length===1){return this.options[key]}switch(key){case"read":this.options[key]=readPref(value,_tags);break;case"safe":this.options[key]=value===false?{w:0}:value;break;default:this.options[key]=value}return this};Schema.prototype.get=function(key){return this.options[key]};var indexTypes="2d 2dsphere hashed text".split(" ");Object.defineProperty(Schema,"indexTypes",{get:function(){return indexTypes},set:function(){throw new Error("Cannot overwrite Schema.indexTypes")}});Schema.prototype.indexes=function(){"use strict";var indexes=[];var seenPrefix={};var collectIndexes=function(schema,prefix){if(seenPrefix[prefix]){return}seenPrefix[prefix]=true;prefix=prefix||"";var key,path,index,field,isObject,options,type;var keys=Object.keys(schema.paths);for(var i=0;i<keys.length;++i){key=keys[i];path=schema.paths[key];if(path instanceof MongooseTypes.DocumentArray||path.$isSingleNested){collectIndexes(path.schema,key+".")}else{index=path._index;if(index!==false&&index!==null&&index!==undefined){field={};isObject=utils.isObject(index);options=isObject?index:{};type=typeof index==="string"?index:isObject?index.type:false;if(type&&~Schema.indexTypes.indexOf(type)){field[prefix+key]=type}else if(options.text){field[prefix+key]="text";delete options.text}else{field[prefix+key]=1}delete options.type;if(!("background"in options)){options.background=true}indexes.push([field,options])}}}if(prefix){fixSubIndexPaths(schema,prefix)}else{schema._indexes.forEach(function(index){if(!("background"in index[1])){index[1].background=true}});indexes=indexes.concat(schema._indexes)}};collectIndexes(this);return indexes;function fixSubIndexPaths(schema,prefix){var subindexes=schema._indexes,len=subindexes.length,indexObj,newindex,klen,keys,key,i=0,j;for(i=0;i<len;++i){indexObj=subindexes[i][0];keys=Object.keys(indexObj);klen=keys.length;newindex={};for(j=0;j<klen;++j){key=keys[j];newindex[prefix+key]=indexObj[key]}indexes.push([newindex,subindexes[i][1]])}}};Schema.prototype.virtual=function(name,options){var virtuals=this.virtuals;var parts=name.split(".");virtuals[name]=parts.reduce(function(mem,part,i){mem[part]||(mem[part]=i===parts.length-1?new VirtualType(options,name):{});return mem[part]},this.tree);return virtuals[name]};Schema.prototype.virtualpath=function(name){return this.virtuals[name]};Schema.prototype.remove=function(path){if(typeof path==="string"){path=[path]}if(Array.isArray(path)){path.forEach(function(name){if(this.path(name)){delete this.paths[name]}},this)}};Schema.prototype._getSchema=function(path){var _this=this;var pathschema=_this.path(path);if(pathschema){return pathschema}function search(parts,schema){var p=parts.length+1,foundschema,trypath;while(p--){trypath=parts.slice(0,p).join(".");foundschema=schema.path(trypath);if(foundschema){if(foundschema.caster){if(foundschema.caster instanceof MongooseTypes.Mixed){return foundschema.caster}if(p!==parts.length&&foundschema.schema){if(parts[p]==="$"){return search(parts.slice(p+1),foundschema.schema)}return search(parts.slice(p),foundschema.schema)}}return foundschema}}}return search(path.split("."),_this)};module.exports=exports=Schema;Schema.Types=MongooseTypes=require("./schema/index");exports.ObjectId=MongooseTypes.ObjectId}).call(this,require("buffer").Buffer)},{"./drivers":10,"./schema/index":32,"./utils":47,"./virtualtype":48,async:49,buffer:91,events:94,kareem:69}],26:[function(require,module,exports){var SchemaType=require("../schematype"),CastError=SchemaType.CastError,Types={Boolean:require("./boolean"),Date:require("./date"),Number:require("./number"),String:require("./string"),ObjectId:require("./objectid"),Buffer:require("./buffer")},MongooseArray=require("../types").Array,EmbeddedDoc=require("../types").Embedded,Mixed=require("./mixed"),cast=require("../cast"),utils=require("../utils"),isMongooseObject=utils.isMongooseObject;function SchemaArray(key,cast,options){if(cast){var castOptions={};if(utils.getFunctionName(cast.constructor)==="Object"){if(cast.type){castOptions=utils.clone(cast);delete castOptions.type;cast=cast.type}else{cast=Mixed}}var name=typeof cast==="string"?cast:utils.getFunctionName(cast);var caster=name in Types?Types[name]:cast;this.casterConstructor=caster;this.caster=new caster(null,castOptions);if(!(this.caster instanceof EmbeddedDoc)){this.caster.path=key}}SchemaType.call(this,key,options,"Array");var _this=this,defaultArr,fn;if(this.defaultValue){defaultArr=this.defaultValue;fn=typeof defaultArr==="function"}this.default(function(){var arr=fn?defaultArr():defaultArr||[];return new MongooseArray(arr,_this.path,this)})}SchemaArray.schemaName="Array";SchemaArray.prototype=Object.create(SchemaType.prototype);SchemaArray.prototype.constructor=SchemaArray;SchemaArray.prototype.checkRequired=function(value){return!!(value&&value.length)};SchemaArray.prototype.applyGetters=function(value,scope){if(this.caster.options&&this.caster.options.ref){return value}return SchemaType.prototype.applyGetters.call(this,value,scope)};SchemaArray.prototype.cast=function(value,doc,init){if(Array.isArray(value)){if(!value.length&&doc){var indexes=doc.schema.indexedPaths();for(var i=0,l=indexes.length;i<l;++i){var pathIndex=indexes[i][0][this.path];if(pathIndex==="2dsphere"||pathIndex==="2d"){return}}}if(!(value&&value.isMongooseArray)){value=new MongooseArray(value,this.path,doc)}if(this.caster){try{for(i=0,l=value.length;i<l;i++){value[i]=this.caster.cast(value[i],doc,init)}}catch(e){throw new CastError(e.type,value,this.path)}}return value}if(!!doc&&!!init){doc.markModified(this.path)}return this.cast([value],doc,init)};SchemaArray.prototype.castForQuery=function($conditional,value){var handler,val;if(arguments.length===2){handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional+" with Array.")}val=handler.call(this,value)}else{val=$conditional;var proto=this.casterConstructor.prototype;var method=proto.castForQuery||proto.cast;var caster=this.caster;if(Array.isArray(val)){val=val.map(function(v){if(utils.isObject(v)&&v.$elemMatch){return v}if(method){v=method.call(caster,v)}return isMongooseObject(v)?v.toObject({virtuals:false}):v})}else if(method){val=method.call(caster,val)}}return val&&isMongooseObject(val)?val.toObject({virtuals:false}):val};function castToNumber(val){return Types.Number.prototype.cast.call(this,val)}function castArraysOfNumbers(arr,self){arr.forEach(function(v,i){if(Array.isArray(v)){castArraysOfNumbers(v,self)}else{arr[i]=castToNumber.call(self,v)}})}function cast$near(val){if(Array.isArray(val)){castArraysOfNumbers(val,this);return val}if(val&&val.$geometry){return cast$geometry(val,this)}return SchemaArray.prototype.castForQuery.call(this,val)}function cast$geometry(val,self){switch(val.$geometry.type){case"Polygon":case"LineString":case"Point":castArraysOfNumbers(val.$geometry.coordinates,self);break;default:break}if(val.$maxDistance){val.$maxDistance=castToNumber.call(self,val.$maxDistance)}return val}function cast$within(val){var _this=this;if(val.$maxDistance){val.$maxDistance=castToNumber.call(_this,val.$maxDistance);
}if(val.$box||val.$polygon){var type=val.$box?"$box":"$polygon";val[type].forEach(function(arr){if(!Array.isArray(arr)){var msg="Invalid $within $box argument. "+"Expected an array, received "+arr;throw new TypeError(msg)}arr.forEach(function(v,i){arr[i]=castToNumber.call(this,v)})})}else if(val.$center||val.$centerSphere){type=val.$center?"$center":"$centerSphere";val[type].forEach(function(item,i){if(Array.isArray(item)){item.forEach(function(v,j){item[j]=castToNumber.call(this,v)})}else{val[type][i]=castToNumber.call(this,item)}})}else if(val.$geometry){cast$geometry(val,this)}return val}function cast$all(val){if(!Array.isArray(val)){val=[val]}val=val.map(function(v){if(utils.isObject(v)){var o={};o[this.path]=v;return cast(this.casterConstructor.schema,o)[this.path]}return v},this);return this.castForQuery(val)}function cast$elemMatch(val){var keys=Object.keys(val);var numKeys=keys.length;var key;var value;for(var i=0;i<numKeys;++i){key=keys[i];value=val[key];if(key.indexOf("$")===0&&value){val[key]=this.castForQuery(key,value)}}return cast(this.casterConstructor.schema,val)}function cast$geoIntersects(val){var geo=val.$geometry;if(!geo){return}cast$geometry(val,this);return val}var handle=SchemaArray.prototype.$conditionalHandlers={};handle.$all=cast$all;handle.$options=String;handle.$elemMatch=cast$elemMatch;handle.$geoIntersects=cast$geoIntersects;handle.$or=handle.$and=function(val){if(!Array.isArray(val)){throw new TypeError("conditional $or/$and require array")}var ret=[];for(var i=0;i<val.length;++i){ret.push(cast(this.casterConstructor.schema,val[i]))}return ret};handle.$near=handle.$nearSphere=cast$near;handle.$within=handle.$geoWithin=cast$within;handle.$size=handle.$maxDistance=castToNumber;handle.$eq=handle.$gt=handle.$gte=handle.$in=handle.$lt=handle.$lte=handle.$ne=handle.$nin=handle.$regex=SchemaArray.prototype.castForQuery;module.exports=SchemaArray},{"../cast":3,"../schematype":38,"../types":44,"../utils":47,"./boolean":27,"./buffer":28,"./date":29,"./mixed":33,"./number":34,"./objectid":35,"./string":37}],27:[function(require,module,exports){var utils=require("../utils");var SchemaType=require("../schematype");function SchemaBoolean(path,options){SchemaType.call(this,path,options,"Boolean")}SchemaBoolean.schemaName="Boolean";SchemaBoolean.prototype=Object.create(SchemaType.prototype);SchemaBoolean.prototype.constructor=SchemaBoolean;SchemaBoolean.prototype.checkRequired=function(value){return value===true||value===false};SchemaBoolean.prototype.cast=function(value){if(value===null){return value}if(value==="0"){return false}if(value==="true"){return true}if(value==="false"){return false}return!!value};SchemaBoolean.$conditionalHandlers=utils.options(SchemaType.prototype.$conditionalHandlers,{});SchemaBoolean.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length===2){handler=SchemaBoolean.$conditionalHandlers[$conditional];if(handler){return handler.call(this,val)}return this.cast(val)}return this.cast($conditional)};module.exports=SchemaBoolean},{"../schematype":38,"../utils":47}],28:[function(require,module,exports){(function(Buffer){var handleBitwiseOperator=require("./operators/bitwise");var utils=require("../utils");var MongooseBuffer=require("../types").Buffer;var SchemaType=require("../schematype");var Binary=MongooseBuffer.Binary;var CastError=SchemaType.CastError;var Document;function SchemaBuffer(key,options){SchemaType.call(this,key,options,"Buffer")}SchemaBuffer.schemaName="Buffer";SchemaBuffer.prototype=Object.create(SchemaType.prototype);SchemaBuffer.prototype.constructor=SchemaBuffer;SchemaBuffer.prototype.checkRequired=function(value,doc){if(SchemaType._isRef(this,value,doc,true)){return!!value}return!!(value&&value.length)};SchemaBuffer.prototype.cast=function(value,doc,init){var ret;if(SchemaType._isRef(this,value,doc,init)){if(value===null||value===undefined){return value}Document||(Document=require("./../document"));if(value instanceof Document){value.$__.wasPopulated=true;return value}if(Buffer.isBuffer(value)){return value}else if(!utils.isObject(value)){throw new CastError("buffer",value,this.path)}var path=doc.$__fullPath(this.path);var owner=doc.ownerDocument?doc.ownerDocument():doc;var pop=owner.populated(path,true);ret=new pop.options.model(value);ret.$__.wasPopulated=true;return ret}if(value&&value._id){value=value._id}if(value&&value.isMongooseBuffer){return value}if(Buffer.isBuffer(value)){if(!value||!value.isMongooseBuffer){value=new MongooseBuffer(value,[this.path,doc])}return value}else if(value instanceof Binary){ret=new MongooseBuffer(value.value(true),[this.path,doc]);if(typeof value.sub_type!=="number"){throw new CastError("buffer",value,this.path)}ret._subtype=value.sub_type;return ret}if(value===null){return value}var type=typeof value;if(type==="string"||type==="number"||Array.isArray(value)){if(type==="number"){value=[value]}ret=new MongooseBuffer(value,[this.path,doc]);return ret}throw new CastError("buffer",value,this.path)};function handleSingle(val){return this.castForQuery(val)}SchemaBuffer.prototype.$conditionalHandlers=utils.options(SchemaType.prototype.$conditionalHandlers,{$bitsAllClear:handleBitwiseOperator,$bitsAnyClear:handleBitwiseOperator,$bitsAllSet:handleBitwiseOperator,$bitsAnySet:handleBitwiseOperator,$gt:handleSingle,$gte:handleSingle,$lt:handleSingle,$lte:handleSingle});SchemaBuffer.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length===2){handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional+" with Buffer.")}return handler.call(this,val)}val=$conditional;return this.cast(val).toObject()};module.exports=SchemaBuffer}).call(this,require("buffer").Buffer)},{"../schematype":38,"../types":44,"../utils":47,"./../document":4,"./operators/bitwise":36,buffer:91}],29:[function(require,module,exports){var errorMessages=require("../error").messages;var utils=require("../utils");var SchemaType=require("../schematype");var CastError=SchemaType.CastError;function SchemaDate(key,options){SchemaType.call(this,key,options,"Date")}SchemaDate.schemaName="Date";SchemaDate.prototype=Object.create(SchemaType.prototype);SchemaDate.prototype.constructor=SchemaDate;SchemaDate.prototype.expires=function(when){if(!this._index||this._index.constructor.name!=="Object"){this._index={}}this._index.expires=when;utils.expires(this._index);return this};SchemaDate.prototype.checkRequired=function(value){return value instanceof Date};SchemaDate.prototype.min=function(value,message){if(this.minValidator){this.validators=this.validators.filter(function(v){return v.validator!==this.minValidator},this)}if(value){var msg=message||errorMessages.Date.min;msg=msg.replace(/{MIN}/,value===Date.now?"Date.now()":this.cast(value).toString());var _this=this;this.validators.push({validator:this.minValidator=function(val){var min=value===Date.now?value():_this.cast(value);return val===null||val.valueOf()>=min.valueOf()},message:msg,type:"min",min:value})}return this};SchemaDate.prototype.max=function(value,message){if(this.maxValidator){this.validators=this.validators.filter(function(v){return v.validator!==this.maxValidator},this)}if(value){var msg=message||errorMessages.Date.max;msg=msg.replace(/{MAX}/,value===Date.now?"Date.now()":this.cast(value).toString());var _this=this;this.validators.push({validator:this.maxValidator=function(val){var max=value===Date.now?value():_this.cast(value);return val===null||val.valueOf()<=max.valueOf()},message:msg,type:"max",max:value})}return this};SchemaDate.prototype.cast=function(value){if(value===null||value===void 0||value===""){return null}if(value instanceof Date){return value}var date;if(value instanceof Number||typeof value==="number"||String(value)==Number(value)){date=new Date(Number(value))}else if(value.valueOf){date=new Date(value.valueOf())}if(!Number.isNaN(date.valueOf())){return date}throw new CastError("date",value,this.path)};function handleSingle(val){return this.cast(val)}SchemaDate.prototype.$conditionalHandlers=utils.options(SchemaType.prototype.$conditionalHandlers,{$gt:handleSingle,$gte:handleSingle,$lt:handleSingle,$lte:handleSingle});SchemaDate.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length!==2){return this.cast($conditional)}handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional+" with Date.")}return handler.call(this,val)};module.exports=SchemaDate},{"../error":11,"../schematype":38,"../utils":47}],30:[function(require,module,exports){var ArrayType=require("./array");var CastError=require("../error/cast");var MongooseDocumentArray=require("../types/documentarray");var SchemaType=require("../schematype");var Subdocument=require("../types/embedded");function DocumentArray(key,schema,options){function EmbeddedDocument(){Subdocument.apply(this,arguments)}EmbeddedDocument.prototype=Object.create(Subdocument.prototype);EmbeddedDocument.prototype.$__setSchema(schema);EmbeddedDocument.schema=schema;for(var i in schema.methods){EmbeddedDocument.prototype[i]=schema.methods[i]}for(i in schema.statics){EmbeddedDocument[i]=schema.statics[i]}EmbeddedDocument.options=options;ArrayType.call(this,key,EmbeddedDocument,options);this.schema=schema;var path=this.path;var fn=this.defaultValue;this.default(function(){var arr=fn.call(this);if(!Array.isArray(arr)){arr=[arr]}return new MongooseDocumentArray(arr,path,this)})}DocumentArray.schemaName="DocumentArray";DocumentArray.prototype=Object.create(ArrayType.prototype);DocumentArray.prototype.constructor=DocumentArray;DocumentArray.prototype.doValidate=function(array,fn,scope,options){SchemaType.prototype.doValidate.call(this,array,function(err){if(err){return fn(err)}var count=array&&array.length;var error;if(!count){return fn()}if(options&&options.updateValidator){return fn()}function callback(err){if(err){error=err}--count||fn(error)}for(var i=0,len=count;i<len;++i){var doc=array[i];if(!doc){--count||fn(error);continue}if(doc.$__original_validate){doc.$__original_validate({__noPromise:true},callback)}else{doc.validate({__noPromise:true},callback)}}},scope)};DocumentArray.prototype.doValidateSync=function(array,scope){var schemaTypeError=SchemaType.prototype.doValidateSync.call(this,array,scope);if(schemaTypeError){return schemaTypeError}var count=array&&array.length,resultError=null;if(!count){return}for(var i=0,len=count;i<len;++i){if(resultError){break}var doc=array[i];if(!doc){continue}var subdocValidateError=doc.validateSync();if(subdocValidateError){resultError=subdocValidateError}}return resultError};DocumentArray.prototype.cast=function(value,doc,init,prev,options){var selected,subdoc,i;if(!Array.isArray(value)){if(!!doc&&init){doc.markModified(this.path)}return this.cast([value],doc,init,prev)}if(!(value&&value.isMongooseDocumentArray)&&(!options||!options.skipDocumentArrayCast)){value=new MongooseDocumentArray(value,this.path,doc);if(prev&&prev._handlers){for(var key in prev._handlers){doc.removeListener(key,prev._handlers[key])}}}i=value.length;while(i--){if(!value[i]){continue}if(value[i]instanceof Subdocument&&value[i].schema!==this.casterConstructor.schema){value[i]=value[i].toObject({virtuals:false})}if(!(value[i]instanceof Subdocument)&&value[i]){if(init){selected||(selected=scopePaths(this,doc.$__.selected,init));subdoc=new this.casterConstructor(null,value,true,selected,i);value[i]=subdoc.init(value[i])}else{try{subdoc=prev.id(value[i]._id)}catch(e){}if(prev&&subdoc){subdoc.set(value[i]);value[i]=subdoc}else{try{subdoc=new this.casterConstructor(value[i],value,undefined,undefined,i);value[i]=subdoc}catch(error){throw new CastError("embedded",value[i],value._path)}}}}}return value};function scopePaths(array,fields,init){if(!(init&&fields)){return undefined}var path=array.path+".",keys=Object.keys(fields),i=keys.length,selected={},hasKeys,key;while(i--){key=keys[i];if(key.indexOf(path)===0){hasKeys||(hasKeys=true);selected[key.substring(path.length)]=fields[key]}}return hasKeys&&selected||undefined}module.exports=DocumentArray},{"../error/cast":12,"../schematype":38,"../types/documentarray":42,"../types/embedded":43,"./array":26}],31:[function(require,module,exports){var SchemaType=require("../schematype");var Subdocument=require("../types/subdocument");module.exports=Embedded;function Embedded(schema,path,options){var _embedded=function(value,path,parent){var _this=this;Subdocument.apply(this,arguments);this.$parent=parent;if(parent){parent.on("save",function(){_this.emit("save",_this)})}};_embedded.prototype=Object.create(Subdocument.prototype);_embedded.prototype.$__setSchema(schema);_embedded.schema=schema;_embedded.$isSingleNested=true;_embedded.prototype.$basePath=path;for(var i in schema.methods){_embedded.prototype[i]=schema.methods[i]}for(i in schema.statics){_embedded[i]=schema.statics[i]}this.caster=_embedded;this.schema=schema;this.$isSingleNested=true;SchemaType.call(this,path,options,"Embedded")}Embedded.prototype=Object.create(SchemaType.prototype);Embedded.prototype.cast=function(val,doc,init){if(val&&val.$isSingleNested){return val}var subdoc=new this.caster(undefined,undefined,doc);if(init){subdoc.init(val)}else{subdoc.set(val,undefined,true)}return subdoc};Embedded.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length===2){handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional)}return handler.call(this,val)}val=$conditional;return new this.caster(val).toObject({virtuals:false})};Embedded.prototype.doValidate=function(value,fn){SchemaType.prototype.doValidate.call(this,value,function(error){if(error){return fn(error)}if(!value){return fn(null)}value.validate(fn,{__noPromise:true})})};Embedded.prototype.doValidateSync=function(value){var schemaTypeError=SchemaType.prototype.doValidateSync.call(this,value);if(schemaTypeError){return schemaTypeError}if(!value){return}return value.validateSync()};Embedded.prototype.checkRequired=function(value){return!!value&&value.$isSingleNested}},{"../schematype":38,"../types/subdocument":46}],32:[function(require,module,exports){exports.String=require("./string");exports.Number=require("./number");exports.Boolean=require("./boolean");exports.DocumentArray=require("./documentarray");exports.Embedded=require("./embedded");exports.Array=require("./array");exports.Buffer=require("./buffer");exports.Date=require("./date");exports.ObjectId=require("./objectid");exports.Mixed=require("./mixed");exports.Oid=exports.ObjectId;exports.Object=exports.Mixed;exports.Bool=exports.Boolean},{"./array":26,"./boolean":27,"./buffer":28,"./date":29,"./documentarray":30,"./embedded":31,"./mixed":33,"./number":34,"./objectid":35,"./string":37}],33:[function(require,module,exports){var SchemaType=require("../schematype");var utils=require("../utils");function Mixed(path,options){if(options&&options.default){var def=options.default;if(Array.isArray(def)&&def.length===0){options.default=Array}else if(!options.shared&&utils.isObject(def)&&Object.keys(def).length===0){options.default=function(){return{}}}}SchemaType.call(this,path,options,"Mixed")}Mixed.schemaName="Mixed";Mixed.prototype=Object.create(SchemaType.prototype);Mixed.prototype.constructor=Mixed;Mixed.prototype.checkRequired=function(val){return val!==undefined&&val!==null};Mixed.prototype.cast=function(val){return val};Mixed.prototype.castForQuery=function($cond,val){if(arguments.length===2){return val}return $cond};module.exports=Mixed},{"../schematype":38,"../utils":47}],34:[function(require,module,exports){(function(Buffer){var SchemaType=require("../schematype");var CastError=SchemaType.CastError;var handleBitwiseOperator=require("./operators/bitwise");var errorMessages=require("../error").messages;var utils=require("../utils");var Document;function SchemaNumber(key,options){SchemaType.call(this,key,options,"Number")}SchemaNumber.schemaName="Number";SchemaNumber.prototype=Object.create(SchemaType.prototype);SchemaNumber.prototype.constructor=SchemaNumber;SchemaNumber.prototype.checkRequired=function checkRequired(value,doc){if(SchemaType._isRef(this,value,doc,true)){return!!value}return typeof value==="number"||value instanceof Number};SchemaNumber.prototype.min=function(value,message){if(this.minValidator){this.validators=this.validators.filter(function(v){return v.validator!==this.minValidator},this)}if(value!==null&&value!==undefined){var msg=message||errorMessages.Number.min;msg=msg.replace(/{MIN}/,value);this.validators.push({validator:this.minValidator=function(v){return v==null||v>=value},message:msg,type:"min",min:value})}return this};SchemaNumber.prototype.max=function(value,message){if(this.maxValidator){this.validators=this.validators.filter(function(v){return v.validator!==this.maxValidator},this)}if(value!==null&&value!==undefined){var msg=message||errorMessages.Number.max;msg=msg.replace(/{MAX}/,value);this.validators.push({validator:this.maxValidator=function(v){return v==null||v<=value},message:msg,type:"max",max:value})}return this};SchemaNumber.prototype.cast=function(value,doc,init){if(SchemaType._isRef(this,value,doc,init)){if(value===null||value===undefined){return value}Document||(Document=require("./../document"));if(value instanceof Document){value.$__.wasPopulated=true;return value}if(typeof value==="number"){return value}else if(Buffer.isBuffer(value)||!utils.isObject(value)){throw new CastError("number",value,this.path)}var path=doc.$__fullPath(this.path);var owner=doc.ownerDocument?doc.ownerDocument():doc;var pop=owner.populated(path,true);var ret=new pop.options.model(value);ret.$__.wasPopulated=true;return ret}var val=value&&value._id?value._id:value;if(!isNaN(val)){if(val===null){return val}if(val===""){return null}if(typeof val==="string"||typeof val==="boolean"){val=Number(val)}if(val instanceof Number){return val}if(typeof val==="number"){return val}if(val.toString&&!Array.isArray(val)&&val.toString()==Number(val)){return new Number(val)}}throw new CastError("number",value,this.path)};function handleSingle(val){return this.cast(val)}function handleArray(val){var _this=this;if(!Array.isArray(val)){return[this.cast(val)]}return val.map(function(m){return _this.cast(m)})}SchemaNumber.prototype.$conditionalHandlers=utils.options(SchemaType.prototype.$conditionalHandlers,{$bitsAllClear:handleBitwiseOperator,$bitsAnyClear:handleBitwiseOperator,$bitsAllSet:handleBitwiseOperator,$bitsAnySet:handleBitwiseOperator,$gt:handleSingle,$gte:handleSingle,$lt:handleSingle,$lte:handleSingle,$mod:handleArray});SchemaNumber.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length===2){handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional+" with Number.")}return handler.call(this,val)}val=this.cast($conditional);return val};module.exports=SchemaNumber}).call(this,require("buffer").Buffer)},{"../error":11,"../schematype":38,"../utils":47,"./../document":4,"./operators/bitwise":36,buffer:91}],35:[function(require,module,exports){(function(Buffer){var SchemaType=require("../schematype"),CastError=SchemaType.CastError,oid=require("../types/objectid"),utils=require("../utils"),Document;function ObjectId(key,options){SchemaType.call(this,key,options,"ObjectID")}ObjectId.schemaName="ObjectId";ObjectId.prototype=Object.create(SchemaType.prototype);ObjectId.prototype.constructor=ObjectId;ObjectId.prototype.auto=function(turnOn){if(turnOn){this.default(defaultId);this.set(resetId)}return this};ObjectId.prototype.checkRequired=function checkRequired(value,doc){if(SchemaType._isRef(this,value,doc,true)){return!!value}return value instanceof oid};ObjectId.prototype.cast=function(value,doc,init){if(SchemaType._isRef(this,value,doc,init)){if(value===null||value===undefined){return value}Document||(Document=require("./../document"));if(value instanceof Document){value.$__.wasPopulated=true;return value}if(value instanceof oid){return value}else if(Buffer.isBuffer(value)||!utils.isObject(value)){throw new CastError("ObjectId",value,this.path)}var path=doc.$__fullPath(this.path);var owner=doc.ownerDocument?doc.ownerDocument():doc;var pop=owner.populated(path,true);var ret=new pop.options.model(value);ret.$__.wasPopulated=true;return ret}if(value===null||value===undefined){return value}if(value instanceof oid){return value}if(value._id){if(value._id instanceof oid){return value._id}if(value._id.toString instanceof Function){try{return oid.createFromHexString(value._id.toString())}catch(e){}}}if(value.toString instanceof Function){try{return oid.createFromHexString(value.toString())}catch(err){throw new CastError("ObjectId",value,this.path)}}throw new CastError("ObjectId",value,this.path)};function handleSingle(val){return this.cast(val)}ObjectId.prototype.$conditionalHandlers=utils.options(SchemaType.prototype.$conditionalHandlers,{$gt:handleSingle,$gte:handleSingle,$lt:handleSingle,$lte:handleSingle});ObjectId.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length===2){handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional+" with ObjectId.")}return handler.call(this,val)}return this.cast($conditional)};function defaultId(){return new oid}function resetId(v){this.$__._id=null;return v}module.exports=ObjectId}).call(this,require("buffer").Buffer)},{"../schematype":38,"../types/objectid":45,"../utils":47,"./../document":4,buffer:91}],36:[function(require,module,exports){(function(Buffer){var CastError=require("../../error/cast");function handleBitwiseOperator(val){var _this=this;if(Array.isArray(val)){return val.map(function(v){return _castNumber(_this.path,v)})}else if(Buffer.isBuffer(val)){return val}return _castNumber(_this.path,val)}function _castNumber(path,num){var v=Number(num);if(isNaN(v)){throw new CastError("number",num,path)}return v}module.exports=handleBitwiseOperator}).call(this,require("buffer").Buffer)},{"../../error/cast":12,buffer:91}],37:[function(require,module,exports){(function(Buffer){var SchemaType=require("../schematype");var CastError=SchemaType.CastError;var errorMessages=require("../error").messages;var utils=require("../utils");var Document;function SchemaString(key,options){this.enumValues=[];this.regExp=null;SchemaType.call(this,key,options,"String")}SchemaString.schemaName="String";SchemaString.prototype=Object.create(SchemaType.prototype);SchemaString.prototype.constructor=SchemaString;SchemaString.prototype.enum=function(){if(this.enumValidator){this.validators=this.validators.filter(function(v){return v.validator!==this.enumValidator},this);this.enumValidator=false}if(arguments[0]===void 0||arguments[0]===false){return this}var values;var errorMessage;if(utils.isObject(arguments[0])){values=arguments[0].values;errorMessage=arguments[0].message}else{values=arguments;errorMessage=errorMessages.String.enum}for(var i=0;i<values.length;i++){if(undefined!==values[i]){this.enumValues.push(this.cast(values[i]))}}var vals=this.enumValues;this.enumValidator=function(v){return undefined===v||~vals.indexOf(v)};this.validators.push({validator:this.enumValidator,message:errorMessage,type:"enum",enumValues:vals});return this};SchemaString.prototype.lowercase=function(){return this.set(function(v,self){if(typeof v!=="string"){v=self.cast(v)}if(v){return v.toLowerCase()}return v})};SchemaString.prototype.uppercase=function(){return this.set(function(v,self){if(typeof v!=="string"){v=self.cast(v)}if(v){return v.toUpperCase()}return v})};SchemaString.prototype.trim=function(){return this.set(function(v,self){if(typeof v!=="string"){v=self.cast(v)}if(v){return v.trim()}return v})};SchemaString.prototype.minlength=function(value,message){if(this.minlengthValidator){this.validators=this.validators.filter(function(v){return v.validator!==this.minlengthValidator},this)}if(value!==null&&value!==undefined){var msg=message||errorMessages.String.minlength;msg=msg.replace(/{MINLENGTH}/,value);this.validators.push({validator:this.minlengthValidator=function(v){return v===null||v.length>=value},message:msg,type:"minlength",minlength:value})}return this};SchemaString.prototype.maxlength=function(value,message){if(this.maxlengthValidator){this.validators=this.validators.filter(function(v){return v.validator!==this.maxlengthValidator},this)}if(value!==null&&value!==undefined){var msg=message||errorMessages.String.maxlength;msg=msg.replace(/{MAXLENGTH}/,value);this.validators.push({validator:this.maxlengthValidator=function(v){return v===null||v.length<=value},message:msg,type:"maxlength",maxlength:value})}return this};SchemaString.prototype.match=function match(regExp,message){var msg=message||errorMessages.String.match;var matchValidator=function(v){if(!regExp){return false}var ret=v!=null&&v!==""?regExp.test(v):true;return ret};this.validators.push({validator:matchValidator,message:msg,type:"regexp",regexp:regExp});return this};SchemaString.prototype.checkRequired=function checkRequired(value,doc){if(SchemaType._isRef(this,value,doc,true)){return!!value}return(value instanceof String||typeof value==="string")&&value.length};SchemaString.prototype.cast=function(value,doc,init){if(SchemaType._isRef(this,value,doc,init)){if(value===null||value===undefined){return value}Document||(Document=require("./../document"));if(value instanceof Document){value.$__.wasPopulated=true;return value}if(typeof value==="string"){return value}else if(Buffer.isBuffer(value)||!utils.isObject(value)){throw new CastError("string",value,this.path)}var path=doc.$__fullPath(this.path);var owner=doc.ownerDocument?doc.ownerDocument():doc;var pop=owner.populated(path,true);var ret=new pop.options.model(value);ret.$__.wasPopulated=true;return ret}if(value===null||value===undefined){return value}if(typeof value!=="undefined"){if(value._id&&typeof value._id==="string"){return value._id}if(value.toString&&value.toString!==Object.prototype.toString){return value.toString()}}throw new CastError("string",value,this.path)};function handleSingle(val){return this.castForQuery(val)}function handleArray(val){var _this=this;if(!Array.isArray(val)){return[this.castForQuery(val)]}return val.map(function(m){return _this.castForQuery(m)})}SchemaString.prototype.$conditionalHandlers=utils.options(SchemaType.prototype.$conditionalHandlers,{$all:handleArray,$gt:handleSingle,$gte:handleSingle,$lt:handleSingle,$lte:handleSingle,$options:handleSingle,$regex:handleSingle});SchemaString.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length===2){handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional+" with String.")}return handler.call(this,val)}val=$conditional;if(Object.prototype.toString.call(val)==="[object RegExp]"){return val}return this.cast(val)};module.exports=SchemaString}).call(this,require("buffer").Buffer)},{"../error":11,"../schematype":38,"../utils":47,"./../document":4,buffer:91}],38:[function(require,module,exports){(function(Buffer){var utils=require("./utils");var error=require("./error");var errorMessages=error.messages;var CastError=error.CastError;var ValidatorError=error.ValidatorError;function SchemaType(path,options,instance){this.path=path;this.instance=instance;this.validators=[];this.setters=[];this.getters=[];this.options=options;this._index=null;this.selected;for(var i in options){if(this[i]&&typeof this[i]==="function"){if(i==="index"&&this._index){continue}var opts=Array.isArray(options[i])?options[i]:[options[i]];this[i].apply(this,opts)}}}SchemaType.prototype.default=function(val){if(arguments.length===1){this.defaultValue=typeof val==="function"?val:this.cast(val);return this}else if(arguments.length>1){this.defaultValue=utils.args(arguments)}return this.defaultValue};SchemaType.prototype.index=function(options){this._index=options;utils.expires(this._index);return this};SchemaType.prototype.unique=function(bool){if(this._index===null||this._index===undefined||typeof this._index==="boolean"){this._index={}}else if(typeof this._index==="string"){this._index={type:this._index}}this._index.unique=bool;return this};SchemaType.prototype.text=function(bool){if(this._index===null||this._index===undefined||typeof this._index==="boolean"){this._index={}}else if(typeof this._index==="string"){this._index={type:this._index}}this._index.text=bool;return this};SchemaType.prototype.sparse=function(bool){if(this._index===null||this._index===undefined||typeof this._index==="boolean"){this._index={}}else if(typeof this._index==="string"){this._index={type:this._index}}this._index.sparse=bool;return this};SchemaType.prototype.set=function(fn){if(typeof fn!=="function"){throw new TypeError("A setter must be a function.")}this.setters.push(fn);return this};SchemaType.prototype.get=function(fn){if(typeof fn!=="function"){throw new TypeError("A getter must be a function.")}this.getters.push(fn);return this};SchemaType.prototype.validate=function(obj,message,type){if(typeof obj==="function"||obj&&utils.getFunctionName(obj.constructor)==="RegExp"){var properties;if(message instanceof Object&&!type){properties=utils.clone(message);if(!properties.message){properties.message=properties.msg}properties.validator=obj;properties.type=properties.type||"user defined"}else{if(!message){message=errorMessages.general.default}if(!type){type="user defined"}properties={message:message,type:type,validator:obj}}this.validators.push(properties);return this}var i,length,arg;for(i=0,length=arguments.length;i<length;i++){arg=arguments[i];if(!(arg&&utils.getFunctionName(arg.constructor)==="Object")){var msg="Invalid validator. Received ("+typeof arg+") "+arg+". See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate";throw new Error(msg)}this.validate(arg.validator,arg)}return this};SchemaType.prototype.required=function(required,message){if(required===false){this.validators=this.validators.filter(function(v){return v.validator!==this.requiredValidator},this);this.isRequired=false;return this}var _this=this;this.isRequired=true;this.requiredValidator=function(v){if("isSelected"in this&&!this.isSelected(_this.path)&&!this.isModified(_this.path)){return true}return typeof required==="function"&&!required.apply(this)||_this.checkRequired(v,this)};if(typeof required==="string"){message=required;required=undefined}var msg=message||errorMessages.general.required;this.validators.unshift({validator:this.requiredValidator,message:msg,type:"required"});return this};SchemaType.prototype.getDefault=function(scope,init){var ret=typeof this.defaultValue==="function"?this.defaultValue.call(scope):this.defaultValue;if(ret!==null&&ret!==undefined){return this.cast(ret,scope,init)}return ret};SchemaType.prototype.applySetters=function(value,scope,init,priorVal,options){var v=value,setters=this.setters,len=setters.length,caster=this.caster;while(len--){v=setters[len].call(scope,v,this)}if(Array.isArray(v)&&caster&&caster.setters){var newVal=[];for(var i=0;i<v.length;i++){newVal.push(caster.applySetters(v[i],scope,init,priorVal))}v=newVal}if(v===null||v===undefined){return v}v=this.cast(v,scope,init,priorVal,options);return v};SchemaType.prototype.applyGetters=function(value,scope){var v=value,getters=this.getters,len=getters.length;if(!len){return v}while(len--){v=getters[len].call(scope,v,this)}return v};SchemaType.prototype.select=function select(val){this.selected=!!val;return this};SchemaType.prototype.doValidate=function(value,fn,scope){var err=false,path=this.path,count=this.validators.length;if(!count){return fn(null)}var validate=function(ok,validatorProperties){if(err){return}if(ok===undefined||ok){--count||fn(null)}else{err=new ValidatorError(validatorProperties);fn(err)}};var _this=this;this.validators.forEach(function(v){if(err){return}var validator=v.validator;var validatorProperties=utils.clone(v);validatorProperties.path=path;validatorProperties.value=value;if(validator instanceof RegExp){validate(validator.test(value),validatorProperties);
}else if(typeof validator==="function"){if(value===undefined&&!_this.isRequired){validate(true,validatorProperties);return}if(validator.length===2){validator.call(scope,value,function(ok,customMsg){if(customMsg){validatorProperties.message=customMsg}validate(ok,validatorProperties)})}else{validate(validator.call(scope,value),validatorProperties)}}})};SchemaType.prototype.doValidateSync=function(value,scope){var err=null,path=this.path,count=this.validators.length;if(!count){return null}var validate=function(ok,validatorProperties){if(err){return}if(ok!==undefined&&!ok){err=new ValidatorError(validatorProperties)}};var _this=this;if(value===undefined&&!_this.isRequired){return null}this.validators.forEach(function(v){if(err){return}var validator=v.validator;var validatorProperties=utils.clone(v);validatorProperties.path=path;validatorProperties.value=value;if(validator instanceof RegExp){validate(validator.test(value),validatorProperties)}else if(typeof validator==="function"){if(validator.length!==2){validate(validator.call(scope,value),validatorProperties)}}});return err};SchemaType._isRef=function(self,value,doc,init){var ref=init&&self.options&&self.options.ref;if(!ref&&doc&&doc.$__fullPath){var path=doc.$__fullPath(self.path);var owner=doc.ownerDocument?doc.ownerDocument():doc;ref=owner.populated(path)}if(ref){if(value==null){return true}if(!Buffer.isBuffer(value)&&value._bsontype!=="Binary"&&utils.isObject(value)){return true}}return false};function handleSingle(val){return this.castForQuery(val)}function handleArray(val){var _this=this;if(!Array.isArray(val)){return[this.castForQuery(val)]}return val.map(function(m){return _this.castForQuery(m)})}SchemaType.prototype.$conditionalHandlers={$all:handleArray,$eq:handleSingle,$in:handleArray,$ne:handleSingle,$nin:handleArray};SchemaType.prototype.castForQuery=function($conditional,val){var handler;if(arguments.length===2){handler=this.$conditionalHandlers[$conditional];if(!handler){throw new Error("Can't use "+$conditional)}return handler.call(this,val)}val=$conditional;return this.cast(val)};SchemaType.prototype.checkRequired=function(val){return val!=null};module.exports=exports=SchemaType;exports.CastError=CastError;exports.ValidatorError=ValidatorError}).call(this,require("buffer").Buffer)},{"./error":11,"./utils":47,buffer:91}],39:[function(require,module,exports){var utils=require("./utils");var StateMachine=module.exports=exports=function StateMachine(){};StateMachine.ctor=function(){var states=utils.args(arguments);var ctor=function(){StateMachine.apply(this,arguments);this.paths={};this.states={};this.stateNames=states;var i=states.length,state;while(i--){state=states[i];this.states[state]={}}};ctor.prototype=new StateMachine;states.forEach(function(state){ctor.prototype[state]=function(path){this._changeState(path,state)}});return ctor};StateMachine.prototype._changeState=function _changeState(path,nextState){var prevBucket=this.states[this.paths[path]];if(prevBucket)delete prevBucket[path];this.paths[path]=nextState;this.states[nextState][path]=true};StateMachine.prototype.clear=function clear(state){var keys=Object.keys(this.states[state]),i=keys.length,path;while(i--){path=keys[i];delete this.states[state][path];delete this.paths[path]}};StateMachine.prototype.some=function some(){var _this=this;var what=arguments.length?arguments:this.stateNames;return Array.prototype.some.call(what,function(state){return Object.keys(_this.states[state]).length})};StateMachine.prototype._iter=function _iter(iterMethod){return function(){var numArgs=arguments.length,states=utils.args(arguments,0,numArgs-1),callback=arguments[numArgs-1];if(!states.length)states=this.stateNames;var _this=this;var paths=states.reduce(function(paths,state){return paths.concat(Object.keys(_this.states[state]))},[]);return paths[iterMethod](function(path,i,paths){return callback(path,i,paths)})}};StateMachine.prototype.forEach=function forEach(){this.forEach=this._iter("forEach");return this.forEach.apply(this,arguments)};StateMachine.prototype.map=function map(){this.map=this._iter("map");return this.map.apply(this,arguments)}},{"./utils":47}],40:[function(require,module,exports){(function(Buffer){var EmbeddedDocument=require("./embedded");var Document=require("../document");var ObjectId=require("./objectid");var utils=require("../utils");var isMongooseObject=utils.isMongooseObject;function MongooseArray(values,path,doc){var arr=[].concat(values);var props={isMongooseArray:true,validators:[],_path:path,_atomics:{},_schema:void 0};var tmp={};var keysMA=Object.keys(MongooseArray.mixin);for(var i=0;i<keysMA.length;++i){tmp[keysMA[i]]={enumerable:false,configurable:true,writable:true,value:MongooseArray.mixin[keysMA[i]]}}var keysP=Object.keys(props);for(var j=0;j<keysP.length;++j){tmp[keysP[j]]={enumerable:false,configurable:true,writable:true,value:props[keysP[j]]}}Object.defineProperties(arr,tmp);if(doc&&doc instanceof Document){arr._parent=doc;arr._schema=doc.schema.path(path)}return arr}MongooseArray.mixin={_atomics:undefined,_parent:undefined,_cast:function(value){var owner=this._owner;var populated=false;var Model;if(this._parent){if(!owner){owner=this._owner=this._parent.ownerDocument?this._parent.ownerDocument():this._parent}populated=owner.populated(this._path,true)}if(populated&&value!==null&&value!==undefined){Model=populated.options.model;if(Buffer.isBuffer(value)||value instanceof ObjectId||!utils.isObject(value)){value={_id:value}}var isDisc=value.schema&&value.schema.discriminatorMapping&&value.schema.discriminatorMapping.key!==undefined;if(!isDisc){value=new Model(value)}return this._schema.caster.cast(value,this._parent,true)}return this._schema.caster.cast(value,this._parent,false)},_markModified:function(elem,embeddedPath){var parent=this._parent,dirtyPath;if(parent){dirtyPath=this._path;if(arguments.length){if(embeddedPath!=null){dirtyPath=dirtyPath+"."+this.indexOf(elem)+"."+embeddedPath}else{dirtyPath=dirtyPath+"."+elem}}parent.markModified(dirtyPath)}return this},_registerAtomic:function(op,val){if(op==="$set"){this._atomics={$set:val};return this}var atomics=this._atomics;if(op==="$pop"&&!("$pop"in atomics)){var _this=this;this._parent.once("save",function(){_this._popped=_this._shifted=null})}if(this._atomics.$set||Object.keys(atomics).length&&!(op in atomics)){this._atomics={$set:this};return this}var selector;if(op==="$pullAll"||op==="$pushAll"||op==="$addToSet"){atomics[op]||(atomics[op]=[]);atomics[op]=atomics[op].concat(val)}else if(op==="$pullDocs"){var pullOp=atomics["$pull"]||(atomics["$pull"]={});if(val[0]instanceof EmbeddedDocument){selector=pullOp["$or"]||(pullOp["$or"]=[]);Array.prototype.push.apply(selector,val.map(function(v){return v.toObject({virtuals:false})}))}else{selector=pullOp["_id"]||(pullOp["_id"]={$in:[]});selector["$in"]=selector["$in"].concat(val)}}else{atomics[op]=val}return this},$__getAtomics:function(){var ret=[];var keys=Object.keys(this._atomics);var i=keys.length;if(i===0){ret[0]=["$set",this.toObject({depopulate:1,transform:false})];return ret}while(i--){var op=keys[i];var val=this._atomics[op];if(isMongooseObject(val)){val=val.toObject({depopulate:1,transform:false})}else if(Array.isArray(val)){val=this.toObject.call(val,{depopulate:1,transform:false})}else if(val.valueOf){val=val.valueOf()}if(op==="$addToSet"){val={$each:val}}ret.push([op,val])}return ret},hasAtomics:function hasAtomics(){if(!(this._atomics&&this._atomics.constructor.name==="Object")){return 0}return Object.keys(this._atomics).length},_mapCast:function(val,index){return this._cast(val,this.length+index)},push:function(){var values=[].map.call(arguments,this._mapCast,this);values=this._schema.applySetters(values,this._parent,undefined,undefined,{skipDocumentArrayCast:true});var ret=[].push.apply(this,values);this._registerAtomic("$pushAll",values);this._markModified();return ret},nonAtomicPush:function(){var values=[].map.call(arguments,this._mapCast,this);var ret=[].push.apply(this,values);this._registerAtomic("$set",this);this._markModified();return ret},$pop:function(){this._registerAtomic("$pop",1);this._markModified();if(this._popped){return}this._popped=true;return[].pop.call(this)},pop:function(){var ret=[].pop.call(this);this._registerAtomic("$set",this);this._markModified();return ret},$shift:function $shift(){this._registerAtomic("$pop",-1);this._markModified();if(this._shifted){return}this._shifted=true;return[].shift.call(this)},shift:function(){var ret=[].shift.call(this);this._registerAtomic("$set",this);this._markModified();return ret},pull:function(){var values=[].map.call(arguments,this._cast,this),cur=this._parent.get(this._path),i=cur.length,mem;while(i--){mem=cur[i];if(mem instanceof Document){var some=values.some(function(v){return v.equals(mem)});if(some){[].splice.call(cur,i,1)}}else if(~cur.indexOf.call(values,mem)){[].splice.call(cur,i,1)}}if(values[0]instanceof EmbeddedDocument){this._registerAtomic("$pullDocs",values.map(function(v){return v._id||v}))}else{this._registerAtomic("$pullAll",values)}this._markModified();return this},splice:function splice(){var ret,vals,i;if(arguments.length){vals=[];for(i=0;i<arguments.length;++i){vals[i]=i<2?arguments[i]:this._cast(arguments[i],arguments[0]+(i-2))}ret=[].splice.apply(this,vals);this._registerAtomic("$set",this);this._markModified()}return ret},unshift:function(){var values=[].map.call(arguments,this._cast,this);values=this._schema.applySetters(values,this._parent);[].unshift.apply(this,values);this._registerAtomic("$set",this);this._markModified();return this.length},sort:function(){var ret=[].sort.apply(this,arguments);this._registerAtomic("$set",this);this._markModified();return ret},addToSet:function addToSet(){var values=[].map.call(arguments,this._mapCast,this);values=this._schema.applySetters(values,this._parent);var added=[];var type="";if(values[0]instanceof EmbeddedDocument){type="doc"}else if(values[0]instanceof Date){type="date"}values.forEach(function(v){var found;switch(type){case"doc":found=this.some(function(doc){return doc.equals(v)});break;case"date":var val=+v;found=this.some(function(d){return+d===val});break;default:found=~this.indexOf(v)}if(!found){[].push.call(this,v);this._registerAtomic("$addToSet",v);this._markModified();[].push.call(added,v)}},this);return added},set:function set(i,val){var value=this._cast(val,i);value=this._schema.caster instanceof EmbeddedDocument?value:this._schema.caster.applySetters(val,this._parent);this[i]=value;this._markModified(i);return this},toObject:function(options){if(options&&options.depopulate){return this.map(function(doc){return doc instanceof Document?doc.toObject(options):doc})}return this.slice()},inspect:function(){return JSON.stringify(this)},indexOf:function indexOf(obj){if(obj instanceof ObjectId){obj=obj.toString()}for(var i=0,len=this.length;i<len;++i){if(obj==this[i]){return i}}return-1}};MongooseArray.mixin.remove=MongooseArray.mixin.pull;module.exports=exports=MongooseArray}).call(this,require("buffer").Buffer)},{"../document":4,"../utils":47,"./embedded":43,"./objectid":45,buffer:91}],41:[function(require,module,exports){(function(Buffer){var Binary=require("../drivers").Binary,utils=require("../utils");function MongooseBuffer(value,encode,offset){var length=arguments.length;var val;if(length===0||arguments[0]===null||arguments[0]===undefined){val=0}else{val=value}var encoding;var path;var doc;if(Array.isArray(encode)){path=encode[0];doc=encode[1]}else{encoding=encode}var buf=new Buffer(val,encoding,offset);utils.decorate(buf,MongooseBuffer.mixin);buf.isMongooseBuffer=true;Object.defineProperties(buf,{validators:{value:[]},_path:{value:path},_parent:{value:doc}});if(doc&&typeof path==="string"){Object.defineProperty(buf,"_schema",{value:doc.schema.path(path)})}buf._subtype=0;return buf}MongooseBuffer.mixin={_parent:undefined,_subtype:undefined,_markModified:function(){var parent=this._parent;if(parent){parent.markModified(this._path)}return this},write:function(){var written=Buffer.prototype.write.apply(this,arguments);if(written>0){this._markModified()}return written},copy:function(target){var ret=Buffer.prototype.copy.apply(this,arguments);if(target&&target.isMongooseBuffer){target._markModified()}return ret}};("writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 "+"writeFloat writeDouble fill "+"utf8Write binaryWrite asciiWrite set "+"writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE "+"writeInt16LE writeInt16BE writeInt32LE writeInt32BE "+"writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE").split(" ").forEach(function(method){if(!Buffer.prototype[method]){return}MongooseBuffer.mixin[method]=function(){var ret=Buffer.prototype[method].apply(this,arguments);this._markModified();return ret}});MongooseBuffer.mixin.toObject=function(options){var subtype=typeof options==="number"?options:this._subtype||0;return new Binary(this,subtype)};MongooseBuffer.mixin.equals=function(other){if(!Buffer.isBuffer(other)){return false}if(this.length!==other.length){return false}for(var i=0;i<this.length;++i){if(this[i]!==other[i]){return false}}return true};MongooseBuffer.mixin.subtype=function(subtype){if(typeof subtype!=="number"){throw new TypeError("Invalid subtype. Expected a number")}if(this._subtype!==subtype){this._markModified()}this._subtype=subtype};MongooseBuffer.Binary=Binary;module.exports=MongooseBuffer}).call(this,require("buffer").Buffer)},{"../drivers":10,"../utils":47,buffer:91}],42:[function(require,module,exports){(function(Buffer){var MongooseArray=require("./array"),ObjectId=require("./objectid"),ObjectIdSchema=require("../schema/objectid"),utils=require("../utils"),Document=require("../document");function MongooseDocumentArray(values,path,doc){var arr=[].concat(values);var props={isMongooseArray:true,isMongooseDocumentArray:true,validators:[],_path:path,_atomics:{},_schema:void 0,_handlers:void 0};var tmp={};var keysMA=Object.keys(MongooseArray.mixin);for(var j=0;j<keysMA.length;++j){tmp[keysMA[j]]={enumerable:false,configurable:true,writable:true,value:MongooseArray.mixin[keysMA[j]]}}var keysMDA=Object.keys(MongooseDocumentArray.mixin);for(var i=0;i<keysMDA.length;++i){tmp[keysMDA[i]]={enumerable:false,configurable:true,writable:true,value:MongooseDocumentArray.mixin[keysMDA[i]]}}var keysP=Object.keys(props);for(var k=0;k<keysP.length;++k){tmp[keysP[k]]={enumerable:false,configurable:true,writable:true,value:props[keysP[k]]}}Object.defineProperties(arr,tmp);if(doc&&doc instanceof Document){arr._parent=doc;arr._schema=doc.schema.path(path);arr._handlers={isNew:arr.notify("isNew"),save:arr.notify("save")};doc.on("save",arr._handlers.save);doc.on("isNew",arr._handlers.isNew)}return arr}MongooseDocumentArray.mixin={_cast:function(value,index){if(value instanceof this._schema.casterConstructor){if(!(value.__parent&&value.__parentArray)){value.__parent=this._parent;value.__parentArray=this}value.__index=index;return value}if(Buffer.isBuffer(value)||value instanceof ObjectId||!utils.isObject(value)){value={_id:value}}return new this._schema.casterConstructor(value,this,undefined,undefined,index)},id:function(id){var casted,sid,_id;try{var casted_=ObjectIdSchema.prototype.cast.call({},id);if(casted_){casted=String(casted_)}}catch(e){casted=null}for(var i=0,l=this.length;i<l;i++){_id=this[i].get("_id");if(_id===null||typeof _id==="undefined"){continue}else if(_id instanceof Document){sid||(sid=String(id));if(sid==_id._id){return this[i]}}else if(!(_id instanceof ObjectId)){if(utils.deepEqual(id,_id)){return this[i]}}else if(casted==_id){return this[i]}}return null},toObject:function(options){return this.map(function(doc){return doc&&doc.toObject(options)||null})},inspect:function(){return Array.prototype.slice.call(this)},create:function(obj){return new this._schema.casterConstructor(obj)},notify:function notify(event){var _this=this;return function notify(val){var i=_this.length;while(i--){if(!_this[i]){continue}switch(event){case"save":val=_this[i];break;default:break}_this[i].emit(event,val)}}}};module.exports=MongooseDocumentArray}).call(this,require("buffer").Buffer)},{"../document":4,"../schema/objectid":35,"../utils":47,"./array":40,"./objectid":45,buffer:91}],43:[function(require,module,exports){var Document=require("../document_provider")();var PromiseProvider=require("../promise_provider");function EmbeddedDocument(obj,parentArr,skipId,fields,index){if(parentArr){this.__parentArray=parentArr;this.__parent=parentArr._parent}else{this.__parentArray=undefined;this.__parent=undefined}this.__index=index;Document.call(this,obj,fields,skipId);var _this=this;this.on("isNew",function(val){_this.isNew=val})}EmbeddedDocument.prototype=Object.create(Document.prototype);EmbeddedDocument.prototype.constructor=EmbeddedDocument;EmbeddedDocument.prototype.markModified=function(path){this.$__.activePaths.modify(path);if(!this.__parentArray){return}if(this.isNew){this.__parentArray._markModified()}else{this.__parentArray._markModified(this,path)}};EmbeddedDocument.prototype.save=function(fn){var Promise=PromiseProvider.get();return new Promise.ES6(function(resolve){fn&&fn();resolve()})};function registerRemoveListener(sub){var owner=sub.ownerDocument();function emitRemove(){owner.removeListener("save",emitRemove);owner.removeListener("remove",emitRemove);sub.emit("remove",sub);owner=sub=null}owner.on("save",emitRemove);owner.on("remove",emitRemove)}EmbeddedDocument.prototype.remove=function(fn){if(!this.__parentArray){return this}var _id;if(!this.willRemove){_id=this._doc._id;if(!_id){throw new Error("For your own good, Mongoose does not know "+"how to remove an EmbeddedDocument that has no _id")}this.__parentArray.pull({_id:_id});this.willRemove=true;registerRemoveListener(this)}if(fn){fn(null)}return this};EmbeddedDocument.prototype.update=function(){throw new Error("The #update method is not available on EmbeddedDocuments")};EmbeddedDocument.prototype.inspect=function(){return this.toObject()};EmbeddedDocument.prototype.invalidate=function(path,err,val,first){if(!this.__parent){var msg="Unable to invalidate a subdocument that has not been added to an array.";throw new Error(msg)}var index=this.__index;if(typeof index!=="undefined"){var parentPath=this.__parentArray._path;var fullPath=[parentPath,index,path].join(".");this.__parent.invalidate(fullPath,err,val)}if(first){this.$__.validationError=this.ownerDocument().$__.validationError}return true};EmbeddedDocument.prototype.$markValid=function(path){if(!this.__parent){return}var index=this.__index;if(typeof index!=="undefined"){var parentPath=this.__parentArray._path;var fullPath=[parentPath,index,path].join(".");this.__parent.$markValid(fullPath)}};EmbeddedDocument.prototype.$isValid=function(path){var index=this.__index;if(typeof index!=="undefined"){return!this.__parent.$__.validationError||!this.__parent.$__.validationError.errors[path]}return true};EmbeddedDocument.prototype.ownerDocument=function(){if(this.$__.ownerDocument){return this.$__.ownerDocument}var parent=this.__parent;if(!parent){return this}while(parent.__parent){parent=parent.__parent}this.$__.ownerDocument=parent;return this.$__.ownerDocument};EmbeddedDocument.prototype.$__fullPath=function(path){if(!this.$__.fullPath){var parent=this;if(!parent.__parent){return path}var paths=[];while(parent.__parent){paths.unshift(parent.__parentArray._path);parent=parent.__parent}this.$__.fullPath=paths.join(".");if(!this.$__.ownerDocument){this.$__.ownerDocument=parent}}return path?this.$__.fullPath+"."+path:this.$__.fullPath};EmbeddedDocument.prototype.parent=function(){return this.__parent};EmbeddedDocument.prototype.parentArray=function(){return this.__parentArray};module.exports=EmbeddedDocument},{"../document_provider":5,"../promise_provider":24}],44:[function(require,module,exports){exports.Array=require("./array");exports.Buffer=require("./buffer");exports.Document=exports.Embedded=require("./embedded");exports.DocumentArray=require("./documentarray");exports.ObjectId=require("./objectid");exports.Subdocument=require("./subdocument")},{"./array":40,"./buffer":41,"./documentarray":42,"./embedded":43,"./objectid":45,"./subdocument":46}],45:[function(require,module,exports){var ObjectId=require("../drivers").ObjectId;module.exports=ObjectId},{"../drivers":10}],46:[function(require,module,exports){var Document=require("../document");var PromiseProvider=require("../promise_provider");module.exports=Subdocument;function Subdocument(){Document.apply(this,arguments);this.$isSingleNested=true}Subdocument.prototype=Object.create(Document.prototype);Subdocument.prototype.save=function(fn){var Promise=PromiseProvider.get();return new Promise.ES6(function(resolve){fn&&fn();resolve()})};Subdocument.prototype.$isValid=function(path){if(this.$parent){return this.$parent.$isValid([this.$basePath,path].join("."))}};Subdocument.prototype.markModified=function(path){if(this.$parent){this.$parent.markModified([this.$basePath,path].join("."))}};Subdocument.prototype.$markValid=function(path){if(this.$parent){this.$parent.$markValid([this.$basePath,path].join("."))}};Subdocument.prototype.invalidate=function(path,err,val){if(this.$parent){this.$parent.invalidate([this.$basePath,path].join("."),err,val)}else if(err.kind==="cast"||err.name==="CastError"){throw err}};Subdocument.prototype.ownerDocument=function(){if(this.$__.ownerDocument){return this.$__.ownerDocument}var parent=this.$parent;if(!parent){return this}while(parent.$parent){parent=parent.$parent}this.$__.ownerDocument=parent;return this.$__.ownerDocument};Subdocument.prototype.remove=function(callback){this.$parent.set(this.$basePath,null);registerRemoveListener(this);if(callback){callback(null)}};function registerRemoveListener(sub){var owner=sub.ownerDocument();function emitRemove(){owner.removeListener("save",emitRemove);owner.removeListener("remove",emitRemove);sub.emit("remove",sub);owner=sub=null}owner.on("save",emitRemove);owner.on("remove",emitRemove)}},{"../document":4,"../promise_provider":24}],47:[function(require,module,exports){(function(process,Buffer){var ObjectId=require("./types/objectid");var cloneRegExp=require("regexp-clone");var sliced=require("sliced");var mpath=require("mpath");var ms=require("ms");var MongooseBuffer;var MongooseArray;var Document;exports.toCollectionName=function(name,options){options=options||{};if(name==="system.profile"){return name}if(name==="system.indexes"){return name}if(options.pluralization===false){return name}return pluralize(name.toLowerCase())};exports.pluralization=[[/(m)an$/gi,"$1en"],[/(pe)rson$/gi,"$1ople"],[/(child)$/gi,"$1ren"],[/^(ox)$/gi,"$1en"],[/(ax|test)is$/gi,"$1es"],[/(octop|vir)us$/gi,"$1i"],[/(alias|status)$/gi,"$1es"],[/(bu)s$/gi,"$1ses"],[/(buffal|tomat|potat)o$/gi,"$1oes"],[/([ti])um$/gi,"$1a"],[/sis$/gi,"ses"],[/(?:([^f])fe|([lr])f)$/gi,"$1$2ves"],[/(hive)$/gi,"$1s"],[/([^aeiouy]|qu)y$/gi,"$1ies"],[/(x|ch|ss|sh)$/gi,"$1es"],[/(matr|vert|ind)ix|ex$/gi,"$1ices"],[/([m|l])ouse$/gi,"$1ice"],[/(kn|w|l)ife$/gi,"$1ives"],[/(quiz)$/gi,"$1zes"],[/s$/gi,"s"],[/([^a-z])$/,"$1"],[/$/gi,"s"]];var rules=exports.pluralization;exports.uncountables=["advice","energy","excretion","digestion","cooperation","health","justice","labour","machinery","equipment","information","pollution","sewage","paper","money","species","series","rain","rice","fish","sheep","moose","deer","news","expertise","status","media"];var uncountables=exports.uncountables;function pluralize(str){var found;if(!~uncountables.indexOf(str.toLowerCase())){found=rules.filter(function(rule){return str.match(rule[0])});if(found[0]){return str.replace(found[0][0],found[0][1])}}return str}exports.deepEqual=function deepEqual(a,b){if(a===b){return true}if(a instanceof Date&&b instanceof Date){return a.getTime()===b.getTime()}if(a instanceof ObjectId&&b instanceof ObjectId){return a.toString()===b.toString()}if(a instanceof RegExp&&b instanceof RegExp){return a.source===b.source&&a.ignoreCase===b.ignoreCase&&a.multiline===b.multiline&&a.global===b.global}if(typeof a!=="object"&&typeof b!=="object"){return a==b}if(a===null||b===null||a===undefined||b===undefined){return false}if(a.prototype!==b.prototype){return false}if(a instanceof Number&&b instanceof Number){return a.valueOf()===b.valueOf()}if(Buffer.isBuffer(a)){return exports.buffer.areEqual(a,b)}if(isMongooseObject(a)){a=a.toObject()}if(isMongooseObject(b)){b=b.toObject()}try{var ka=Object.keys(a),kb=Object.keys(b),key,i}catch(e){return false}if(ka.length!==kb.length){return false}ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!==kb[i]){return false}}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!deepEqual(a[key],b[key])){return false}}return true};exports.clone=function clone(obj,options){if(obj===undefined||obj===null){return obj}if(Array.isArray(obj)){return cloneArray(obj,options)}if(isMongooseObject(obj)){if(options&&options.json&&typeof obj.toJSON==="function"){return obj.toJSON(options)}return obj.toObject(options)}if(obj.constructor){switch(exports.getFunctionName(obj.constructor)){case"Object":return cloneObject(obj,options);case"Date":return new obj.constructor(+obj);case"RegExp":return cloneRegExp(obj);default:break}}if(obj instanceof ObjectId){return new ObjectId(obj.id)}if(!obj.constructor&&exports.isObject(obj)){return cloneObject(obj,options)}if(obj.valueOf){return obj.valueOf()}};var clone=exports.clone;function cloneObject(obj,options){var retainKeyOrder=options&&options.retainKeyOrder,minimize=options&&options.minimize,ret={},hasKeys,keys,val,k,i;if(retainKeyOrder){for(k in obj){val=clone(obj[k],options);if(!minimize||typeof val!=="undefined"){hasKeys||(hasKeys=true);ret[k]=val}}}else{keys=Object.keys(obj);i=keys.length;while(i--){k=keys[i];val=clone(obj[k],options);if(!minimize||typeof val!=="undefined"){if(!hasKeys){hasKeys=true}ret[k]=val}}}return minimize?hasKeys&&ret:ret}function cloneArray(arr,options){var ret=[];for(var i=0,l=arr.length;i<l;i++){ret.push(clone(arr[i],options))}return ret}exports.options=function(defaults,options){var keys=Object.keys(defaults),i=keys.length,k;options=options||{};while(i--){k=keys[i];if(!(k in options)){options[k]=defaults[k]}}return options};exports.random=function(){return Math.random().toString().substr(3)};exports.merge=function merge(to,from){var keys=Object.keys(from),i=keys.length,key;while(i--){key=keys[i];if(typeof to[key]==="undefined"){to[key]=from[key]}else if(exports.isObject(from[key])){merge(to[key],from[key])}}};var toString=Object.prototype.toString;exports.toObject=function toObject(obj){var ret;if(exports.isNullOrUndefined(obj)){return obj}if(obj instanceof Document){return obj.toObject()}if(Array.isArray(obj)){ret=[];for(var i=0,len=obj.length;i<len;++i){ret.push(toObject(obj[i]))}return ret}if(obj.constructor&&exports.getFunctionName(obj.constructor)==="Object"||!obj.constructor&&exports.isObject(obj)){ret={};for(var k in obj){ret[k]=toObject(obj[k])}return ret}return obj};exports.isObject=function(arg){if(Buffer.isBuffer(arg)){return true}return toString.call(arg)==="[object Object]"};exports.args=sliced;exports.tick=function tick(callback){if(typeof callback!=="function"){return}return function(){try{callback.apply(this,arguments)}catch(err){process.nextTick(function(){throw err})}}};exports.isMongooseObject=function(v){Document||(Document=require("./document"));MongooseArray||(MongooseArray=require("./types").Array);MongooseBuffer||(MongooseBuffer=require("./types").Buffer);return v instanceof Document||v&&v.isMongooseArray||v&&v.isMongooseBuffer};var isMongooseObject=exports.isMongooseObject;exports.expires=function expires(object){if(!(object&&object.constructor.name==="Object")){return}if(!("expires"in object)){return}var when;if(typeof object.expires!=="string"){when=object.expires}else{when=Math.round(ms(object.expires)/1e3)}object.expireAfterSeconds=when;delete object.expires};function PopulateOptions(path,select,match,options,model,subPopulate){this.path=path;this.match=match;this.select=select;this.options=options;this.model=model;if(typeof subPopulate==="object"){this.populate=subPopulate}this._docs={}}PopulateOptions.prototype.constructor=Object;exports.PopulateOptions=PopulateOptions;exports.populate=function populate(path,select,model,match,options,subPopulate){if(arguments.length===1){if(path instanceof PopulateOptions){return[path]}if(Array.isArray(path)){return path.map(function(o){return exports.populate(o)[0]})}if(exports.isObject(path)){match=path.match;options=path.options;select=path.select;model=path.model;subPopulate=path.populate;path=path.path}}else if(typeof model!=="string"&&typeof model!=="function"){options=match;match=model;model=undefined}if(typeof path!=="string"){throw new TypeError("utils.populate: invalid path. Expected string. Got typeof `"+typeof path+"`")}if(typeof subPopulate==="object"){subPopulate=exports.populate(subPopulate)}var ret=[];var paths=path.split(" ");for(var i=0;i<paths.length;++i){ret.push(new PopulateOptions(paths[i],select,match,options,model,subPopulate))}return ret};exports.getValue=function(path,obj,map){return mpath.get(path,obj,"_doc",map)};exports.setValue=function(path,val,obj,map){mpath.set(path,val,obj,"_doc",map)};exports.object={};exports.object.vals=function vals(o){var keys=Object.keys(o),i=keys.length,ret=[];while(i--){ret.push(o[keys[i]])}return ret};exports.object.shallowCopy=exports.options;var hop=Object.prototype.hasOwnProperty;exports.object.hasOwnProperty=function(obj,prop){return hop.call(obj,prop)};exports.isNullOrUndefined=function(val){return val===null||val===undefined};exports.array={};exports.array.flatten=function flatten(arr,filter,ret){ret||(ret=[]);arr.forEach(function(item){if(Array.isArray(item)){flatten(item,filter,ret)}else{if(!filter||filter(item)){ret.push(item)}}});return ret};exports.array.unique=function(arr){var primitives={};var ids={};var ret=[];var length=arr.length;for(var i=0;i<length;++i){if(typeof arr[i]==="number"||typeof arr[i]==="string"){if(primitives[arr[i]]){continue}ret.push(arr[i]);primitives[arr[i]]=true}else if(arr[i]instanceof ObjectId){if(ids[arr[i].toString()]){continue}ret.push(arr[i]);ids[arr[i].toString()]=true}else{ret.push(arr[i])}}return ret};exports.buffer={};exports.buffer.areEqual=function(a,b){if(!Buffer.isBuffer(a)){return false}if(!Buffer.isBuffer(b)){return false}if(a.length!==b.length){return false}for(var i=0,len=a.length;i<len;++i){if(a[i]!==b[i]){return false}}return true};exports.getFunctionName=function(fn){if(fn.name){return fn.name}return(fn.toString().trim().match(/^function\s*([^\s(]+)/)||[])[1]};exports.decorate=function(destination,source){for(var key in source){destination[key]=source[key]}};exports.mergeClone=function(to,from){var keys=Object.keys(from),i=keys.length,key;while(i--){key=keys[i];if(typeof to[key]==="undefined"){to[key]=exports.clone(from[key],{retainKeyOrder:1})}else{if(exports.isObject(from[key])){exports.mergeClone(to[key],from[key])}else{to[key]=exports.clone(from[key],{retainKeyOrder:1})}}}};exports.each=function(arr,fn){for(var i=0;i<arr.length;++i){fn(arr[i])}}}).call(this,require("_process"),require("buffer").Buffer)},{"./document":4,"./types":44,"./types/objectid":45,_process:96,buffer:91,mpath:70,ms:85,"regexp-clone":86,sliced:87}],48:[function(require,module,exports){function VirtualType(options,name){this.path=name;this.getters=[];this.setters=[];this.options=options||{}}VirtualType.prototype.get=function(fn){this.getters.push(fn);return this};VirtualType.prototype.set=function(fn){this.setters.push(fn);return this};VirtualType.prototype.applyGetters=function(value,scope){var v=value;for(var l=this.getters.length-1;l>=0;l--){v=this.getters[l].call(scope,v,this)}return v};VirtualType.prototype.applySetters=function(value,scope){var v=value;for(var l=this.setters.length-1;l>=0;l--){v=this.setters[l].call(scope,v,this)}return v};module.exports=VirtualType},{}],49:[function(require,module,exports){(function(process,global){(function(){var async={};function noop(){}function identity(v){return v}function toBool(v){
return!!v}function notId(v){return!v}var previous_async;var root=typeof self==="object"&&self.self===self&&self||typeof global==="object"&&global.global===global&&global||this;if(root!=null){previous_async=root.async}async.noConflict=function(){root.async=previous_async;return async};function only_once(fn){return function(){if(fn===null)throw new Error("Callback was already called.");fn.apply(this,arguments);fn=null}}function _once(fn){return function(){if(fn===null)return;fn.apply(this,arguments);fn=null}}var _toString=Object.prototype.toString;var _isArray=Array.isArray||function(obj){return _toString.call(obj)==="[object Array]"};var _isObject=function(obj){var type=typeof obj;return type==="function"||type==="object"&&!!obj};function _isArrayLike(arr){return _isArray(arr)||typeof arr.length==="number"&&arr.length>=0&&arr.length%1===0}function _arrayEach(arr,iterator){var index=-1,length=arr.length;while(++index<length){iterator(arr[index],index,arr)}}function _map(arr,iterator){var index=-1,length=arr.length,result=Array(length);while(++index<length){result[index]=iterator(arr[index],index,arr)}return result}function _range(count){return _map(Array(count),function(v,i){return i})}function _reduce(arr,iterator,memo){_arrayEach(arr,function(x,i,a){memo=iterator(memo,x,i,a)});return memo}function _forEachOf(object,iterator){_arrayEach(_keys(object),function(key){iterator(object[key],key)})}function _indexOf(arr,item){for(var i=0;i<arr.length;i++){if(arr[i]===item)return i}return-1}var _keys=Object.keys||function(obj){var keys=[];for(var k in obj){if(obj.hasOwnProperty(k)){keys.push(k)}}return keys};function _keyIterator(coll){var i=-1;var len;var keys;if(_isArrayLike(coll)){len=coll.length;return function next(){i++;return i<len?i:null}}else{keys=_keys(coll);len=keys.length;return function next(){i++;return i<len?keys[i]:null}}}function _restParam(func,startIndex){startIndex=startIndex==null?func.length-1:+startIndex;return function(){var length=Math.max(arguments.length-startIndex,0);var rest=Array(length);for(var index=0;index<length;index++){rest[index]=arguments[index+startIndex]}switch(startIndex){case 0:return func.call(this,rest);case 1:return func.call(this,arguments[0],rest)}}}function _withoutIndex(iterator){return function(value,index,callback){return iterator(value,callback)}}var _setImmediate=typeof setImmediate==="function"&&setImmediate;var _delay=_setImmediate?function(fn){_setImmediate(fn)}:function(fn){setTimeout(fn,0)};if(typeof process==="object"&&typeof process.nextTick==="function"){async.nextTick=process.nextTick}else{async.nextTick=_delay}async.setImmediate=_setImmediate?_delay:async.nextTick;async.forEach=async.each=function(arr,iterator,callback){return async.eachOf(arr,_withoutIndex(iterator),callback)};async.forEachSeries=async.eachSeries=function(arr,iterator,callback){return async.eachOfSeries(arr,_withoutIndex(iterator),callback)};async.forEachLimit=async.eachLimit=function(arr,limit,iterator,callback){return _eachOfLimit(limit)(arr,_withoutIndex(iterator),callback)};async.forEachOf=async.eachOf=function(object,iterator,callback){callback=_once(callback||noop);object=object||[];var iter=_keyIterator(object);var key,completed=0;while((key=iter())!=null){completed+=1;iterator(object[key],key,only_once(done))}if(completed===0)callback(null);function done(err){completed--;if(err){callback(err)}else if(key===null&&completed<=0){callback(null)}}};async.forEachOfSeries=async.eachOfSeries=function(obj,iterator,callback){callback=_once(callback||noop);obj=obj||[];var nextKey=_keyIterator(obj);var key=nextKey();function iterate(){var sync=true;if(key===null){return callback(null)}iterator(obj[key],key,only_once(function(err){if(err){callback(err)}else{key=nextKey();if(key===null){return callback(null)}else{if(sync){async.setImmediate(iterate)}else{iterate()}}}}));sync=false}iterate()};async.forEachOfLimit=async.eachOfLimit=function(obj,limit,iterator,callback){_eachOfLimit(limit)(obj,iterator,callback)};function _eachOfLimit(limit){return function(obj,iterator,callback){callback=_once(callback||noop);obj=obj||[];var nextKey=_keyIterator(obj);if(limit<=0){return callback(null)}var done=false;var running=0;var errored=false;(function replenish(){if(done&&running<=0){return callback(null)}while(running<limit&&!errored){var key=nextKey();if(key===null){done=true;if(running<=0){callback(null)}return}running+=1;iterator(obj[key],key,only_once(function(err){running-=1;if(err){callback(err);errored=true}else{replenish()}}))}})()}}function doParallel(fn){return function(obj,iterator,callback){return fn(async.eachOf,obj,iterator,callback)}}function doParallelLimit(fn){return function(obj,limit,iterator,callback){return fn(_eachOfLimit(limit),obj,iterator,callback)}}function doSeries(fn){return function(obj,iterator,callback){return fn(async.eachOfSeries,obj,iterator,callback)}}function _asyncMap(eachfn,arr,iterator,callback){callback=_once(callback||noop);arr=arr||[];var results=_isArrayLike(arr)?[]:{};eachfn(arr,function(value,index,callback){iterator(value,function(err,v){results[index]=v;callback(err)})},function(err){callback(err,results)})}async.map=doParallel(_asyncMap);async.mapSeries=doSeries(_asyncMap);async.mapLimit=doParallelLimit(_asyncMap);async.inject=async.foldl=async.reduce=function(arr,memo,iterator,callback){async.eachOfSeries(arr,function(x,i,callback){iterator(memo,x,function(err,v){memo=v;callback(err)})},function(err){callback(err,memo)})};async.foldr=async.reduceRight=function(arr,memo,iterator,callback){var reversed=_map(arr,identity).reverse();async.reduce(reversed,memo,iterator,callback)};async.transform=function(arr,memo,iterator,callback){if(arguments.length===3){callback=iterator;iterator=memo;memo=_isArray(arr)?[]:{}}async.eachOf(arr,function(v,k,cb){iterator(memo,v,k,cb)},function(err){callback(err,memo)})};function _filter(eachfn,arr,iterator,callback){var results=[];eachfn(arr,function(x,index,callback){iterator(x,function(v){if(v){results.push({index:index,value:x})}callback()})},function(){callback(_map(results.sort(function(a,b){return a.index-b.index}),function(x){return x.value}))})}async.select=async.filter=doParallel(_filter);async.selectLimit=async.filterLimit=doParallelLimit(_filter);async.selectSeries=async.filterSeries=doSeries(_filter);function _reject(eachfn,arr,iterator,callback){_filter(eachfn,arr,function(value,cb){iterator(value,function(v){cb(!v)})},callback)}async.reject=doParallel(_reject);async.rejectLimit=doParallelLimit(_reject);async.rejectSeries=doSeries(_reject);function _createTester(eachfn,check,getResult){return function(arr,limit,iterator,cb){function done(){if(cb)cb(getResult(false,void 0))}function iteratee(x,_,callback){if(!cb)return callback();iterator(x,function(v){if(cb&&check(v)){cb(getResult(true,x));cb=iterator=false}callback()})}if(arguments.length>3){eachfn(arr,limit,iteratee,done)}else{cb=iterator;iterator=limit;eachfn(arr,iteratee,done)}}}async.any=async.some=_createTester(async.eachOf,toBool,identity);async.someLimit=_createTester(async.eachOfLimit,toBool,identity);async.all=async.every=_createTester(async.eachOf,notId,notId);async.everyLimit=_createTester(async.eachOfLimit,notId,notId);function _findGetResult(v,x){return x}async.detect=_createTester(async.eachOf,identity,_findGetResult);async.detectSeries=_createTester(async.eachOfSeries,identity,_findGetResult);async.detectLimit=_createTester(async.eachOfLimit,identity,_findGetResult);async.sortBy=function(arr,iterator,callback){async.map(arr,function(x,callback){iterator(x,function(err,criteria){if(err){callback(err)}else{callback(null,{value:x,criteria:criteria})}})},function(err,results){if(err){return callback(err)}else{callback(null,_map(results.sort(comparator),function(x){return x.value}))}});function comparator(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0}};async.auto=function(tasks,concurrency,callback){if(typeof arguments[1]==="function"){callback=concurrency;concurrency=null}callback=_once(callback||noop);var keys=_keys(tasks);var remainingTasks=keys.length;if(!remainingTasks){return callback(null)}if(!concurrency){concurrency=remainingTasks}var results={};var runningTasks=0;var hasError=false;var listeners=[];function addListener(fn){listeners.unshift(fn)}function removeListener(fn){var idx=_indexOf(listeners,fn);if(idx>=0)listeners.splice(idx,1)}function taskComplete(){remainingTasks--;_arrayEach(listeners.slice(0),function(fn){fn()})}addListener(function(){if(!remainingTasks){callback(null,results)}});_arrayEach(keys,function(k){if(hasError)return;var task=_isArray(tasks[k])?tasks[k]:[tasks[k]];var taskCallback=_restParam(function(err,args){runningTasks--;if(args.length<=1){args=args[0]}if(err){var safeResults={};_forEachOf(results,function(val,rkey){safeResults[rkey]=val});safeResults[k]=args;hasError=true;callback(err,safeResults)}else{results[k]=args;async.setImmediate(taskComplete)}});var requires=task.slice(0,task.length-1);var len=requires.length;var dep;while(len--){if(!(dep=tasks[requires[len]])){throw new Error("Has nonexistent dependency in "+requires.join(", "))}if(_isArray(dep)&&_indexOf(dep,k)>=0){throw new Error("Has cyclic dependencies")}}function ready(){return runningTasks<concurrency&&_reduce(requires,function(a,x){return a&&results.hasOwnProperty(x)},true)&&!results.hasOwnProperty(k)}if(ready()){runningTasks++;task[task.length-1](taskCallback,results)}else{addListener(listener)}function listener(){if(ready()){runningTasks++;removeListener(listener);task[task.length-1](taskCallback,results)}}})};async.retry=function(times,task,callback){var DEFAULT_TIMES=5;var DEFAULT_INTERVAL=0;var attempts=[];var opts={times:DEFAULT_TIMES,interval:DEFAULT_INTERVAL};function parseTimes(acc,t){if(typeof t==="number"){acc.times=parseInt(t,10)||DEFAULT_TIMES}else if(typeof t==="object"){acc.times=parseInt(t.times,10)||DEFAULT_TIMES;acc.interval=parseInt(t.interval,10)||DEFAULT_INTERVAL}else{throw new Error("Unsupported argument type for 'times': "+typeof t)}}var length=arguments.length;if(length<1||length>3){throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)")}else if(length<=2&&typeof times==="function"){callback=task;task=times}if(typeof times!=="function"){parseTimes(opts,times)}opts.callback=callback;opts.task=task;function wrappedTask(wrappedCallback,wrappedResults){function retryAttempt(task,finalAttempt){return function(seriesCallback){task(function(err,result){seriesCallback(!err||finalAttempt,{err:err,result:result})},wrappedResults)}}function retryInterval(interval){return function(seriesCallback){setTimeout(function(){seriesCallback(null)},interval)}}while(opts.times){var finalAttempt=!(opts.times-=1);attempts.push(retryAttempt(opts.task,finalAttempt));if(!finalAttempt&&opts.interval>0){attempts.push(retryInterval(opts.interval))}}async.series(attempts,function(done,data){data=data[data.length-1];(wrappedCallback||opts.callback)(data.err,data.result)})}return opts.callback?wrappedTask():wrappedTask};async.waterfall=function(tasks,callback){callback=_once(callback||noop);if(!_isArray(tasks)){var err=new Error("First argument to waterfall must be an array of functions");return callback(err)}if(!tasks.length){return callback()}function wrapIterator(iterator){return _restParam(function(err,args){if(err){callback.apply(null,[err].concat(args))}else{var next=iterator.next();if(next){args.push(wrapIterator(next))}else{args.push(callback)}ensureAsync(iterator).apply(null,args)}})}wrapIterator(async.iterator(tasks))()};function _parallel(eachfn,tasks,callback){callback=callback||noop;var results=_isArrayLike(tasks)?[]:{};eachfn(tasks,function(task,key,callback){task(_restParam(function(err,args){if(args.length<=1){args=args[0]}results[key]=args;callback(err)}))},function(err){callback(err,results)})}async.parallel=function(tasks,callback){_parallel(async.eachOf,tasks,callback)};async.parallelLimit=function(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)};async.series=function(tasks,callback){_parallel(async.eachOfSeries,tasks,callback)};async.iterator=function(tasks){function makeCallback(index){function fn(){if(tasks.length){tasks[index].apply(null,arguments)}return fn.next()}fn.next=function(){return index<tasks.length-1?makeCallback(index+1):null};return fn}return makeCallback(0)};async.apply=_restParam(function(fn,args){return _restParam(function(callArgs){return fn.apply(null,args.concat(callArgs))})});function _concat(eachfn,arr,fn,callback){var result=[];eachfn(arr,function(x,index,cb){fn(x,function(err,y){result=result.concat(y||[]);cb(err)})},function(err){callback(err,result)})}async.concat=doParallel(_concat);async.concatSeries=doSeries(_concat);async.whilst=function(test,iterator,callback){callback=callback||noop;if(test()){var next=_restParam(function(err,args){if(err){callback(err)}else if(test.apply(this,args)){iterator(next)}else{callback.apply(null,[null].concat(args))}});iterator(next)}else{callback(null)}};async.doWhilst=function(iterator,test,callback){var calls=0;return async.whilst(function(){return++calls<=1||test.apply(this,arguments)},iterator,callback)};async.until=function(test,iterator,callback){return async.whilst(function(){return!test.apply(this,arguments)},iterator,callback)};async.doUntil=function(iterator,test,callback){return async.doWhilst(iterator,function(){return!test.apply(this,arguments)},callback)};async.during=function(test,iterator,callback){callback=callback||noop;var next=_restParam(function(err,args){if(err){callback(err)}else{args.push(check);test.apply(this,args)}});var check=function(err,truth){if(err){callback(err)}else if(truth){iterator(next)}else{callback(null)}};test(check)};async.doDuring=function(iterator,test,callback){var calls=0;async.during(function(next){if(calls++<1){next(null,true)}else{test.apply(this,arguments)}},iterator,callback)};function _queue(worker,concurrency,payload){if(concurrency==null){concurrency=1}else if(concurrency===0){throw new Error("Concurrency must not be zero")}function _insert(q,data,pos,callback){if(callback!=null&&typeof callback!=="function"){throw new Error("task callback must be a function")}q.started=true;if(!_isArray(data)){data=[data]}if(data.length===0&&q.idle()){return async.setImmediate(function(){q.drain()})}_arrayEach(data,function(task){var item={data:task,callback:callback||noop};if(pos){q.tasks.unshift(item)}else{q.tasks.push(item)}if(q.tasks.length===q.concurrency){q.saturated()}});async.setImmediate(q.process)}function _next(q,tasks){return function(){workers-=1;var removed=false;var args=arguments;_arrayEach(tasks,function(task){_arrayEach(workersList,function(worker,index){if(worker===task&&!removed){workersList.splice(index,1);removed=true}});task.callback.apply(task,args)});if(q.tasks.length+workers===0){q.drain()}q.process()}}var workers=0;var workersList=[];var q={tasks:[],concurrency:concurrency,payload:payload,saturated:noop,empty:noop,drain:noop,started:false,paused:false,push:function(data,callback){_insert(q,data,false,callback)},kill:function(){q.drain=noop;q.tasks=[]},unshift:function(data,callback){_insert(q,data,true,callback)},process:function(){while(!q.paused&&workers<q.concurrency&&q.tasks.length){var tasks=q.payload?q.tasks.splice(0,q.payload):q.tasks.splice(0,q.tasks.length);var data=_map(tasks,function(task){return task.data});if(q.tasks.length===0){q.empty()}workers+=1;workersList.push(tasks[0]);var cb=only_once(_next(q,tasks));worker(data,cb)}},length:function(){return q.tasks.length},running:function(){return workers},workersList:function(){return workersList},idle:function(){return q.tasks.length+workers===0},pause:function(){q.paused=true},resume:function(){if(q.paused===false){return}q.paused=false;var resumeCount=Math.min(q.concurrency,q.tasks.length);for(var w=1;w<=resumeCount;w++){async.setImmediate(q.process)}}};return q}async.queue=function(worker,concurrency){var q=_queue(function(items,cb){worker(items[0],cb)},concurrency,1);return q};async.priorityQueue=function(worker,concurrency){function _compareTasks(a,b){return a.priority-b.priority}function _binarySearch(sequence,item,compare){var beg=-1,end=sequence.length-1;while(beg<end){var mid=beg+(end-beg+1>>>1);if(compare(item,sequence[mid])>=0){beg=mid}else{end=mid-1}}return beg}function _insert(q,data,priority,callback){if(callback!=null&&typeof callback!=="function"){throw new Error("task callback must be a function")}q.started=true;if(!_isArray(data)){data=[data]}if(data.length===0){return async.setImmediate(function(){q.drain()})}_arrayEach(data,function(task){var item={data:task,priority:priority,callback:typeof callback==="function"?callback:noop};q.tasks.splice(_binarySearch(q.tasks,item,_compareTasks)+1,0,item);if(q.tasks.length===q.concurrency){q.saturated()}async.setImmediate(q.process)})}var q=async.queue(worker,concurrency);q.push=function(data,priority,callback){_insert(q,data,priority,callback)};delete q.unshift;return q};async.cargo=function(worker,payload){return _queue(worker,1,payload)};function _console_fn(name){return _restParam(function(fn,args){fn.apply(null,args.concat([_restParam(function(err,args){if(typeof console==="object"){if(err){if(console.error){console.error(err)}}else if(console[name]){_arrayEach(args,function(x){console[name](x)})}}})]))})}async.log=_console_fn("log");async.dir=_console_fn("dir");async.memoize=function(fn,hasher){var memo={};var queues={};var has=Object.prototype.hasOwnProperty;hasher=hasher||identity;var memoized=_restParam(function memoized(args){var callback=args.pop();var key=hasher.apply(null,args);if(has.call(memo,key)){async.setImmediate(function(){callback.apply(null,memo[key])})}else if(has.call(queues,key)){queues[key].push(callback)}else{queues[key]=[callback];fn.apply(null,args.concat([_restParam(function(args){memo[key]=args;var q=queues[key];delete queues[key];for(var i=0,l=q.length;i<l;i++){q[i].apply(null,args)}})]))}});memoized.memo=memo;memoized.unmemoized=fn;return memoized};async.unmemoize=function(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}};function _times(mapper){return function(count,iterator,callback){mapper(_range(count),iterator,callback)}}async.times=_times(async.map);async.timesSeries=_times(async.mapSeries);async.timesLimit=function(count,limit,iterator,callback){return async.mapLimit(_range(count),limit,iterator,callback)};async.seq=function(){var fns=arguments;return _restParam(function(args){var that=this;var callback=args[args.length-1];if(typeof callback=="function"){args.pop()}else{callback=noop}async.reduce(fns,args,function(newargs,fn,cb){fn.apply(that,newargs.concat([_restParam(function(err,nextargs){cb(err,nextargs)})]))},function(err,results){callback.apply(that,[err].concat(results))})})};async.compose=function(){return async.seq.apply(null,Array.prototype.reverse.call(arguments))};function _applyEach(eachfn){return _restParam(function(fns,args){var go=_restParam(function(args){var that=this;var callback=args.pop();return eachfn(fns,function(fn,_,cb){fn.apply(that,args.concat([cb]))},callback)});if(args.length){return go.apply(this,args)}else{return go}})}async.applyEach=_applyEach(async.eachOf);async.applyEachSeries=_applyEach(async.eachOfSeries);async.forever=function(fn,callback){var done=only_once(callback||noop);var task=ensureAsync(fn);function next(err){if(err){return done(err)}task(next)}next()};function ensureAsync(fn){return _restParam(function(args){var callback=args.pop();args.push(function(){var innerArgs=arguments;if(sync){async.setImmediate(function(){callback.apply(null,innerArgs)})}else{callback.apply(null,innerArgs)}});var sync=true;fn.apply(this,args);sync=false})}async.ensureAsync=ensureAsync;async.constant=_restParam(function(values){var args=[null].concat(values);return function(callback){return callback.apply(this,args)}});async.wrapSync=async.asyncify=function asyncify(func){return _restParam(function(args){var callback=args.pop();var result;try{result=func.apply(this,args)}catch(e){return callback(e)}if(_isObject(result)&&typeof result.then==="function"){result.then(function(value){callback(null,value)})["catch"](function(err){callback(err.message?err:new Error(err))})}else{callback(null,result)}})};if(typeof module==="object"&&module.exports){module.exports=async}else if(typeof define==="function"&&define.amd){define([],function(){return async})}else{root.async=async}})()}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:96}],50:[function(require,module,exports){if(typeof window==="undefined"){var Buffer=require("buffer").Buffer}function Binary(buffer,subType){if(!(this instanceof Binary))return new Binary(buffer,subType);this._bsontype="Binary";if(buffer instanceof Number){this.sub_type=buffer;this.position=0}else{this.sub_type=subType==null?BSON_BINARY_SUBTYPE_DEFAULT:subType;this.position=0}if(buffer!=null&&!(buffer instanceof Number)){if(typeof buffer=="string"){if(typeof Buffer!="undefined"){this.buffer=new Buffer(buffer)}else if(typeof Uint8Array!="undefined"||Object.prototype.toString.call(buffer)=="[object Array]"){this.buffer=writeStringToArray(buffer)}else{throw new Error("only String, Buffer, Uint8Array or Array accepted")}}else{this.buffer=buffer}this.position=buffer.length}else{if(typeof Buffer!="undefined"){this.buffer=new Buffer(Binary.BUFFER_SIZE)}else if(typeof Uint8Array!="undefined"){this.buffer=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE))}else{this.buffer=new Array(Binary.BUFFER_SIZE)}this.position=0}}Binary.prototype.put=function put(byte_value){if(byte_value["length"]!=null&&typeof byte_value!="number"&&byte_value.length!=1)throw new Error("only accepts single character String, Uint8Array or Array");if(typeof byte_value!="number"&&byte_value<0||byte_value>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var decoded_byte=null;if(typeof byte_value=="string"){decoded_byte=byte_value.charCodeAt(0)}else if(byte_value["length"]!=null){decoded_byte=byte_value[0]}else{decoded_byte=byte_value}if(this.buffer.length>this.position){this.buffer[this.position++]=decoded_byte}else{if(typeof Buffer!="undefined"&&Buffer.isBuffer(this.buffer)){var buffer=new Buffer(Binary.BUFFER_SIZE+this.buffer.length);this.buffer.copy(buffer,0,0,this.buffer.length);this.buffer=buffer;this.buffer[this.position++]=decoded_byte}else{var buffer=null;if(Object.prototype.toString.call(this.buffer)=="[object Uint8Array]"){buffer=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE+this.buffer.length))}else{buffer=new Array(Binary.BUFFER_SIZE+this.buffer.length)}for(var i=0;i<this.buffer.length;i++){buffer[i]=this.buffer[i]}this.buffer=buffer;this.buffer[this.position++]=decoded_byte}}};Binary.prototype.write=function write(string,offset){offset=typeof offset=="number"?offset:this.position;if(this.buffer.length<offset+string.length){var buffer=null;if(typeof Buffer!="undefined"&&Buffer.isBuffer(this.buffer)){buffer=new Buffer(this.buffer.length+string.length);this.buffer.copy(buffer,0,0,this.buffer.length)}else if(Object.prototype.toString.call(this.buffer)=="[object Uint8Array]"){buffer=new Uint8Array(new ArrayBuffer(this.buffer.length+string.length));for(var i=0;i<this.position;i++){buffer[i]=this.buffer[i]}}this.buffer=buffer}if(typeof Buffer!="undefined"&&Buffer.isBuffer(string)&&Buffer.isBuffer(this.buffer)){string.copy(this.buffer,offset,0,string.length);this.position=offset+string.length>this.position?offset+string.length:this.position}else if(typeof Buffer!="undefined"&&typeof string=="string"&&Buffer.isBuffer(this.buffer)){this.buffer.write(string,offset,"binary");this.position=offset+string.length>this.position?offset+string.length:this.position}else if(Object.prototype.toString.call(string)=="[object Uint8Array]"||Object.prototype.toString.call(string)=="[object Array]"&&typeof string!="string"){for(var i=0;i<string.length;i++){this.buffer[offset++]=string[i]}this.position=offset>this.position?offset:this.position}else if(typeof string=="string"){for(var i=0;i<string.length;i++){this.buffer[offset++]=string.charCodeAt(i)}this.position=offset>this.position?offset:this.position}};Binary.prototype.read=function read(position,length){length=length&&length>0?length:this.position;if(this.buffer["slice"]){return this.buffer.slice(position,position+length)}else{var buffer=typeof Uint8Array!="undefined"?new Uint8Array(new ArrayBuffer(length)):new Array(length);for(var i=0;i<length;i++){buffer[i]=this.buffer[position++]}}return buffer};Binary.prototype.value=function value(asRaw){asRaw=asRaw==null?false:asRaw;if(asRaw&&typeof Buffer!="undefined"&&Buffer.isBuffer(this.buffer)&&this.buffer.length==this.position)return this.buffer;if(typeof Buffer!="undefined"&&Buffer.isBuffer(this.buffer)){return asRaw?this.buffer.slice(0,this.position):this.buffer.toString("binary",0,this.position)}else{if(asRaw){if(this.buffer["slice"]!=null){return this.buffer.slice(0,this.position)}else{var newBuffer=Object.prototype.toString.call(this.buffer)=="[object Uint8Array]"?new Uint8Array(new ArrayBuffer(this.position)):new Array(this.position);for(var i=0;i<this.position;i++){newBuffer[i]=this.buffer[i]}return newBuffer}}else{return convertArraytoUtf8BinaryString(this.buffer,0,this.position)}}};Binary.prototype.length=function length(){return this.position};Binary.prototype.toJSON=function(){return this.buffer!=null?this.buffer.toString("base64"):""};Binary.prototype.toString=function(format){return this.buffer!=null?this.buffer.slice(0,this.position).toString(format):""};var BSON_BINARY_SUBTYPE_DEFAULT=0;var writeStringToArray=function(data){var buffer=typeof Uint8Array!="undefined"?new Uint8Array(new ArrayBuffer(data.length)):new Array(data.length);for(var i=0;i<data.length;i++){buffer[i]=data.charCodeAt(i)}return buffer};var convertArraytoUtf8BinaryString=function(byteArray,startIndex,endIndex){var result="";for(var i=startIndex;i<endIndex;i++){result=result+String.fromCharCode(byteArray[i])}return result};Binary.BUFFER_SIZE=256;Binary.SUBTYPE_DEFAULT=0;Binary.SUBTYPE_FUNCTION=1;Binary.SUBTYPE_BYTE_ARRAY=2;Binary.SUBTYPE_UUID_OLD=3;Binary.SUBTYPE_UUID=4;Binary.SUBTYPE_MD5=5;Binary.SUBTYPE_USER_DEFINED=128;module.exports=Binary;module.exports.Binary=Binary},{buffer:91}],51:[function(require,module,exports){(function(process){var chr=String.fromCharCode;var maxBits=[];for(var i=0;i<64;i++){maxBits[i]=Math.pow(2,i)}function BinaryParser(bigEndian,allowExceptions){if(!(this instanceof BinaryParser))return new BinaryParser(bigEndian,allowExceptions);this.bigEndian=bigEndian;this.allowExceptions=allowExceptions}BinaryParser.warn=function warn(msg){if(this.allowExceptions){throw new Error(msg)}return 1};BinaryParser.decodeFloat=function decodeFloat(data,precisionBits,exponentBits){var b=new this.Buffer(this.bigEndian,data);b.checkBuffer(precisionBits+exponentBits+1);var bias=maxBits[exponentBits-1]-1,signal=b.readBits(precisionBits+exponentBits,1),exponent=b.readBits(precisionBits,exponentBits),significand=0,divisor=2,curByte=b.buffer.length+(-precisionBits>>3)-1;do{for(var byteValue=b.buffer[++curByte],startBit=precisionBits%8||8,mask=1<<startBit;mask>>=1;byteValue&mask&&(significand+=1/divisor),divisor*=2);}while(precisionBits-=startBit);return exponent==(bias<<1)+1?significand?NaN:signal?-Infinity:+Infinity:(1+signal*-2)*(exponent||significand?!exponent?Math.pow(2,-bias+1)*significand:Math.pow(2,exponent-bias)*(1+significand):0)};BinaryParser.decodeInt=function decodeInt(data,bits,signed,forceBigEndian){var b=new this.Buffer(this.bigEndian||forceBigEndian,data),x=b.readBits(0,bits),max=maxBits[bits];return signed&&x>=max/2?x-max:x};BinaryParser.encodeFloat=function encodeFloat(data,precisionBits,exponentBits){var bias=maxBits[exponentBits-1]-1,minExp=-bias+1,maxExp=bias,minUnnormExp=minExp-precisionBits,n=parseFloat(data),status=isNaN(n)||n==-Infinity||n==+Infinity?n:0,exp=0,len=2*bias+1+precisionBits+3,bin=new Array(len),signal=(n=status!==0?0:n)<0,intPart=Math.floor(n=Math.abs(n)),floatPart=n-intPart,lastBit,rounded,result,i,j;for(i=len;i;bin[--i]=0);for(i=bias+2;intPart&&i;bin[--i]=intPart%2,intPart=Math.floor(intPart/2));for(i=bias+1;floatPart>0&&i;(bin[++i]=((floatPart*=2)>=1)-0)&&--floatPart);for(i=-1;++i<len&&!bin[i];);if(bin[(lastBit=precisionBits-1+(i=(exp=bias+1-i)>=minExp&&exp<=maxExp?i+1:bias+1-(exp=minExp-1)))+1]){if(!(rounded=bin[lastBit])){for(j=lastBit+2;!rounded&&j<len;rounded=bin[j++]);}for(j=lastBit+1;rounded&&--j>=0;(bin[j]=!bin[j]-0)&&(rounded=0));}for(i=i-2<0?-1:i-3;++i<len&&!bin[i];);if((exp=bias+1-i)>=minExp&&exp<=maxExp){++i}else if(exp<minExp){exp!=bias+1-len&&exp<minUnnormExp&&this.warn("encodeFloat::float underflow");i=bias+1-(exp=minExp-1)}if(intPart||status!==0){this.warn(intPart?"encodeFloat::float overflow":"encodeFloat::"+status);exp=maxExp+1;i=bias+2;if(status==-Infinity){signal=1}else if(isNaN(status)){bin[i]=1}}for(n=Math.abs(exp+bias),j=exponentBits+1,result="";--j;result=n%2+result,n=n>>=1);for(n=0,j=0,i=(result=(signal?"1":"0")+result+bin.slice(i,i+precisionBits).join("")).length,r=[];i;j=(j+1)%8){n+=(1<<j)*result.charAt(--i);if(j==7){r[r.length]=String.fromCharCode(n);n=0}}r[r.length]=n?String.fromCharCode(n):"";return(this.bigEndian?r.reverse():r).join("")};BinaryParser.encodeInt=function encodeInt(data,bits,signed,forceBigEndian){var max=maxBits[bits];if(data>=max||data<-(max/2)){this.warn("encodeInt::overflow");data=0}if(data<0){data+=max}for(var r=[];data;r[r.length]=String.fromCharCode(data%256),data=Math.floor(data/256));for(bits=-(-bits>>3)-r.length;bits--;r[r.length]="\x00");return(this.bigEndian||forceBigEndian?r.reverse():r).join("")};BinaryParser.toSmall=function(data){return this.decodeInt(data,8,true)};BinaryParser.fromSmall=function(data){return this.encodeInt(data,8,true)};BinaryParser.toByte=function(data){return this.decodeInt(data,8,false)};BinaryParser.fromByte=function(data){return this.encodeInt(data,8,false)};BinaryParser.toShort=function(data){return this.decodeInt(data,16,true)};BinaryParser.fromShort=function(data){return this.encodeInt(data,16,true)};BinaryParser.toWord=function(data){return this.decodeInt(data,16,false)};BinaryParser.fromWord=function(data){return this.encodeInt(data,16,false)};BinaryParser.toInt=function(data){return this.decodeInt(data,32,true)};BinaryParser.fromInt=function(data){return this.encodeInt(data,32,true)};BinaryParser.toLong=function(data){return this.decodeInt(data,64,true)};BinaryParser.fromLong=function(data){return this.encodeInt(data,64,true)};BinaryParser.toDWord=function(data){return this.decodeInt(data,32,false)};BinaryParser.fromDWord=function(data){return this.encodeInt(data,32,false)};BinaryParser.toQWord=function(data){return this.decodeInt(data,64,true)};BinaryParser.fromQWord=function(data){return this.encodeInt(data,64,true)};BinaryParser.toFloat=function(data){return this.decodeFloat(data,23,8)};BinaryParser.fromFloat=function(data){return this.encodeFloat(data,23,8)};BinaryParser.toDouble=function(data){return this.decodeFloat(data,52,11)};BinaryParser.fromDouble=function(data){return this.encodeFloat(data,52,11)};BinaryParser.encode_int32=function encode_int32(number,asArray){var a,b,c,d,unsigned;unsigned=number<0?number+4294967296:number;a=Math.floor(unsigned/16777215);unsigned&=16777215;b=Math.floor(unsigned/65535);unsigned&=65535;c=Math.floor(unsigned/255);unsigned&=255;d=Math.floor(unsigned);return asArray?[chr(a),chr(b),chr(c),chr(d)]:chr(a)+chr(b)+chr(c)+chr(d)};BinaryParser.encode_int64=function encode_int64(number){var a,b,c,d,e,f,g,h,unsigned;unsigned=number<0?number+0x10000000000000000:number;a=Math.floor(unsigned/72057594037927940);unsigned&=72057594037927940;b=Math.floor(unsigned/0xffffffffffff);unsigned&=0xffffffffffff;c=Math.floor(unsigned/0xffffffffff);unsigned&=0xffffffffff;d=Math.floor(unsigned/4294967295);unsigned&=4294967295;e=Math.floor(unsigned/16777215);unsigned&=16777215;
f=Math.floor(unsigned/65535);unsigned&=65535;g=Math.floor(unsigned/255);unsigned&=255;h=Math.floor(unsigned);return chr(a)+chr(b)+chr(c)+chr(d)+chr(e)+chr(f)+chr(g)+chr(h)};BinaryParser.decode_utf8=function decode_utf8(binaryStr){var len=binaryStr.length,decoded="",i=0,c=0,c1=0,c2=0,c3;while(i<len){c=binaryStr.charCodeAt(i);if(c<128){decoded+=String.fromCharCode(c);i++}else if(c>191&&c<224){c2=binaryStr.charCodeAt(i+1);decoded+=String.fromCharCode((c&31)<<6|c2&63);i+=2}else{c2=binaryStr.charCodeAt(i+1);c3=binaryStr.charCodeAt(i+2);decoded+=String.fromCharCode((c&15)<<12|(c2&63)<<6|c3&63);i+=3}}return decoded};BinaryParser.encode_cstring=function encode_cstring(s){return unescape(encodeURIComponent(s))+BinaryParser.fromByte(0)};BinaryParser.encode_utf8=function encode_utf8(s){var a="",c;for(var n=0,len=s.length;n<len;n++){c=s.charCodeAt(n);if(c<128){a+=String.fromCharCode(c)}else if(c>127&&c<2048){a+=String.fromCharCode(c>>6|192);a+=String.fromCharCode(c&63|128)}else{a+=String.fromCharCode(c>>12|224);a+=String.fromCharCode(c>>6&63|128);a+=String.fromCharCode(c&63|128)}}return a};BinaryParser.hprint=function hprint(s){var number;for(var i=0,len=s.length;i<len;i++){if(s.charCodeAt(i)<32){number=s.charCodeAt(i)<=15?"0"+s.charCodeAt(i).toString(16):s.charCodeAt(i).toString(16);process.stdout.write(number+" ")}else{number=s.charCodeAt(i)<=15?"0"+s.charCodeAt(i).toString(16):s.charCodeAt(i).toString(16);process.stdout.write(number+" ")}}process.stdout.write("\n\n")};BinaryParser.ilprint=function hprint(s){var number;for(var i=0,len=s.length;i<len;i++){if(s.charCodeAt(i)<32){number=s.charCodeAt(i)<=15?"0"+s.charCodeAt(i).toString(10):s.charCodeAt(i).toString(10);require("util").debug(number+" : ")}else{number=s.charCodeAt(i)<=15?"0"+s.charCodeAt(i).toString(10):s.charCodeAt(i).toString(10);require("util").debug(number+" : "+s.charAt(i))}}};BinaryParser.hlprint=function hprint(s){var number;for(var i=0,len=s.length;i<len;i++){if(s.charCodeAt(i)<32){number=s.charCodeAt(i)<=15?"0"+s.charCodeAt(i).toString(16):s.charCodeAt(i).toString(16);require("util").debug(number+" : ")}else{number=s.charCodeAt(i)<=15?"0"+s.charCodeAt(i).toString(16):s.charCodeAt(i).toString(16);require("util").debug(number+" : "+s.charAt(i))}}};function BinaryParserBuffer(bigEndian,buffer){this.bigEndian=bigEndian||0;this.buffer=[];this.setBuffer(buffer)}BinaryParserBuffer.prototype.setBuffer=function setBuffer(data){var l,i,b;if(data){i=l=data.length;b=this.buffer=new Array(l);for(;i;b[l-i]=data.charCodeAt(--i));this.bigEndian&&b.reverse()}};BinaryParserBuffer.prototype.hasNeededBits=function hasNeededBits(neededBits){return this.buffer.length>=-(-neededBits>>3)};BinaryParserBuffer.prototype.checkBuffer=function checkBuffer(neededBits){if(!this.hasNeededBits(neededBits)){throw new Error("checkBuffer::missing bytes")}};BinaryParserBuffer.prototype.readBits=function readBits(start,length){function shl(a,b){for(;b--;a=((a%=2147483647+1)&1073741824)==1073741824?a*2:(a-1073741824)*2+2147483647+1);return a}if(start<0||length<=0){return 0}this.checkBuffer(start+length);var offsetLeft,offsetRight=start%8,curByte=this.buffer.length-(start>>3)-1,lastByte=this.buffer.length+(-(start+length)>>3),diff=curByte-lastByte,sum=(this.buffer[curByte]>>offsetRight&(1<<(diff?8-offsetRight:length))-1)+(diff&&(offsetLeft=(start+length)%8)?(this.buffer[lastByte++]&(1<<offsetLeft)-1)<<(diff--<<3)-offsetRight:0);for(;diff;sum+=shl(this.buffer[lastByte++],(diff--<<3)-offsetRight));return sum};BinaryParser.Buffer=BinaryParserBuffer;exports.BinaryParser=BinaryParser}).call(this,require("_process"))},{_process:96,util:98}],52:[function(require,module,exports){(function(Buffer){var writeIEEE754=require("./float_parser").writeIEEE754,readIEEE754=require("./float_parser").readIEEE754,Map=require("./map"),Long=require("./long").Long,Double=require("./double").Double,Timestamp=require("./timestamp").Timestamp,ObjectID=require("./objectid").ObjectID,BSONRegExp=require("./regexp").BSONRegExp,Symbol=require("./symbol").Symbol,Code=require("./code").Code,MinKey=require("./min_key").MinKey,MaxKey=require("./max_key").MaxKey,DBRef=require("./db_ref").DBRef,Binary=require("./binary").Binary;var deserialize=require("./parser/deserializer"),serializer=require("./parser/serializer"),calculateObjectSize=require("./parser/calculate_size");var MAXSIZE=1024*1024*17;var buffer=new Buffer(MAXSIZE);var BSON=function(){};BSON.prototype.serialize=function serialize(object,checkKeys,asBuffer,serializeFunctions,index,ignoreUndefined){var serializationIndex=serializer(buffer,object,checkKeys,index||0,0,serializeFunctions,ignoreUndefined);var finishedBuffer=new Buffer(serializationIndex);buffer.copy(finishedBuffer,0,0,finishedBuffer.length);return finishedBuffer};BSON.prototype.serializeWithBufferAndIndex=function(object,checkKeys,finalBuffer,startIndex,serializeFunctions,ignoreUndefined){var serializationIndex=serializer(buffer,object,checkKeys,startIndex||0,0,serializeFunctions,ignoreUndefined);buffer.copy(finalBuffer,startIndex,0,serializationIndex);return startIndex+serializationIndex-1};BSON.prototype.deserialize=function(data,options){return deserialize(data,options)};BSON.prototype.calculateObjectSize=function(object,serializeFunctions,ignoreUndefined){return calculateObjectSize(object,serializeFunctions,ignoreUndefined)};BSON.prototype.deserializeStream=function(data,startIndex,numberOfDocuments,documents,docStartIndex,options){options=options!=null?options:{};var index=startIndex;for(var i=0;i<numberOfDocuments;i++){var size=data[index]|data[index+1]<<8|data[index+2]<<16|data[index+3]<<24;options["index"]=index;documents[docStartIndex+i]=this.deserialize(data,options);index=index+size}return index};BSON.BSON_INT32_MAX=2147483647;BSON.BSON_INT32_MIN=-2147483648;BSON.BSON_INT64_MAX=Math.pow(2,63)-1;BSON.BSON_INT64_MIN=-Math.pow(2,63);BSON.JS_INT_MAX=9007199254740992;BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);BSON.BSON_DATA_NUMBER=1;BSON.BSON_DATA_STRING=2;BSON.BSON_DATA_OBJECT=3;BSON.BSON_DATA_ARRAY=4;BSON.BSON_DATA_BINARY=5;BSON.BSON_DATA_OID=7;BSON.BSON_DATA_BOOLEAN=8;BSON.BSON_DATA_DATE=9;BSON.BSON_DATA_NULL=10;BSON.BSON_DATA_REGEXP=11;BSON.BSON_DATA_CODE=13;BSON.BSON_DATA_SYMBOL=14;BSON.BSON_DATA_CODE_W_SCOPE=15;BSON.BSON_DATA_INT=16;BSON.BSON_DATA_TIMESTAMP=17;BSON.BSON_DATA_LONG=18;BSON.BSON_DATA_MIN_KEY=255;BSON.BSON_DATA_MAX_KEY=127;BSON.BSON_BINARY_SUBTYPE_DEFAULT=0;BSON.BSON_BINARY_SUBTYPE_FUNCTION=1;BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;BSON.BSON_BINARY_SUBTYPE_UUID=3;BSON.BSON_BINARY_SUBTYPE_MD5=4;BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128;module.exports=BSON;module.exports.Code=Code;module.exports.Map=Map;module.exports.Symbol=Symbol;module.exports.BSON=BSON;module.exports.DBRef=DBRef;module.exports.Binary=Binary;module.exports.ObjectID=ObjectID;module.exports.Long=Long;module.exports.Timestamp=Timestamp;module.exports.Double=Double;module.exports.MinKey=MinKey;module.exports.MaxKey=MaxKey;module.exports.BSONRegExp=BSONRegExp}).call(this,require("buffer").Buffer)},{"./binary":50,"./code":53,"./db_ref":54,"./double":55,"./float_parser":56,"./long":57,"./map":58,"./max_key":59,"./min_key":60,"./objectid":61,"./parser/calculate_size":62,"./parser/deserializer":63,"./parser/serializer":64,"./regexp":65,"./symbol":66,"./timestamp":67,buffer:91}],53:[function(require,module,exports){var Code=function Code(code,scope){if(!(this instanceof Code))return new Code(code,scope);this._bsontype="Code";this.code=code;this.scope=scope==null?{}:scope};Code.prototype.toJSON=function(){return{scope:this.scope,code:this.code}};module.exports=Code;module.exports.Code=Code},{}],54:[function(require,module,exports){function DBRef(namespace,oid,db){if(!(this instanceof DBRef))return new DBRef(namespace,oid,db);this._bsontype="DBRef";this.namespace=namespace;this.oid=oid;this.db=db}DBRef.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:this.db==null?"":this.db}};module.exports=DBRef;module.exports.DBRef=DBRef},{}],55:[function(require,module,exports){function Double(value){if(!(this instanceof Double))return new Double(value);this._bsontype="Double";this.value=value}Double.prototype.valueOf=function(){return this.value};Double.prototype.toJSON=function(){return this.value};module.exports=Double;module.exports.Double=Double},{}],56:[function(require,module,exports){var readIEEE754=function(buffer,offset,endian,mLen,nBytes){var e,m,bBE=endian==="big",eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=bBE?0:nBytes-1,d=bBE?1:-1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};var writeIEEE754=function(buffer,value,offset,endian,mLen,nBytes){var e,m,c,bBE=endian==="big",eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=bBE?nBytes-1:0,d=bBE?-1:1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128};exports.readIEEE754=readIEEE754;exports.writeIEEE754=writeIEEE754},{}],57:[function(require,module,exports){function Long(low,high){if(!(this instanceof Long))return new Long(low,high);this._bsontype="Long";this.low_=low|0;this.high_=high|0}Long.prototype.toInt=function(){return this.low_};Long.prototype.toNumber=function(){return this.high_*Long.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Long.prototype.toJSON=function(){return this.toString()};Long.prototype.toString=function(opt_radix){var radix=opt_radix||10;if(radix<2||36<radix){throw Error("radix out of range: "+radix)}if(this.isZero()){return"0"}if(this.isNegative()){if(this.equals(Long.MIN_VALUE)){var radixLong=Long.fromNumber(radix);var div=this.div(radixLong);var rem=div.multiply(radixLong).subtract(this);return div.toString(radix)+rem.toInt().toString(radix)}else{return"-"+this.negate().toString(radix)}}var radixToPower=Long.fromNumber(Math.pow(radix,6));var rem=this;var result="";while(true){var remDiv=rem.div(radixToPower);var intval=rem.subtract(remDiv.multiply(radixToPower)).toInt();var digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6){digits="0"+digits}result=""+digits+result}}};Long.prototype.getHighBits=function(){return this.high_};Long.prototype.getLowBits=function(){return this.low_};Long.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:Long.TWO_PWR_32_DBL_+this.low_};Long.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Long.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var val=this.high_!=0?this.high_:this.low_;for(var bit=31;bit>0;bit--){if((val&1<<bit)!=0){break}}return this.high_!=0?bit+33:bit+1}};Long.prototype.isZero=function(){return this.high_==0&&this.low_==0};Long.prototype.isNegative=function(){return this.high_<0};Long.prototype.isOdd=function(){return(this.low_&1)==1};Long.prototype.equals=function(other){return this.high_==other.high_&&this.low_==other.low_};Long.prototype.notEquals=function(other){return this.high_!=other.high_||this.low_!=other.low_};Long.prototype.lessThan=function(other){return this.compare(other)<0};Long.prototype.lessThanOrEqual=function(other){return this.compare(other)<=0};Long.prototype.greaterThan=function(other){return this.compare(other)>0};Long.prototype.greaterThanOrEqual=function(other){return this.compare(other)>=0};Long.prototype.compare=function(other){if(this.equals(other)){return 0}var thisNeg=this.isNegative();var otherNeg=other.isNegative();if(thisNeg&&!otherNeg){return-1}if(!thisNeg&&otherNeg){return 1}if(this.subtract(other).isNegative()){return-1}else{return 1}};Long.prototype.negate=function(){if(this.equals(Long.MIN_VALUE)){return Long.MIN_VALUE}else{return this.not().add(Long.ONE)}};Long.prototype.add=function(other){var a48=this.high_>>>16;var a32=this.high_&65535;var a16=this.low_>>>16;var a00=this.low_&65535;var b48=other.high_>>>16;var b32=other.high_&65535;var b16=other.low_>>>16;var b00=other.low_&65535;var c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return Long.fromBits(c16<<16|c00,c48<<16|c32)};Long.prototype.subtract=function(other){return this.add(other.negate())};Long.prototype.multiply=function(other){if(this.isZero()){return Long.ZERO}else if(other.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){return other.isOdd()?Long.MIN_VALUE:Long.ZERO}else if(other.equals(Long.MIN_VALUE)){return this.isOdd()?Long.MIN_VALUE:Long.ZERO}if(this.isNegative()){if(other.isNegative()){return this.negate().multiply(other.negate())}else{return this.negate().multiply(other).negate()}}else if(other.isNegative()){return this.multiply(other.negate()).negate()}if(this.lessThan(Long.TWO_PWR_24_)&&other.lessThan(Long.TWO_PWR_24_)){return Long.fromNumber(this.toNumber()*other.toNumber())}var a48=this.high_>>>16;var a32=this.high_&65535;var a16=this.low_>>>16;var a00=this.low_&65535;var b48=other.high_>>>16;var b32=other.high_&65535;var b16=other.low_>>>16;var b00=other.low_&65535;var c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return Long.fromBits(c16<<16|c00,c48<<16|c32)};Long.prototype.div=function(other){if(other.isZero()){throw Error("division by zero")}else if(this.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){if(other.equals(Long.ONE)||other.equals(Long.NEG_ONE)){return Long.MIN_VALUE}else if(other.equals(Long.MIN_VALUE)){return Long.ONE}else{var halfThis=this.shiftRight(1);var approx=halfThis.div(other).shiftLeft(1);if(approx.equals(Long.ZERO)){return other.isNegative()?Long.ONE:Long.NEG_ONE}else{var rem=this.subtract(other.multiply(approx));var result=approx.add(rem.div(other));return result}}}else if(other.equals(Long.MIN_VALUE)){return Long.ZERO}if(this.isNegative()){if(other.isNegative()){return this.negate().div(other.negate())}else{return this.negate().div(other).negate()}}else if(other.isNegative()){return this.div(other.negate()).negate()}var res=Long.ZERO;var rem=this;while(rem.greaterThanOrEqual(other)){var approx=Math.max(1,Math.floor(rem.toNumber()/other.toNumber()));var log2=Math.ceil(Math.log(approx)/Math.LN2);var delta=log2<=48?1:Math.pow(2,log2-48);var approxRes=Long.fromNumber(approx);var approxRem=approxRes.multiply(other);while(approxRem.isNegative()||approxRem.greaterThan(rem)){approx-=delta;approxRes=Long.fromNumber(approx);approxRem=approxRes.multiply(other)}if(approxRes.isZero()){approxRes=Long.ONE}res=res.add(approxRes);rem=rem.subtract(approxRem)}return res};Long.prototype.modulo=function(other){return this.subtract(this.div(other).multiply(other))};Long.prototype.not=function(){return Long.fromBits(~this.low_,~this.high_)};Long.prototype.and=function(other){return Long.fromBits(this.low_&other.low_,this.high_&other.high_)};Long.prototype.or=function(other){return Long.fromBits(this.low_|other.low_,this.high_|other.high_)};Long.prototype.xor=function(other){return Long.fromBits(this.low_^other.low_,this.high_^other.high_)};Long.prototype.shiftLeft=function(numBits){numBits&=63;if(numBits==0){return this}else{var low=this.low_;if(numBits<32){var high=this.high_;return Long.fromBits(low<<numBits,high<<numBits|low>>>32-numBits)}else{return Long.fromBits(0,low<<numBits-32)}}};Long.prototype.shiftRight=function(numBits){numBits&=63;if(numBits==0){return this}else{var high=this.high_;if(numBits<32){var low=this.low_;return Long.fromBits(low>>>numBits|high<<32-numBits,high>>numBits)}else{return Long.fromBits(high>>numBits-32,high>=0?0:-1)}}};Long.prototype.shiftRightUnsigned=function(numBits){numBits&=63;if(numBits==0){return this}else{var high=this.high_;if(numBits<32){var low=this.low_;return Long.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits)}else if(numBits==32){return Long.fromBits(high,0)}else{return Long.fromBits(high>>>numBits-32,0)}}};Long.fromInt=function(value){if(-128<=value&&value<128){var cachedObj=Long.INT_CACHE_[value];if(cachedObj){return cachedObj}}var obj=new Long(value|0,value<0?-1:0);if(-128<=value&&value<128){Long.INT_CACHE_[value]=obj}return obj};Long.fromNumber=function(value){if(isNaN(value)||!isFinite(value)){return Long.ZERO}else if(value<=-Long.TWO_PWR_63_DBL_){return Long.MIN_VALUE}else if(value+1>=Long.TWO_PWR_63_DBL_){return Long.MAX_VALUE}else if(value<0){return Long.fromNumber(-value).negate()}else{return new Long(value%Long.TWO_PWR_32_DBL_|0,value/Long.TWO_PWR_32_DBL_|0)}};Long.fromBits=function(lowBits,highBits){return new Long(lowBits,highBits)};Long.fromString=function(str,opt_radix){if(str.length==0){throw Error("number format error: empty string")}var radix=opt_radix||10;if(radix<2||36<radix){throw Error("radix out of range: "+radix)}if(str.charAt(0)=="-"){return Long.fromString(str.substring(1),radix).negate()}else if(str.indexOf("-")>=0){throw Error('number format error: interior "-" character: '+str)}var radixToPower=Long.fromNumber(Math.pow(radix,8));var result=Long.ZERO;for(var i=0;i<str.length;i+=8){var size=Math.min(8,str.length-i);var value=parseInt(str.substring(i,i+size),radix);if(size<8){var power=Long.fromNumber(Math.pow(radix,size));result=result.multiply(power).add(Long.fromNumber(value))}else{result=result.multiply(radixToPower);result=result.add(Long.fromNumber(value))}}return result};Long.INT_CACHE_={};Long.TWO_PWR_16_DBL_=1<<16;Long.TWO_PWR_24_DBL_=1<<24;Long.TWO_PWR_32_DBL_=Long.TWO_PWR_16_DBL_*Long.TWO_PWR_16_DBL_;Long.TWO_PWR_31_DBL_=Long.TWO_PWR_32_DBL_/2;Long.TWO_PWR_48_DBL_=Long.TWO_PWR_32_DBL_*Long.TWO_PWR_16_DBL_;Long.TWO_PWR_64_DBL_=Long.TWO_PWR_32_DBL_*Long.TWO_PWR_32_DBL_;Long.TWO_PWR_63_DBL_=Long.TWO_PWR_64_DBL_/2;Long.ZERO=Long.fromInt(0);Long.ONE=Long.fromInt(1);Long.NEG_ONE=Long.fromInt(-1);Long.MAX_VALUE=Long.fromBits(4294967295|0,2147483647|0);Long.MIN_VALUE=Long.fromBits(0,2147483648|0);Long.TWO_PWR_24_=Long.fromInt(1<<24);module.exports=Long;module.exports.Long=Long},{}],58:[function(require,module,exports){(function(global){"use strict";if(typeof global.Map!=="undefined"){module.exports=global.Map;module.exports.Map=global.Map}else{var Map=function(array){this._keys=[];this._values={};for(var i=0;i<array.length;i++){if(array[i]==null)continue;var entry=array[i];var key=entry[0];var value=entry[1];this._keys.push(key);this._values[key]={v:value,i:this._keys.length-1}}};Map.prototype.clear=function(){this._keys=[];this._values={}};Map.prototype.delete=function(key){var value=this._values[key];if(value==null)return false;delete this._values[key];this._keys.splice(value.i,1);return true};Map.prototype.entries=function(){var self=this;var index=0;return{next:function(){var key=self._keys[index++];return{value:key!==undefined?[key,self._values[key].v]:undefined,done:key!==undefined?false:true}}}};Map.prototype.forEach=function(callback,self){self=self||this;for(var i=0;i<this._keys.length;i++){var key=this._keys[i];callback.call(self,this._values[key].v,key,self)}};Map.prototype.get=function(key){return this._values[key]?this._values[key].v:undefined};Map.prototype.has=function(key){return this._values[key]!=null};Map.prototype.keys=function(key){var self=this;var index=0;return{next:function(){var key=self._keys[index++];return{value:key!==undefined?key:undefined,done:key!==undefined?false:true}}}};Map.prototype.set=function(key,value){if(this._values[key]){this._values[key].v=value;return this}this._keys.push(key);this._values[key]={v:value,i:this._keys.length-1};return this};Map.prototype.values=function(key,value){var self=this;var index=0;return{next:function(){var key=self._keys[index++];return{value:key!==undefined?self._values[key].v:undefined,done:key!==undefined?false:true}}}};Object.defineProperty(Map.prototype,"size",{enumerable:true,get:function(){return this._keys.length}});module.exports=Map;module.exports.Map=Map}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],59:[function(require,module,exports){function MaxKey(){if(!(this instanceof MaxKey))return new MaxKey;this._bsontype="MaxKey"}module.exports=MaxKey;module.exports.MaxKey=MaxKey},{}],60:[function(require,module,exports){function MinKey(){if(!(this instanceof MinKey))return new MinKey;this._bsontype="MinKey"}module.exports=MinKey;module.exports.MinKey=MinKey},{}],61:[function(require,module,exports){(function(process){var BinaryParser=require("./binary_parser").BinaryParser;var MACHINE_ID=parseInt(Math.random()*16777215,10);var checkForHexRegExp=new RegExp("^[0-9a-fA-F]{24}$");var ObjectID=function ObjectID(id){if(!(this instanceof ObjectID))return new ObjectID(id);if(id instanceof ObjectID)return id;this._bsontype="ObjectID";var __id=null;var valid=ObjectID.isValid(id);if(!valid&&id!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(valid&&typeof id=="string"&&id.length==24){return ObjectID.createFromHexString(id)}else if(id==null||typeof id=="number"){this.id=this.generate(id)}else if(id!=null&&id.length===12){this.id=id}if(ObjectID.cacheHexString)this.__id=this.toHexString()};var ObjectId=ObjectID;var hexTable=[];for(var i=0;i<256;i++){hexTable[i]=(i<=15?"0":"")+i.toString(16)}ObjectID.prototype.toHexString=function(){if(ObjectID.cacheHexString&&this.__id)return this.__id;var hexString="";for(var i=0;i<this.id.length;i++){hexString+=hexTable[this.id.charCodeAt(i)]}if(ObjectID.cacheHexString)this.__id=hexString;return hexString};ObjectID.prototype.get_inc=function(){return ObjectID.index=(ObjectID.index+1)%16777215};ObjectID.prototype.getInc=function(){return this.get_inc()};ObjectID.prototype.generate=function(time){if("number"!=typeof time){time=parseInt(Date.now()/1e3,10)}var time4Bytes=BinaryParser.encodeInt(time,32,true,true);var machine3Bytes=BinaryParser.encodeInt(MACHINE_ID,24,false);var pid2Bytes=BinaryParser.fromShort((typeof process==="undefined"?Math.floor(Math.random()*1e5):process.pid)%65535);var index3Bytes=BinaryParser.encodeInt(this.get_inc(),24,false,true);return time4Bytes+machine3Bytes+pid2Bytes+index3Bytes};ObjectID.prototype.toString=function(){return this.toHexString()};ObjectID.prototype.inspect=ObjectID.prototype.toString;ObjectID.prototype.toJSON=function(){return this.toHexString()};ObjectID.prototype.equals=function equals(otherID){var id;if(otherID!=null&&(otherID instanceof ObjectID||otherID.toHexString)){id=otherID.id}else if(typeof otherID=="string"&&ObjectID.isValid(otherID)){id=ObjectID.createFromHexString(otherID).id}else{return false}return this.id===id};ObjectID.prototype.getTimestamp=function(){var timestamp=new Date;timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4),32,true,true))*1e3);return timestamp};ObjectID.index=parseInt(Math.random()*16777215,10);ObjectID.createPk=function createPk(){return new ObjectID};ObjectID.createFromTime=function createFromTime(time){var id=BinaryParser.encodeInt(time,32,true,true)+BinaryParser.encodeInt(0,64,true,true);return new ObjectID(id)};ObjectID.createFromHexString=function createFromHexString(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!=24)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");var len=hexString.length;if(len>12*2){throw new Error("Id cannot be longer than 12 bytes")}var result="",string,number;for(var index=0;index<len;index+=2){string=hexString.substr(index,2);number=parseInt(string,16);result+=BinaryParser.fromByte(number)}return new ObjectID(result,hexString)};ObjectID.isValid=function isValid(id){if(id==null)return false;if(typeof id=="number")return true;if(typeof id=="string"){return id.length==12||id.length==24&&checkForHexRegExp.test(id)}return false};Object.defineProperty(ObjectID.prototype,"generationTime",{enumerable:true,get:function(){return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4),32,true,true))},set:function(value){var value=BinaryParser.encodeInt(value,32,true,true);this.id=value+this.id.substr(4);this.toHexString()}});module.exports=ObjectID;module.exports.ObjectID=ObjectID;module.exports.ObjectId=ObjectID}).call(this,require("_process"))},{"./binary_parser":51,_process:96}],62:[function(require,module,exports){(function(Buffer){"use strict";var writeIEEE754=require("../float_parser").writeIEEE754,readIEEE754=require("../float_parser").readIEEE754,Long=require("../long").Long,Double=require("../double").Double,Timestamp=require("../timestamp").Timestamp,ObjectID=require("../objectid").ObjectID,Symbol=require("../symbol").Symbol,BSONRegExp=require("../regexp").BSONRegExp,Code=require("../code").Code,MinKey=require("../min_key").MinKey,MaxKey=require("../max_key").MaxKey,DBRef=require("../db_ref").DBRef,Binary=require("../binary").Binary;var isDate=function isDate(d){return typeof d==="object"&&Object.prototype.toString.call(d)==="[object Date]"};var calculateObjectSize=function calculateObjectSize(object,serializeFunctions,ignoreUndefined){var totalLength=4+1;if(Array.isArray(object)){for(var i=0;i<object.length;i++){totalLength+=calculateElement(i.toString(),object[i],serializeFunctions,true,ignoreUndefined)}}else{if(object.toBSON){object=object.toBSON()}for(var key in object){totalLength+=calculateElement(key,object[key],serializeFunctions,false,ignoreUndefined)}}return totalLength};function calculateElement(name,value,serializeFunctions,isArray,ignoreUndefined){if(value&&value.toBSON){value=value.toBSON()}switch(typeof value){case"string":return 1+Buffer.byteLength(name,"utf8")+1+4+Buffer.byteLength(value,"utf8")+1;case"number":if(Math.floor(value)===value&&value>=BSON.JS_INT_MIN&&value<=BSON.JS_INT_MAX){if(value>=BSON.BSON_INT32_MIN&&value<=BSON.BSON_INT32_MAX){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(4+1)}else{return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(8+1)}}else{return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(8+1)}case"undefined":if(isArray||!ignoreUndefined)return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1;return 0;case"boolean":return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(1+1);case"object":if(value==null||value instanceof MinKey||value instanceof MaxKey||value["_bsontype"]=="MinKey"||value["_bsontype"]=="MaxKey"){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1}else if(value instanceof ObjectID||value["_bsontype"]=="ObjectID"){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(12+1)}else if(value instanceof Date||isDate(value)){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(8+1)}else if(typeof Buffer!=="undefined"&&Buffer.isBuffer(value)){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(1+4+1)+value.length}else if(value instanceof Long||value instanceof Double||value instanceof Timestamp||value["_bsontype"]=="Long"||value["_bsontype"]=="Double"||value["_bsontype"]=="Timestamp"){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(8+1)}else if(value instanceof Code||value["_bsontype"]=="Code"){if(value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+4+4+Buffer.byteLength(value.code.toString(),"utf8")+1+calculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else{return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+4+Buffer.byteLength(value.code.toString(),"utf8")+1}}else if(value instanceof Binary||value["_bsontype"]=="Binary"){if(value.sub_type==Binary.SUBTYPE_BYTE_ARRAY){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(value.position+1+4+1+4)}else{return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+(value.position+1+4+1)}}else if(value instanceof Symbol||value["_bsontype"]=="Symbol"){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+Buffer.byteLength(value.value,"utf8")+4+1+1}else if(value instanceof DBRef||value["_bsontype"]=="DBRef"){var ordered_values={$ref:value.namespace,$id:value.oid};if(null!=value.db){ordered_values["$db"]=value.db}return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+calculateObjectSize(ordered_values,serializeFunctions,ignoreUndefined)}else if(value instanceof RegExp||Object.prototype.toString.call(value)==="[object RegExp]"){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+Buffer.byteLength(value.source,"utf8")+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else if(value instanceof BSONRegExp||value["_bsontype"]=="BSONRegExp"){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+Buffer.byteLength(value.pattern,"utf8")+1+Buffer.byteLength(value.options,"utf8")+1}else{return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+calculateObjectSize(value,serializeFunctions,ignoreUndefined)+1}case"function":if(value instanceof RegExp||Object.prototype.toString.call(value)==="[object RegExp]"||String.call(value)=="[object RegExp]"){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+Buffer.byteLength(value.source,"utf8")+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else{if(serializeFunctions&&value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+4+4+Buffer.byteLength(value.toString(),"utf8")+1+calculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else if(serializeFunctions){return(name!=null?Buffer.byteLength(name,"utf8")+1:0)+1+4+Buffer.byteLength(value.toString(),"utf8")+1}}}return 0}var BSON={};var functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1;BSON.BSON_DATA_STRING=2;BSON.BSON_DATA_OBJECT=3;BSON.BSON_DATA_ARRAY=4;BSON.BSON_DATA_BINARY=5;BSON.BSON_DATA_OID=7;BSON.BSON_DATA_BOOLEAN=8;BSON.BSON_DATA_DATE=9;BSON.BSON_DATA_NULL=10;BSON.BSON_DATA_REGEXP=11;BSON.BSON_DATA_CODE=13;BSON.BSON_DATA_SYMBOL=14;BSON.BSON_DATA_CODE_W_SCOPE=15;BSON.BSON_DATA_INT=16;BSON.BSON_DATA_TIMESTAMP=17;BSON.BSON_DATA_LONG=18;BSON.BSON_DATA_MIN_KEY=255;BSON.BSON_DATA_MAX_KEY=127;BSON.BSON_BINARY_SUBTYPE_DEFAULT=0;BSON.BSON_BINARY_SUBTYPE_FUNCTION=1;BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;BSON.BSON_BINARY_SUBTYPE_UUID=3;BSON.BSON_BINARY_SUBTYPE_MD5=4;BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128;BSON.BSON_INT32_MAX=2147483647;BSON.BSON_INT32_MIN=-2147483648;BSON.BSON_INT64_MAX=Math.pow(2,63)-1;BSON.BSON_INT64_MIN=-Math.pow(2,63);BSON.JS_INT_MAX=9007199254740992;BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=calculateObjectSize}).call(this,require("buffer").Buffer)},{"../binary":50,"../code":53,"../db_ref":54,"../double":55,"../float_parser":56,"../long":57,"../max_key":59,"../min_key":60,"../objectid":61,"../regexp":65,"../symbol":66,"../timestamp":67,buffer:91}],63:[function(require,module,exports){"use strict";var readIEEE754=require("../float_parser").readIEEE754,f=require("util").format,Long=require("../long").Long,Double=require("../double").Double,Timestamp=require("../timestamp").Timestamp,ObjectID=require("../objectid").ObjectID,Symbol=require("../symbol").Symbol,Code=require("../code").Code,MinKey=require("../min_key").MinKey,MaxKey=require("../max_key").MaxKey,DBRef=require("../db_ref").DBRef,BSONRegExp=require("../regexp").BSONRegExp,Binary=require("../binary").Binary;
var deserialize=function(buffer,options,isArray){options=options==null?{}:options;var index=options&&options.index?options.index:0;var size=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;if(size<5||buffer.length<size){throw new Error("corrupt bson message")}if(buffer[size-1]!=0){throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(buffer,index-4,options,isArray)};var deserializeObject=function(buffer,index,options,isArray){var evalFunctions=options["evalFunctions"]==null?false:options["evalFunctions"];var cacheFunctions=options["cacheFunctions"]==null?false:options["cacheFunctions"];var cacheFunctionsCrc32=options["cacheFunctionsCrc32"]==null?false:options["cacheFunctionsCrc32"];var promoteLongs=options["promoteLongs"]==null?true:options["promoteLongs"];var fieldsAsRaw=options["fieldsAsRaw"]==null?null:options["fieldsAsRaw"];var raw=options["raw"]==null?false:options["raw"];var bsonRegExp=typeof options["bsonRegExp"]=="boolean"?options["bsonRegExp"]:false;var promoteBuffers=options["promoteBuffers"]==null?false:options["promoteBuffers"];if(buffer.length<5)throw new Error("corrupt bson message < 5 bytes long");var size=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;if(size<5||size>buffer.length)throw new Error("corrupt bson message");var object=isArray?[]:{};while(true){var elementType=buffer[index++];if(elementType==0)break;var i=index;while(buffer[i]!==0&&i<buffer.length){i++}if(i>=buffer.length)throw new Error("Bad BSON Document: illegal CString");var name=buffer.toString("utf8",index,i);index=i+1;if(elementType==BSON.BSON_DATA_STRING){var stringSize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;if(stringSize<=0||stringSize>buffer.length-index||buffer[index+stringSize-1]!=0)throw new Error("bad string length in bson");object[name]=buffer.toString("utf8",index,index+stringSize-1);index=index+stringSize}else if(elementType==BSON.BSON_DATA_OID){var string=buffer.toString("binary",index,index+12);object[name]=new ObjectID(string);index=index+12}else if(elementType==BSON.BSON_DATA_INT){object[name]=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24}else if(elementType==BSON.BSON_DATA_NUMBER){object[name]=buffer.readDoubleLE(index);index=index+8}else if(elementType==BSON.BSON_DATA_DATE){var lowBits=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;var highBits=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;object[name]=new Date(new Long(lowBits,highBits).toNumber())}else if(elementType==BSON.BSON_DATA_BOOLEAN){object[name]=buffer[index++]==1}else if(elementType==BSON.BSON_DATA_OBJECT){var _index=index;var objectSize=buffer[index]|buffer[index+1]<<8|buffer[index+2]<<16|buffer[index+3]<<24;if(objectSize<=0||objectSize>buffer.length-index)throw new Error("bad embedded document length in bson");if(raw){object[name]=buffer.slice(index,index+objectSize)}else{object[name]=deserializeObject(buffer,_index,options,false)}index=index+objectSize}else if(elementType==BSON.BSON_DATA_ARRAY){var _index=index;var objectSize=buffer[index]|buffer[index+1]<<8|buffer[index+2]<<16|buffer[index+3]<<24;var arrayOptions=options;if(fieldsAsRaw&&fieldsAsRaw[name]){arrayOptions={};for(var n in options)arrayOptions[n]=options[n];arrayOptions["raw"]=true}object[name]=deserializeObject(buffer,_index,arrayOptions,true);index=index+objectSize}else if(elementType==BSON.BSON_DATA_UNDEFINED||elementType==BSON.BSON_DATA_NULL){object[name]=null}else if(elementType==BSON.BSON_DATA_LONG){var lowBits=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;var highBits=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;var long=new Long(lowBits,highBits);if(promoteLongs){object[name]=long.lessThanOrEqual(JS_INT_MAX_LONG)&&long.greaterThanOrEqual(JS_INT_MIN_LONG)?long.toNumber():long}else{object[name]=long}}else if(elementType==BSON.BSON_DATA_BINARY){var binarySize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;var subType=buffer[index++];if(buffer["slice"]!=null){if(subType==Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24}if(promoteBuffers){object[name]=buffer.slice(index,index+binarySize)}else{object[name]=new Binary(buffer.slice(index,index+binarySize),subType)}}else{var _buffer=typeof Uint8Array!="undefined"?new Uint8Array(new ArrayBuffer(binarySize)):new Array(binarySize);if(subType==Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24}for(var i=0;i<binarySize;i++){_buffer[i]=buffer[index+i]}if(promoteBuffers){object[name]=_buffer}else{object[name]=new Binary(_buffer,subType)}}index=index+binarySize}else if(elementType==BSON.BSON_DATA_REGEXP&&bsonRegExp==false){var i=index;while(buffer[i]!==0&&i<buffer.length){i++}if(i>=buffer.length)throw new Error("Bad BSON Document: illegal CString");var source=buffer.toString("utf8",index,i);index=i+1;var i=index;while(buffer[i]!==0&&i<buffer.length){i++}if(i>=buffer.length)throw new Error("Bad BSON Document: illegal CString");var regExpOptions=buffer.toString("utf8",index,i);index=i+1;var optionsArray=new Array(regExpOptions.length);for(var i=0;i<regExpOptions.length;i++){switch(regExpOptions[i]){case"m":optionsArray[i]="m";break;case"s":optionsArray[i]="g";break;case"i":optionsArray[i]="i";break}}object[name]=new RegExp(source,optionsArray.join(""))}else if(elementType==BSON.BSON_DATA_REGEXP&&bsonRegExp==true){var i=index;while(buffer[i]!==0&&i<buffer.length){i++}if(i>=buffer.length)throw new Error("Bad BSON Document: illegal CString");var source=buffer.toString("utf8",index,i);index=i+1;var i=index;while(buffer[i]!==0&&i<buffer.length){i++}if(i>=buffer.length)throw new Error("Bad BSON Document: illegal CString");var regExpOptions=buffer.toString("utf8",index,i);index=i+1;object[name]=new BSONRegExp(source,regExpOptions)}else if(elementType==BSON.BSON_DATA_SYMBOL){var stringSize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;if(stringSize<=0||stringSize>buffer.length-index||buffer[index+stringSize-1]!=0)throw new Error("bad string length in bson");object[name]=new Symbol(buffer.toString("utf8",index,index+stringSize-1));index=index+stringSize}else if(elementType==BSON.BSON_DATA_TIMESTAMP){var lowBits=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;var highBits=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;object[name]=new Timestamp(lowBits,highBits)}else if(elementType==BSON.BSON_DATA_MIN_KEY){object[name]=new MinKey}else if(elementType==BSON.BSON_DATA_MAX_KEY){object[name]=new MaxKey}else if(elementType==BSON.BSON_DATA_CODE){var stringSize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;if(stringSize<=0||stringSize>buffer.length-index||buffer[index+stringSize-1]!=0)throw new Error("bad string length in bson");var functionString=buffer.toString("utf8",index,index+stringSize-1);if(evalFunctions){var value=null;if(cacheFunctions){var hash=cacheFunctionsCrc32?crc32(functionString):functionString;object[name]=isolateEvalWithHash(functionCache,hash,functionString,object)}else{object[name]=isolateEval(functionString)}}else{object[name]=new Code(functionString,{})}index=index+stringSize}else if(elementType==BSON.BSON_DATA_CODE_W_SCOPE){var totalSize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;var stringSize=buffer[index++]|buffer[index++]<<8|buffer[index++]<<16|buffer[index++]<<24;if(stringSize<=0||stringSize>buffer.length-index||buffer[index+stringSize-1]!=0)throw new Error("bad string length in bson");var functionString=buffer.toString("utf8",index,index+stringSize-1);index=index+stringSize;var _index=index;var objectSize=buffer[index]|buffer[index+1]<<8|buffer[index+2]<<16|buffer[index+3]<<24;var scopeObject=deserializeObject(buffer,_index,options,false);index=index+objectSize;if(evalFunctions){var value=null;if(cacheFunctions){var hash=cacheFunctionsCrc32?crc32(functionString):functionString;object[name]=isolateEvalWithHash(functionCache,hash,functionString,object)}else{object[name]=isolateEval(functionString)}object[name].scope=scopeObject}else{object[name]=new Code(functionString,scopeObject)}}}if(object["$id"]!=null)object=new DBRef(object["$ref"],object["$id"],object["$db"]);return object};var isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;if(functionCache[hash]==null){eval("value = "+functionString);functionCache[hash]=value}return functionCache[hash].bind(object)};var isolateEval=function(functionString){var value=null;eval("value = "+functionString);return value};var BSON={};var functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1;BSON.BSON_DATA_STRING=2;BSON.BSON_DATA_OBJECT=3;BSON.BSON_DATA_ARRAY=4;BSON.BSON_DATA_BINARY=5;BSON.BSON_DATA_OID=7;BSON.BSON_DATA_BOOLEAN=8;BSON.BSON_DATA_DATE=9;BSON.BSON_DATA_NULL=10;BSON.BSON_DATA_REGEXP=11;BSON.BSON_DATA_CODE=13;BSON.BSON_DATA_SYMBOL=14;BSON.BSON_DATA_CODE_W_SCOPE=15;BSON.BSON_DATA_INT=16;BSON.BSON_DATA_TIMESTAMP=17;BSON.BSON_DATA_LONG=18;BSON.BSON_DATA_MIN_KEY=255;BSON.BSON_DATA_MAX_KEY=127;BSON.BSON_BINARY_SUBTYPE_DEFAULT=0;BSON.BSON_BINARY_SUBTYPE_FUNCTION=1;BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;BSON.BSON_BINARY_SUBTYPE_UUID=3;BSON.BSON_BINARY_SUBTYPE_MD5=4;BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128;BSON.BSON_INT32_MAX=2147483647;BSON.BSON_INT32_MIN=-2147483648;BSON.BSON_INT64_MAX=Math.pow(2,63)-1;BSON.BSON_INT64_MIN=-Math.pow(2,63);BSON.JS_INT_MAX=9007199254740992;BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},{"../binary":50,"../code":53,"../db_ref":54,"../double":55,"../float_parser":56,"../long":57,"../max_key":59,"../min_key":60,"../objectid":61,"../regexp":65,"../symbol":66,"../timestamp":67,util:98}],64:[function(require,module,exports){(function(Buffer){"use strict";var writeIEEE754=require("../float_parser").writeIEEE754,readIEEE754=require("../float_parser").readIEEE754,Long=require("../long").Long,Map=require("../map"),Double=require("../double").Double,Timestamp=require("../timestamp").Timestamp,ObjectID=require("../objectid").ObjectID,Symbol=require("../symbol").Symbol,Code=require("../code").Code,BSONRegExp=require("../regexp").BSONRegExp,MinKey=require("../min_key").MinKey,MaxKey=require("../max_key").MaxKey,DBRef=require("../db_ref").DBRef,Binary=require("../binary").Binary;var regexp=/\x00/;var isDate=function isDate(d){return typeof d==="object"&&Object.prototype.toString.call(d)==="[object Date]"};var isRegExp=function isRegExp(d){return Object.prototype.toString.call(d)==="[object RegExp]"};var serializeString=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_STRING;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes+1;buffer[index-1]=0;var size=buffer.write(value,index+4,"utf8");buffer[index+3]=size+1>>24&255;buffer[index+2]=size+1>>16&255;buffer[index+1]=size+1>>8&255;buffer[index]=size+1&255;index=index+4+size;buffer[index++]=0;return index};var serializeNumber=function(buffer,key,value,index){if(Math.floor(value)===value&&value>=BSON.JS_INT_MIN&&value<=BSON.JS_INT_MAX){if(value>=BSON.BSON_INT32_MIN&&value<=BSON.BSON_INT32_MAX){buffer[index++]=BSON.BSON_DATA_INT;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;buffer[index++]=value&255;buffer[index++]=value>>8&255;buffer[index++]=value>>16&255;buffer[index++]=value>>24&255}else if(value>=BSON.JS_INT_MIN&&value<=BSON.JS_INT_MAX){buffer[index++]=BSON.BSON_DATA_NUMBER;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;writeIEEE754(buffer,value,index,"little",52,8);index=index+8}else{buffer[index++]=BSON.BSON_DATA_LONG;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var longVal=Long.fromNumber(value);var lowBits=longVal.getLowBits();var highBits=longVal.getHighBits();buffer[index++]=lowBits&255;buffer[index++]=lowBits>>8&255;buffer[index++]=lowBits>>16&255;buffer[index++]=lowBits>>24&255;buffer[index++]=highBits&255;buffer[index++]=highBits>>8&255;buffer[index++]=highBits>>16&255;buffer[index++]=highBits>>24&255}}else{buffer[index++]=BSON.BSON_DATA_NUMBER;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;writeIEEE754(buffer,value,index,"little",52,8);index=index+8}return index};var serializeUndefined=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_NULL;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;return index};var serializeBoolean=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_BOOLEAN;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;buffer[index++]=value?1:0;return index};var serializeDate=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_DATE;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var dateInMilis=Long.fromNumber(value.getTime());var lowBits=dateInMilis.getLowBits();var highBits=dateInMilis.getHighBits();buffer[index++]=lowBits&255;buffer[index++]=lowBits>>8&255;buffer[index++]=lowBits>>16&255;buffer[index++]=lowBits>>24&255;buffer[index++]=highBits&255;buffer[index++]=highBits>>8&255;buffer[index++]=highBits>>16&255;buffer[index++]=highBits>>24&255;return index};var serializeRegExp=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_REGEXP;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;if(value.source&&value.source.match(regexp)!=null){throw Error("value "+value.source+" must not contain null bytes")}index=index+buffer.write(value.source,index,"utf8");buffer[index++]=0;if(value.global)buffer[index++]=115;if(value.ignoreCase)buffer[index++]=105;if(value.multiline)buffer[index++]=109;buffer[index++]=0;return index};var serializeBSONRegExp=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_REGEXP;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;index=index+buffer.write(value.pattern,index,"utf8");buffer[index++]=0;index=index+buffer.write(value.options,index,"utf8");buffer[index++]=0;return index};var serializeMinMax=function(buffer,key,value,index){if(value===null){buffer[index++]=BSON.BSON_DATA_NULL}else if(value instanceof MinKey){buffer[index++]=BSON.BSON_DATA_MIN_KEY}else{buffer[index++]=BSON.BSON_DATA_MAX_KEY}var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;return index};var serializeObjectId=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_OID;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;buffer.write(value.id,index,"binary");return index+12};var serializeBuffer=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_BINARY;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var size=value.length;buffer[index++]=size&255;buffer[index++]=size>>8&255;buffer[index++]=size>>16&255;buffer[index++]=size>>24&255;buffer[index++]=BSON.BSON_BINARY_SUBTYPE_DEFAULT;value.copy(buffer,index,0,size);index=index+size;return index};var serializeObject=function(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined){buffer[index++]=Array.isArray(value)?BSON.BSON_DATA_ARRAY:BSON.BSON_DATA_OBJECT;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var endIndex=serializeInto(buffer,value,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined);var size=endIndex-index;return endIndex};var serializeLong=function(buffer,key,value,index){buffer[index++]=value._bsontype=="Long"?BSON.BSON_DATA_LONG:BSON.BSON_DATA_TIMESTAMP;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var lowBits=value.getLowBits();var highBits=value.getHighBits();buffer[index++]=lowBits&255;buffer[index++]=lowBits>>8&255;buffer[index++]=lowBits>>16&255;buffer[index++]=lowBits>>24&255;buffer[index++]=highBits&255;buffer[index++]=highBits>>8&255;buffer[index++]=highBits>>16&255;buffer[index++]=highBits>>24&255;return index};var serializeDouble=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_NUMBER;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;writeIEEE754(buffer,value,index,"little",52,8);index=index+8;return index};var serializeFunction=function(buffer,key,value,index,checkKeys,depth){buffer[index++]=BSON.BSON_DATA_CODE;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var functionString=value.toString();var size=buffer.write(functionString,index+4,"utf8")+1;buffer[index]=size&255;buffer[index+1]=size>>8&255;buffer[index+2]=size>>16&255;buffer[index+3]=size>>24&255;index=index+4+size-1;buffer[index++]=0;return index};var serializeCode=function(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined){if(value.scope!=null&&Object.keys(value.scope).length>0){buffer[index++]=BSON.BSON_DATA_CODE_W_SCOPE;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var startIndex=index;var functionString=typeof value.code=="string"?value.code:value.code.toString();index=index+4;var codeSize=buffer.write(functionString,index+4,"utf8")+1;buffer[index]=codeSize&255;buffer[index+1]=codeSize>>8&255;buffer[index+2]=codeSize>>16&255;buffer[index+3]=codeSize>>24&255;buffer[index+4+codeSize-1]=0;index=index+codeSize+4;var endIndex=serializeInto(buffer,value.scope,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined);index=endIndex-1;var totalSize=endIndex-startIndex;buffer[startIndex++]=totalSize&255;buffer[startIndex++]=totalSize>>8&255;buffer[startIndex++]=totalSize>>16&255;buffer[startIndex++]=totalSize>>24&255;buffer[index++]=0}else{buffer[index++]=BSON.BSON_DATA_CODE;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var functionString=value.code.toString();var size=buffer.write(functionString,index+4,"utf8")+1;buffer[index]=size&255;buffer[index+1]=size>>8&255;buffer[index+2]=size>>16&255;buffer[index+3]=size>>24&255;index=index+4+size-1;buffer[index++]=0}return index};var serializeBinary=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_BINARY;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var data=value.value(true);var size=value.position;buffer[index++]=size&255;buffer[index++]=size>>8&255;buffer[index++]=size>>16&255;buffer[index++]=size>>24&255;buffer[index++]=value.sub_type;if(value.sub_type==Binary.SUBTYPE_BYTE_ARRAY){buffer[index++]=size&255;buffer[index++]=size>>8&255;buffer[index++]=size>>16&255;buffer[index++]=size>>24&255}data.copy(buffer,index,0,value.position);index=index+value.position;return index};var serializeSymbol=function(buffer,key,value,index){buffer[index++]=BSON.BSON_DATA_SYMBOL;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var size=buffer.write(value.value,index+4,"utf8")+1;buffer[index]=size&255;buffer[index+1]=size>>8&255;buffer[index+2]=size>>16&255;buffer[index+3]=size>>24&255;index=index+4+size-1;buffer[index++]=0;return index};var serializeDBRef=function(buffer,key,value,index,depth,serializeFunctions){buffer[index++]=BSON.BSON_DATA_OBJECT;var numberOfWrittenBytes=buffer.write(key,index,"utf8");index=index+numberOfWrittenBytes;buffer[index++]=0;var startIndex=index;var endIndex;if(null!=value.db){endIndex=serializeInto(buffer,{$ref:value.namespace,$id:value.oid,$db:value.db},false,index,depth+1,serializeFunctions)}else{endIndex=serializeInto(buffer,{$ref:value.namespace,$id:value.oid},false,index,depth+1,serializeFunctions)}var size=endIndex-startIndex;buffer[startIndex++]=size&255;buffer[startIndex++]=size>>8&255;buffer[startIndex++]=size>>16&255;buffer[startIndex++]=size>>24&255;return endIndex};var serializeInto=function serializeInto(buffer,object,checkKeys,startingIndex,depth,serializeFunctions,ignoreUndefined){startingIndex=startingIndex||0;var index=startingIndex+4;var self=this;if(Array.isArray(object)){for(var i=0;i<object.length;i++){var key=""+i;var value=object[i];if(value&&value.toBSON){if(typeof value.toBSON!="function")throw new Error("toBSON is not a function");value=value.toBSON()}var type=typeof value;if(type=="string"){index=serializeString(buffer,key,value,index)}else if(type=="number"){index=serializeNumber(buffer,key,value,index)}else if(type=="boolean"){index=serializeBoolean(buffer,key,value,index)}else if(value instanceof Date||isDate(value)){index=serializeDate(buffer,key,value,index)}else if(type=="undefined"||value==null){index=serializeUndefined(buffer,key,value,index)}else if(value["_bsontype"]=="ObjectID"){index=serializeObjectId(buffer,key,value,index)}else if(Buffer.isBuffer(value)){index=serializeBuffer(buffer,key,value,index)}else if(value instanceof RegExp||isRegExp(value)){index=serializeRegExp(buffer,key,value,index)}else if(type=="object"&&value["_bsontype"]==null){index=serializeObject(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined)}else if(value["_bsontype"]=="Long"||value["_bsontype"]=="Timestamp"){index=serializeLong(buffer,key,value,index)}else if(value["_bsontype"]=="Double"){index=serializeDouble(buffer,key,value,index)}else if(typeof value=="function"&&serializeFunctions){index=serializeFunction(buffer,key,value,index,checkKeys,depth,serializeFunctions)}else if(value["_bsontype"]=="Code"){index=serializeCode(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined)}else if(value["_bsontype"]=="Binary"){index=serializeBinary(buffer,key,value,index)}else if(value["_bsontype"]=="Symbol"){index=serializeSymbol(buffer,key,value,index)}else if(value["_bsontype"]=="DBRef"){index=serializeDBRef(buffer,key,value,index,depth,serializeFunctions)}else if(value["_bsontype"]=="BSONRegExp"){index=serializeBSONRegExp(buffer,key,value,index)}else if(value["_bsontype"]=="MinKey"||value["_bsontype"]=="MaxKey"){index=serializeMinMax(buffer,key,value,index)}}}else if(object instanceof Map){var iterator=object.entries();var done=false;while(!done){var entry=iterator.next();done=entry.done;if(done)continue;var key=entry.value[0];var value=entry.value[1];var type=typeof value;if(key!="$db"&&key!="$ref"&&key!="$id"){if(key.match(regexp)!=null){throw Error("key "+key+" must not contain null bytes")}if(checkKeys){if("$"==key[0]){throw Error("key "+key+" must not start with '$'")}else if(!!~key.indexOf(".")){throw Error("key "+key+" must not contain '.'")}}}if(type=="string"){index=serializeString(buffer,key,value,index)}else if(type=="number"){index=serializeNumber(buffer,key,value,index)}else if(type=="boolean"){index=serializeBoolean(buffer,key,value,index)}else if(value instanceof Date||isDate(value)){index=serializeDate(buffer,key,value,index)}else if(value===undefined&&ignoreUndefined==true){}else if(value===null||value===undefined){index=serializeUndefined(buffer,key,value,index)}else if(value["_bsontype"]=="ObjectID"){index=serializeObjectId(buffer,key,value,index)}else if(Buffer.isBuffer(value)){index=serializeBuffer(buffer,key,value,index)}else if(value instanceof RegExp||isRegExp(value)){index=serializeRegExp(buffer,key,value,index)}else if(type=="object"&&value["_bsontype"]==null){index=serializeObject(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined)}else if(value["_bsontype"]=="Long"||value["_bsontype"]=="Timestamp"){index=serializeLong(buffer,key,value,index)}else if(value["_bsontype"]=="Double"){index=serializeDouble(buffer,key,value,index)}else if(value["_bsontype"]=="Code"){index=serializeCode(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined)}else if(typeof value=="function"&&serializeFunctions){index=serializeFunction(buffer,key,value,index,checkKeys,depth,serializeFunctions)}else if(value["_bsontype"]=="Binary"){index=serializeBinary(buffer,key,value,index)}else if(value["_bsontype"]=="Symbol"){index=serializeSymbol(buffer,key,value,index)}else if(value["_bsontype"]=="DBRef"){index=serializeDBRef(buffer,key,value,index,depth,serializeFunctions)}else if(value["_bsontype"]=="BSONRegExp"){index=serializeBSONRegExp(buffer,key,value,index)}else if(value["_bsontype"]=="MinKey"||value["_bsontype"]=="MaxKey"){index=serializeMinMax(buffer,key,value,index)}}}else{if(object.toBSON){if(typeof object.toBSON!="function")throw new Error("toBSON is not a function");object=object.toBSON();if(object!=null&&typeof object!="object")throw new Error("toBSON function did not return an object")}for(var key in object){var value=object[key];if(value&&value.toBSON){if(typeof value.toBSON!="function")throw new Error("toBSON is not a function");value=value.toBSON()}var type=typeof value;if(key!="$db"&&key!="$ref"&&key!="$id"){if(key.match(regexp)!=null){throw Error("key "+key+" must not contain null bytes")}if(checkKeys){if("$"==key[0]){throw Error("key "+key+" must not start with '$'")}else if(!!~key.indexOf(".")){throw Error("key "+key+" must not contain '.'")}}}if(type=="string"){index=serializeString(buffer,key,value,index)}else if(type=="number"){index=serializeNumber(buffer,key,value,index)}else if(type=="boolean"){index=serializeBoolean(buffer,key,value,index)}else if(value instanceof Date||isDate(value)){index=serializeDate(buffer,key,value,index)}else if(value===undefined&&ignoreUndefined==true){}else if(value===null||value===undefined){index=serializeUndefined(buffer,key,value,index)}else if(value["_bsontype"]=="ObjectID"){index=serializeObjectId(buffer,key,value,index)}else if(Buffer.isBuffer(value)){index=serializeBuffer(buffer,key,value,index)}else if(value instanceof RegExp||isRegExp(value)){index=serializeRegExp(buffer,key,value,index)}else if(type=="object"&&value["_bsontype"]==null){index=serializeObject(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined)}else if(value["_bsontype"]=="Long"||value["_bsontype"]=="Timestamp"){index=serializeLong(buffer,key,value,index)}else if(value["_bsontype"]=="Double"){index=serializeDouble(buffer,key,value,index)}else if(value["_bsontype"]=="Code"){index=serializeCode(buffer,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined)}else if(typeof value=="function"&&serializeFunctions){index=serializeFunction(buffer,key,value,index,checkKeys,depth,serializeFunctions)}else if(value["_bsontype"]=="Binary"){index=serializeBinary(buffer,key,value,index)}else if(value["_bsontype"]=="Symbol"){index=serializeSymbol(buffer,key,value,index)}else if(value["_bsontype"]=="DBRef"){index=serializeDBRef(buffer,key,value,index,depth,serializeFunctions)}else if(value["_bsontype"]=="BSONRegExp"){index=serializeBSONRegExp(buffer,key,value,index)}else if(value["_bsontype"]=="MinKey"||value["_bsontype"]=="MaxKey"){index=serializeMinMax(buffer,key,value,index)}}}buffer[index++]=0;var size=index-startingIndex;buffer[startingIndex++]=size&255;buffer[startingIndex++]=size>>8&255;buffer[startingIndex++]=size>>16&255;buffer[startingIndex++]=size>>24&255;return index};var BSON={};var functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1;BSON.BSON_DATA_STRING=2;BSON.BSON_DATA_OBJECT=3;BSON.BSON_DATA_ARRAY=4;BSON.BSON_DATA_BINARY=5;BSON.BSON_DATA_OID=7;BSON.BSON_DATA_BOOLEAN=8;BSON.BSON_DATA_DATE=9;BSON.BSON_DATA_NULL=10;BSON.BSON_DATA_REGEXP=11;BSON.BSON_DATA_CODE=13;BSON.BSON_DATA_SYMBOL=14;BSON.BSON_DATA_CODE_W_SCOPE=15;BSON.BSON_DATA_INT=16;BSON.BSON_DATA_TIMESTAMP=17;BSON.BSON_DATA_LONG=18;BSON.BSON_DATA_MIN_KEY=255;BSON.BSON_DATA_MAX_KEY=127;BSON.BSON_BINARY_SUBTYPE_DEFAULT=0;BSON.BSON_BINARY_SUBTYPE_FUNCTION=1;BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;BSON.BSON_BINARY_SUBTYPE_UUID=3;BSON.BSON_BINARY_SUBTYPE_MD5=4;BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128;BSON.BSON_INT32_MAX=2147483647;BSON.BSON_INT32_MIN=-2147483648;BSON.BSON_INT64_MAX=Math.pow(2,63)-1;BSON.BSON_INT64_MIN=-Math.pow(2,63);BSON.JS_INT_MAX=9007199254740992;BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=serializeInto}).call(this,require("buffer").Buffer)},{"../binary":50,"../code":53,"../db_ref":54,"../double":55,"../float_parser":56,"../long":57,"../map":58,"../max_key":59,"../min_key":60,"../objectid":61,"../regexp":65,"../symbol":66,"../timestamp":67,buffer:91}],65:[function(require,module,exports){function BSONRegExp(pattern,options){if(!(this instanceof BSONRegExp))return new BSONRegExp;this._bsontype="BSONRegExp";this.pattern=pattern;this.options=options;for(var i=0;i<options.length;i++){if(!(this.options[i]=="i"||this.options[i]=="m"||this.options[i]=="x"||this.options[i]=="l"||this.options[i]=="s"||this.options[i]=="u")){throw new Error("the regular expression options ["+this.options[i]+"] is not supported")}}}module.exports=BSONRegExp;module.exports.BSONRegExp=BSONRegExp},{}],66:[function(require,module,exports){function Symbol(value){if(!(this instanceof Symbol))return new Symbol(value);this._bsontype="Symbol";this.value=value}Symbol.prototype.valueOf=function(){return this.value};Symbol.prototype.toString=function(){return this.value};Symbol.prototype.inspect=function(){return this.value};Symbol.prototype.toJSON=function(){return this.value};module.exports=Symbol;module.exports.Symbol=Symbol},{}],67:[function(require,module,exports){function Timestamp(low,high){if(!(this instanceof Timestamp))return new Timestamp(low,high);this._bsontype="Timestamp";this.low_=low|0;this.high_=high|0}Timestamp.prototype.toInt=function(){return this.low_};Timestamp.prototype.toNumber=function(){return this.high_*Timestamp.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Timestamp.prototype.toJSON=function(){return this.toString()};Timestamp.prototype.toString=function(opt_radix){var radix=opt_radix||10;if(radix<2||36<radix){throw Error("radix out of range: "+radix)}if(this.isZero()){return"0"}if(this.isNegative()){if(this.equals(Timestamp.MIN_VALUE)){var radixTimestamp=Timestamp.fromNumber(radix);var div=this.div(radixTimestamp);var rem=div.multiply(radixTimestamp).subtract(this);return div.toString(radix)+rem.toInt().toString(radix)}else{return"-"+this.negate().toString(radix)}}var radixToPower=Timestamp.fromNumber(Math.pow(radix,6));var rem=this;var result="";while(true){var remDiv=rem.div(radixToPower);var intval=rem.subtract(remDiv.multiply(radixToPower)).toInt();var digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6){digits="0"+digits}result=""+digits+result}}};Timestamp.prototype.getHighBits=function(){return this.high_};Timestamp.prototype.getLowBits=function(){return this.low_};Timestamp.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:Timestamp.TWO_PWR_32_DBL_+this.low_};Timestamp.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Timestamp.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var val=this.high_!=0?this.high_:this.low_;for(var bit=31;bit>0;bit--){if((val&1<<bit)!=0){break}}return this.high_!=0?bit+33:bit+1}};Timestamp.prototype.isZero=function(){return this.high_==0&&this.low_==0};Timestamp.prototype.isNegative=function(){return this.high_<0};Timestamp.prototype.isOdd=function(){return(this.low_&1)==1};Timestamp.prototype.equals=function(other){return this.high_==other.high_&&this.low_==other.low_;
};Timestamp.prototype.notEquals=function(other){return this.high_!=other.high_||this.low_!=other.low_};Timestamp.prototype.lessThan=function(other){return this.compare(other)<0};Timestamp.prototype.lessThanOrEqual=function(other){return this.compare(other)<=0};Timestamp.prototype.greaterThan=function(other){return this.compare(other)>0};Timestamp.prototype.greaterThanOrEqual=function(other){return this.compare(other)>=0};Timestamp.prototype.compare=function(other){if(this.equals(other)){return 0}var thisNeg=this.isNegative();var otherNeg=other.isNegative();if(thisNeg&&!otherNeg){return-1}if(!thisNeg&&otherNeg){return 1}if(this.subtract(other).isNegative()){return-1}else{return 1}};Timestamp.prototype.negate=function(){if(this.equals(Timestamp.MIN_VALUE)){return Timestamp.MIN_VALUE}else{return this.not().add(Timestamp.ONE)}};Timestamp.prototype.add=function(other){var a48=this.high_>>>16;var a32=this.high_&65535;var a16=this.low_>>>16;var a00=this.low_&65535;var b48=other.high_>>>16;var b32=other.high_&65535;var b16=other.low_>>>16;var b00=other.low_&65535;var c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return Timestamp.fromBits(c16<<16|c00,c48<<16|c32)};Timestamp.prototype.subtract=function(other){return this.add(other.negate())};Timestamp.prototype.multiply=function(other){if(this.isZero()){return Timestamp.ZERO}else if(other.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){return other.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}else if(other.equals(Timestamp.MIN_VALUE)){return this.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}if(this.isNegative()){if(other.isNegative()){return this.negate().multiply(other.negate())}else{return this.negate().multiply(other).negate()}}else if(other.isNegative()){return this.multiply(other.negate()).negate()}if(this.lessThan(Timestamp.TWO_PWR_24_)&&other.lessThan(Timestamp.TWO_PWR_24_)){return Timestamp.fromNumber(this.toNumber()*other.toNumber())}var a48=this.high_>>>16;var a32=this.high_&65535;var a16=this.low_>>>16;var a00=this.low_&65535;var b48=other.high_>>>16;var b32=other.high_&65535;var b16=other.low_>>>16;var b00=other.low_&65535;var c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return Timestamp.fromBits(c16<<16|c00,c48<<16|c32)};Timestamp.prototype.div=function(other){if(other.isZero()){throw Error("division by zero")}else if(this.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){if(other.equals(Timestamp.ONE)||other.equals(Timestamp.NEG_ONE)){return Timestamp.MIN_VALUE}else if(other.equals(Timestamp.MIN_VALUE)){return Timestamp.ONE}else{var halfThis=this.shiftRight(1);var approx=halfThis.div(other).shiftLeft(1);if(approx.equals(Timestamp.ZERO)){return other.isNegative()?Timestamp.ONE:Timestamp.NEG_ONE}else{var rem=this.subtract(other.multiply(approx));var result=approx.add(rem.div(other));return result}}}else if(other.equals(Timestamp.MIN_VALUE)){return Timestamp.ZERO}if(this.isNegative()){if(other.isNegative()){return this.negate().div(other.negate())}else{return this.negate().div(other).negate()}}else if(other.isNegative()){return this.div(other.negate()).negate()}var res=Timestamp.ZERO;var rem=this;while(rem.greaterThanOrEqual(other)){var approx=Math.max(1,Math.floor(rem.toNumber()/other.toNumber()));var log2=Math.ceil(Math.log(approx)/Math.LN2);var delta=log2<=48?1:Math.pow(2,log2-48);var approxRes=Timestamp.fromNumber(approx);var approxRem=approxRes.multiply(other);while(approxRem.isNegative()||approxRem.greaterThan(rem)){approx-=delta;approxRes=Timestamp.fromNumber(approx);approxRem=approxRes.multiply(other)}if(approxRes.isZero()){approxRes=Timestamp.ONE}res=res.add(approxRes);rem=rem.subtract(approxRem)}return res};Timestamp.prototype.modulo=function(other){return this.subtract(this.div(other).multiply(other))};Timestamp.prototype.not=function(){return Timestamp.fromBits(~this.low_,~this.high_)};Timestamp.prototype.and=function(other){return Timestamp.fromBits(this.low_&other.low_,this.high_&other.high_)};Timestamp.prototype.or=function(other){return Timestamp.fromBits(this.low_|other.low_,this.high_|other.high_)};Timestamp.prototype.xor=function(other){return Timestamp.fromBits(this.low_^other.low_,this.high_^other.high_)};Timestamp.prototype.shiftLeft=function(numBits){numBits&=63;if(numBits==0){return this}else{var low=this.low_;if(numBits<32){var high=this.high_;return Timestamp.fromBits(low<<numBits,high<<numBits|low>>>32-numBits)}else{return Timestamp.fromBits(0,low<<numBits-32)}}};Timestamp.prototype.shiftRight=function(numBits){numBits&=63;if(numBits==0){return this}else{var high=this.high_;if(numBits<32){var low=this.low_;return Timestamp.fromBits(low>>>numBits|high<<32-numBits,high>>numBits)}else{return Timestamp.fromBits(high>>numBits-32,high>=0?0:-1)}}};Timestamp.prototype.shiftRightUnsigned=function(numBits){numBits&=63;if(numBits==0){return this}else{var high=this.high_;if(numBits<32){var low=this.low_;return Timestamp.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits)}else if(numBits==32){return Timestamp.fromBits(high,0)}else{return Timestamp.fromBits(high>>>numBits-32,0)}}};Timestamp.fromInt=function(value){if(-128<=value&&value<128){var cachedObj=Timestamp.INT_CACHE_[value];if(cachedObj){return cachedObj}}var obj=new Timestamp(value|0,value<0?-1:0);if(-128<=value&&value<128){Timestamp.INT_CACHE_[value]=obj}return obj};Timestamp.fromNumber=function(value){if(isNaN(value)||!isFinite(value)){return Timestamp.ZERO}else if(value<=-Timestamp.TWO_PWR_63_DBL_){return Timestamp.MIN_VALUE}else if(value+1>=Timestamp.TWO_PWR_63_DBL_){return Timestamp.MAX_VALUE}else if(value<0){return Timestamp.fromNumber(-value).negate()}else{return new Timestamp(value%Timestamp.TWO_PWR_32_DBL_|0,value/Timestamp.TWO_PWR_32_DBL_|0)}};Timestamp.fromBits=function(lowBits,highBits){return new Timestamp(lowBits,highBits)};Timestamp.fromString=function(str,opt_radix){if(str.length==0){throw Error("number format error: empty string")}var radix=opt_radix||10;if(radix<2||36<radix){throw Error("radix out of range: "+radix)}if(str.charAt(0)=="-"){return Timestamp.fromString(str.substring(1),radix).negate()}else if(str.indexOf("-")>=0){throw Error('number format error: interior "-" character: '+str)}var radixToPower=Timestamp.fromNumber(Math.pow(radix,8));var result=Timestamp.ZERO;for(var i=0;i<str.length;i+=8){var size=Math.min(8,str.length-i);var value=parseInt(str.substring(i,i+size),radix);if(size<8){var power=Timestamp.fromNumber(Math.pow(radix,size));result=result.multiply(power).add(Timestamp.fromNumber(value))}else{result=result.multiply(radixToPower);result=result.add(Timestamp.fromNumber(value))}}return result};Timestamp.INT_CACHE_={};Timestamp.TWO_PWR_16_DBL_=1<<16;Timestamp.TWO_PWR_24_DBL_=1<<24;Timestamp.TWO_PWR_32_DBL_=Timestamp.TWO_PWR_16_DBL_*Timestamp.TWO_PWR_16_DBL_;Timestamp.TWO_PWR_31_DBL_=Timestamp.TWO_PWR_32_DBL_/2;Timestamp.TWO_PWR_48_DBL_=Timestamp.TWO_PWR_32_DBL_*Timestamp.TWO_PWR_16_DBL_;Timestamp.TWO_PWR_64_DBL_=Timestamp.TWO_PWR_32_DBL_*Timestamp.TWO_PWR_32_DBL_;Timestamp.TWO_PWR_63_DBL_=Timestamp.TWO_PWR_64_DBL_/2;Timestamp.ZERO=Timestamp.fromInt(0);Timestamp.ONE=Timestamp.fromInt(1);Timestamp.NEG_ONE=Timestamp.fromInt(-1);Timestamp.MAX_VALUE=Timestamp.fromBits(4294967295|0,2147483647|0);Timestamp.MIN_VALUE=Timestamp.fromBits(0,2147483648|0);Timestamp.TWO_PWR_24_=Timestamp.fromInt(1<<24);module.exports=Timestamp;module.exports.Timestamp=Timestamp},{}],68:[function(require,module,exports){module.exports={hook:function(name,fn,errorCb){if(arguments.length===1&&typeof name==="object"){for(var k in name){this.hook(k,name[k])}return}var proto=this.prototype||this,pres=proto._pres=proto._pres||{},posts=proto._posts=proto._posts||{};pres[name]=pres[name]||[];posts[name]=posts[name]||[];proto[name]=function(){var self=this,hookArgs,lastArg=arguments[arguments.length-1],pres=this._pres[name],posts=this._posts[name],_total=pres.length,_current=-1,_asyncsLeft=proto[name].numAsyncPres,_asyncsDone=function(err){if(err){return handleError(err)}--_asyncsLeft||_done.apply(self,hookArgs)},handleError=function(err){if("function"==typeof lastArg)return lastArg(err);if(errorCb)return errorCb.call(self,err);throw err},_next=function(){if(arguments[0]instanceof Error){return handleError(arguments[0])}var _args=Array.prototype.slice.call(arguments),currPre,preArgs;if(_args.length&&!(arguments[0]==null&&typeof lastArg==="function"))hookArgs=_args;if(++_current<_total){currPre=pres[_current];if(currPre.isAsync&&currPre.length<2)throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)");if(currPre.length<1)throw new Error("Your pre must have a next argument -- e.g., function (next, ...)");preArgs=(currPre.isAsync?[once(_next),once(_asyncsDone)]:[once(_next)]).concat(hookArgs);return currPre.apply(self,preArgs)}else if(!_asyncsLeft){return _done.apply(self,hookArgs)}},_done=function(){var args_=Array.prototype.slice.call(arguments),ret,total_,current_,next_,done_,postArgs;if(_current===_total){next_=function(){if(arguments[0]instanceof Error){return handleError(arguments[0])}var args_=Array.prototype.slice.call(arguments,1),currPost,postArgs;if(args_.length)hookArgs=args_;if(++current_<total_){currPost=posts[current_];if(currPost.length<1)throw new Error("Your post must have a next argument -- e.g., function (next, ...)");postArgs=[once(next_)].concat(hookArgs);return currPost.apply(self,postArgs)}else if(typeof lastArg==="function"){return lastArg.apply(self,arguments)}};if(typeof lastArg==="function"){args_[args_.length-1]=once(next_)}total_=posts.length;current_=-1;ret=fn.apply(self,args_);if(total_&&typeof lastArg!=="function")return next_();return ret}};return _next.apply(this,arguments)};proto[name].numAsyncPres=0;return this},pre:function(name,isAsync,fn,errorCb){if("boolean"!==typeof arguments[1]){errorCb=fn;fn=isAsync;isAsync=false}var proto=this.prototype||this,pres=proto._pres=proto._pres||{};this._lazySetupHooks(proto,name,errorCb);if(fn.isAsync=isAsync){proto[name].numAsyncPres++}(pres[name]=pres[name]||[]).push(fn);return this},post:function(name,isAsync,fn){if(arguments.length===2){fn=isAsync;isAsync=false}var proto=this.prototype||this,posts=proto._posts=proto._posts||{};this._lazySetupHooks(proto,name);(posts[name]=posts[name]||[]).push(fn);return this},removePre:function(name,fnToRemove){var proto=this.prototype||this,pres=proto._pres||(proto._pres||{});if(!pres[name])return this;if(arguments.length===1){pres[name].length=0}else{pres[name]=pres[name].filter(function(currFn){return currFn!==fnToRemove})}return this},removePost:function(name,fnToRemove){var proto=this.prototype||this,posts=proto._posts||(proto._posts||{});if(!posts[name])return this;if(arguments.length===1){posts[name].length=0}else{posts[name]=posts[name].filter(function(currFn){return currFn!==fnToRemove})}return this},_lazySetupHooks:function(proto,methodName,errorCb){if("undefined"===typeof proto[methodName].numAsyncPres){this.hook(methodName,proto[methodName],errorCb)}}};function once(fn,scope){return function fnWrapper(){if(fnWrapper.hookCalled)return;fnWrapper.hookCalled=true;var ret=fn.apply(scope,arguments);if(ret&&ret.then){ret.then(function(){},function(){})}}}},{}],69:[function(require,module,exports){(function(process){"use strict";function Kareem(){this._pres={};this._posts={}}Kareem.prototype.execPre=function(name,context,callback){var pres=this._pres[name]||[];var numPres=pres.length;var numAsyncPres=pres.numAsync||0;var currentPre=0;var asyncPresLeft=numAsyncPres;var done=false;if(!numPres){return process.nextTick(function(){callback(null)})}var next=function(){if(currentPre>=numPres){return}var pre=pres[currentPre];if(pre.isAsync){pre.fn.call(context,function(error){if(error){if(done){return}done=true;return callback(error)}++currentPre;next.apply(context,arguments)},function(error){if(error){if(done){return}done=true;return callback(error)}if(--numAsyncPres===0){return callback(null)}})}else if(pre.fn.length>0){var args=[function(error){if(error){if(done){return}done=true;return callback(error)}if(++currentPre>=numPres){if(asyncPresLeft>0){return}else{return callback(null)}}next.apply(context,arguments)}];if(arguments.length>=2){for(var i=1;i<arguments.length;++i){args.push(arguments[i])}}pre.fn.apply(context,args)}else{pre.fn.call(context);if(++currentPre>=numPres){if(asyncPresLeft>0){return}else{return process.nextTick(function(){callback(null)})}}next()}};next()};Kareem.prototype.execPost=function(name,context,args,callback){var posts=this._posts[name]||[];var numPosts=posts.length;var currentPost=0;if(!numPosts){return process.nextTick(function(){callback.apply(null,[null].concat(args))})}var next=function(){var post=posts[currentPost];if(post.length>args.length){post.apply(context,args.concat(function(error){if(error){return callback(error)}if(++currentPost>=numPosts){return callback.apply(null,[null].concat(args))}next()}))}else{post.apply(context,args);if(++currentPost>=numPosts){return callback.apply(null,[null].concat(args))}next()}};next()};Kareem.prototype.wrap=function(name,fn,context,args,useLegacyPost){var lastArg=args.length>0?args[args.length-1]:null;var _this=this;this.execPre(name,context,function(error){if(error){if(typeof lastArg==="function"){return lastArg(error)}return}var end=typeof lastArg==="function"?args.length-1:args.length;fn.apply(context,args.slice(0,end).concat(function(){if(arguments[0]){return typeof lastArg==="function"?lastArg(arguments[0]):undefined}if(useLegacyPost&&typeof lastArg==="function"){lastArg.apply(context,arguments)}var argsWithoutError=Array.prototype.slice.call(arguments,1);_this.execPost(name,context,argsWithoutError,function(){if(arguments[0]){return typeof lastArg==="function"?lastArg(arguments[0]):undefined}return typeof lastArg==="function"&&!useLegacyPost?lastArg.apply(context,arguments):undefined})}))})};Kareem.prototype.createWrapper=function(name,fn,context){var _this=this;return function(){var args=Array.prototype.slice.call(arguments);_this.wrap(name,fn,context,args)}};Kareem.prototype.pre=function(name,isAsync,fn,error){if(typeof arguments[1]!=="boolean"){error=fn;fn=isAsync;isAsync=false}this._pres[name]=this._pres[name]||[];var pres=this._pres[name];if(isAsync){pres.numAsync=pres.numAsync||0;++pres.numAsync}pres.push({fn:fn,isAsync:isAsync});return this};Kareem.prototype.post=function(name,fn){(this._posts[name]=this._posts[name]||[]).push(fn);return this};Kareem.prototype.clone=function(){var n=new Kareem;for(var key in this._pres){n._pres[key]=this._pres[key].slice()}for(var key in this._posts){n._posts[key]=this._posts[key].slice()}return n};module.exports=Kareem}).call(this,require("_process"))},{_process:96}],70:[function(require,module,exports){module.exports=exports=require("./lib")},{"./lib":71}],71:[function(require,module,exports){exports.get=function(path,o,special,map){var lookup;if("function"==typeof special){if(special.length<2){map=special;special=undefined}else{lookup=special;special=undefined}}map||(map=K);var parts="string"==typeof path?path.split("."):path;if(!Array.isArray(parts)){throw new TypeError("Invalid `path`. Must be either string or array")}var obj=o,part;for(var i=0;i<parts.length;++i){part=parts[i];if(Array.isArray(obj)&&!/^\d+$/.test(part)){var paths=parts.slice(i);return obj.map(function(item){return item?exports.get(paths,item,special||lookup,map):map(undefined)})}if(lookup){obj=lookup(obj,part)}else{obj=special&&obj[special]?obj[special][part]:obj[part]}if(!obj)return map(obj)}return map(obj)};exports.set=function(path,val,o,special,map,_copying){var lookup;if("function"==typeof special){if(special.length<2){map=special;special=undefined}else{lookup=special;special=undefined}}map||(map=K);var parts="string"==typeof path?path.split("."):path;if(!Array.isArray(parts)){throw new TypeError("Invalid `path`. Must be either string or array")}if(null==o)return;var copy=_copying||/\$/.test(path),obj=o,part;for(var i=0,len=parts.length-1;i<len;++i){part=parts[i];if("$"==part){if(i==len-1){break}else{continue}}if(Array.isArray(obj)&&!/^\d+$/.test(part)){var paths=parts.slice(i);if(!copy&&Array.isArray(val)){for(var j=0;j<obj.length&&j<val.length;++j){exports.set(paths,val[j],obj[j],special||lookup,map,copy)}}else{for(var j=0;j<obj.length;++j){exports.set(paths,val,obj[j],special||lookup,map,copy)}}return}if(lookup){obj=lookup(obj,part)}else{obj=special&&obj[special]?obj[special][part]:obj[part]}if(!obj)return}part=parts[len];if(special&&obj[special]){obj=obj[special]}if(Array.isArray(obj)&&!/^\d+$/.test(part)){if(!copy&&Array.isArray(val)){for(var item,j=0;j<obj.length&&j<val.length;++j){item=obj[j];if(item){if(lookup){lookup(item,part,map(val[j]))}else{if(item[special])item=item[special];item[part]=map(val[j])}}}}else{for(var j=0;j<obj.length;++j){item=obj[j];if(item){if(lookup){lookup(item,part,map(val))}else{if(item[special])item=item[special];item[part]=map(val)}}}}}else{if(lookup){lookup(obj,part,map(val))}else{obj[part]=map(val)}}};function K(v){return v}},{}],72:[function(require,module,exports){(function(process){"use strict";var util=require("util");var EventEmitter=require("events").EventEmitter;function toArray(arr,start,end){return Array.prototype.slice.call(arr,start,end)}function strongUnshift(x,arrLike){var arr=toArray(arrLike);arr.unshift(x);return arr}function Promise(back){this.emitter=new EventEmitter;this.emitted={};this.ended=false;if("function"==typeof back){this.ended=true;this.onResolve(back)}}module.exports=Promise;Promise.SUCCESS="fulfill";Promise.FAILURE="reject";Promise.prototype.on=function(event,callback){if(this.emitted[event])callback.apply(undefined,this.emitted[event]);else this.emitter.on(event,callback);return this};Promise.prototype.safeEmit=function(event){if(event==Promise.SUCCESS||event==Promise.FAILURE){if(this.emitted[Promise.SUCCESS]||this.emitted[Promise.FAILURE]){return this}this.emitted[event]=toArray(arguments,1)}this.emitter.emit.apply(this.emitter,arguments);return this};Promise.prototype.hasRejectListeners=function(){return EventEmitter.listenerCount(this.emitter,Promise.FAILURE)>0};Promise.prototype.fulfill=function(){return this.safeEmit.apply(this,strongUnshift(Promise.SUCCESS,arguments))};Promise.prototype.reject=function(reason){if(this.ended&&!this.hasRejectListeners())throw reason;return this.safeEmit(Promise.FAILURE,reason)};Promise.prototype.resolve=function(err,val){if(err)return this.reject(err);return this.fulfill(val)};Promise.prototype.onFulfill=function(fn){if(!fn)return this;if("function"!=typeof fn)throw new TypeError("fn should be a function");return this.on(Promise.SUCCESS,fn)};Promise.prototype.onReject=function(fn){if(!fn)return this;if("function"!=typeof fn)throw new TypeError("fn should be a function");return this.on(Promise.FAILURE,fn)};Promise.prototype.onResolve=function(fn){if(!fn)return this;if("function"!=typeof fn)throw new TypeError("fn should be a function");this.on(Promise.FAILURE,function(err){fn.call(this,err)});this.on(Promise.SUCCESS,function(){fn.apply(this,strongUnshift(null,arguments))});return this};Promise.prototype.then=function(onFulfill,onReject){var newPromise=new Promise;if("function"==typeof onFulfill){this.onFulfill(handler(newPromise,onFulfill))}else{this.onFulfill(newPromise.fulfill.bind(newPromise))}if("function"==typeof onReject){this.onReject(handler(newPromise,onReject))}else{this.onReject(newPromise.reject.bind(newPromise))}return newPromise};function handler(promise,fn){function newTickHandler(){var pDomain=promise.emitter.domain;if(pDomain&&pDomain!==process.domain)pDomain.enter();try{var x=fn.apply(undefined,boundHandler.args)}catch(err){promise.reject(err);return}resolve(promise,x)}function boundHandler(){boundHandler.args=arguments;process.nextTick(newTickHandler)}return boundHandler}function resolve(promise,x){function fulfillOnce(){if(done++)return;resolve.apply(undefined,strongUnshift(promise,arguments))}function rejectOnce(reason){if(done++)return;promise.reject(reason)}if(promise===x){promise.reject(new TypeError("promise and x are the same"));return}var rest=toArray(arguments,1);var type=typeof x;if("undefined"==type||null==x||!("object"==type||"function"==type)){promise.fulfill.apply(promise,rest);return}try{var theThen=x.then}catch(err){promise.reject(err);return}if("function"!=typeof theThen){promise.fulfill.apply(promise,rest);return}var done=0;try{var ret=theThen.call(x,fulfillOnce,rejectOnce);return ret}catch(err){if(done++)return;promise.reject(err)}}Promise.prototype.end=Promise.prototype["catch"]=function(onReject){if(!onReject&&!this.hasRejectListeners())onReject=function idRejector(e){throw e};this.onReject(onReject);this.ended=true;return this};Promise.trace=function(p,name){p.then(function(){console.log("%s fulfill %j",name,toArray(arguments))},function(){console.log("%s reject %j",name,toArray(arguments))})};Promise.prototype.chain=function(p2){var p1=this;p1.onFulfill(p2.fulfill.bind(p2));p1.onReject(p2.reject.bind(p2));return p2};Promise.prototype.all=function(promiseOfArr){var pRet=new Promise;this.then(promiseOfArr).then(function(promiseArr){var count=0;var ret=[];var errSentinel;if(!promiseArr.length)pRet.resolve();promiseArr.forEach(function(promise,index){if(errSentinel)return;count++;promise.then(function(val){if(errSentinel)return;ret[index]=val;--count;if(count==0)pRet.fulfill(ret)},function(err){if(errSentinel)return;errSentinel=err;pRet.reject(err)})});return pRet},pRet.reject.bind(pRet));return pRet};Promise.hook=function(arr){var p1=new Promise;var pFinal=new Promise;var signalP=function(){--count;if(count==0)pFinal.fulfill();return pFinal};var count=1;var ps=p1;arr.forEach(function(hook){ps=ps.then(function(){var p=new Promise;count++;hook(p.resolve.bind(p),signalP);return p})});ps=ps.then(signalP);p1.resolve();return ps};Promise.fulfilled=function fulfilled(){var p=new Promise;p.fulfill.apply(p,arguments);return p};Promise.rejected=function rejected(reason){return(new Promise).reject(reason)};Promise.deferred=function deferred(){var p=new Promise;return{promise:p,reject:p.reject.bind(p),resolve:p.fulfill.bind(p),callback:p.resolve.bind(p)}}}).call(this,require("_process"))},{_process:96,events:94,util:98}],73:[function(require,module,exports){"use strict";var methods=["find","findOne","update","remove","count","distinct","findAndModify","aggregate","findStream"];function Collection(){}for(var i=0,len=methods.length;i<len;++i){var method=methods[i];Collection.prototype[method]=notImplemented(method)}module.exports=exports=Collection;Collection.methods=methods;function notImplemented(method){return function(){throw new Error("collection."+method+" not implemented")}}},{}],74:[function(require,module,exports){"use strict";var env=require("../env");if("unknown"==env.type){throw new Error("Unknown environment")}module.exports=env.isNode?require("./node"):env.isMongo?require("./collection"):require("./collection")},{"../env":76,"./collection":73,"./node":75}],75:[function(require,module,exports){"use strict";var Collection=require("./collection");var utils=require("../utils");function NodeCollection(col){this.collection=col;this.collectionName=col.collectionName}utils.inherits(NodeCollection,Collection);NodeCollection.prototype.find=function(match,options,cb){this.collection.find(match,options,function(err,cursor){if(err)return cb(err);cursor.toArray(cb)})};NodeCollection.prototype.findOne=function(match,options,cb){this.collection.findOne(match,options,cb)};NodeCollection.prototype.count=function(match,options,cb){this.collection.count(match,options,cb)};NodeCollection.prototype.distinct=function(prop,match,options,cb){this.collection.distinct(prop,match,options,cb)};NodeCollection.prototype.update=function(match,update,options,cb){this.collection.update(match,update,options,cb)};NodeCollection.prototype.remove=function(match,options,cb){this.collection.remove(match,options,cb)};NodeCollection.prototype.findAndModify=function(match,update,options,cb){var sort=Array.isArray(options.sort)?options.sort:[];this.collection.findAndModify(match,sort,update,options,cb)};NodeCollection.prototype.findStream=function(match,findOptions,streamOptions){return this.collection.find(match,findOptions).stream(streamOptions)};module.exports=exports=NodeCollection},{"../utils":79,"./collection":73}],76:[function(require,module,exports){(function(process,global,Buffer){"use strict";exports.isNode="undefined"!=typeof process&&"object"==typeof module&&"object"==typeof global&&"function"==typeof Buffer&&process.argv;exports.isMongo=!exports.isNode&&"function"==typeof printjson&&"function"==typeof ObjectId&&"function"==typeof rs&&"function"==typeof sh;exports.isBrowser=!exports.isNode&&!exports.isMongo&&"undefined"!=typeof window;exports.type=exports.isNode?"node":exports.isMongo?"mongo":exports.isBrowser?"browser":"unknown"}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{_process:96,buffer:91}],77:[function(require,module,exports){"use strict";var slice=require("sliced");var assert=require("assert");var util=require("util");var utils=require("./utils");var debug=require("debug")("mquery");function Query(criteria,options){if(!(this instanceof Query))return new Query(criteria,options);var proto=this.constructor.prototype;this.op=proto.op||undefined;this.options={};this.setOptions(proto.options);this._conditions=proto._conditions?utils.clone(proto._conditions):{};this._fields=proto._fields?utils.clone(proto._fields):undefined;this._update=proto._update?utils.clone(proto._update):undefined;this._path=proto._path||undefined;this._distinct=proto._distinct||undefined;this._collection=proto._collection||undefined;this._traceFunction=proto._traceFunction||undefined;if(options){this.setOptions(options)}if(criteria){if(criteria.find&&criteria.remove&&criteria.update){this.collection(criteria)}else{this.find(criteria)}}}var $withinCmd="$geoWithin";Object.defineProperty(Query,"use$geoWithin",{get:function(){return $withinCmd=="$geoWithin"},set:function(v){if(true===v){$withinCmd="$geoWithin"}else{$withinCmd="$within"}}});Query.prototype.toConstructor=function toConstructor(){function CustomQuery(criteria,options){if(!(this instanceof CustomQuery))return new CustomQuery(criteria,options);Query.call(this,criteria,options)}utils.inherits(CustomQuery,Query);var p=CustomQuery.prototype;p.options={};p.setOptions(this.options);p.op=this.op;p._conditions=utils.clone(this._conditions);p._fields=utils.clone(this._fields);p._update=utils.clone(this._update);p._path=this._path;p._distinct=this._distinct;p._collection=this._collection;p._traceFunction=this._traceFunction;return CustomQuery};Query.prototype.setOptions=function(options){if(!(options&&utils.isObject(options)))return this;var methods=utils.keys(options),method;for(var i=0;i<methods.length;++i){method=methods[i];if("function"==typeof this[method]){var args=utils.isArray(options[method])?options[method]:[options[method]];this[method].apply(this,args)}else{this.options[method]=options[method]}}return this};Query.prototype.collection=function collection(coll){this._collection=new Query.Collection(coll);return this};Query.prototype.$where=function(js){this._conditions.$where=js;return this};Query.prototype.where=function(){if(!arguments.length)return this;if(!this.op)this.op="find";var type=typeof arguments[0];if("string"==type){this._path=arguments[0];if(2===arguments.length){this._conditions[this._path]=arguments[1]}return this}if("object"==type&&!Array.isArray(arguments[0])){return this.merge(arguments[0])}throw new TypeError("path must be a string or object")};Query.prototype.equals=function equals(val){this._ensurePath("equals");var path=this._path;this._conditions[path]=val;return this};Query.prototype.or=function or(array){var or=this._conditions.$or||(this._conditions.$or=[]);if(!utils.isArray(array))array=[array];or.push.apply(or,array);return this};Query.prototype.nor=function nor(array){var nor=this._conditions.$nor||(this._conditions.$nor=[]);if(!utils.isArray(array))array=[array];nor.push.apply(nor,array);return this};Query.prototype.and=function and(array){var and=this._conditions.$and||(this._conditions.$and=[]);if(!Array.isArray(array))array=[array];and.push.apply(and,array);return this};"gt gte lt lte ne in nin all regex size maxDistance".split(" ").forEach(function($conditional){Query.prototype[$conditional]=function(){var path,val;if(1===arguments.length){this._ensurePath($conditional);val=arguments[0];path=this._path}else{val=arguments[1];path=arguments[0]}var conds=this._conditions[path]||(this._conditions[path]={});conds["$"+$conditional]=val;return this}});Query.prototype.mod=function(){var val,path;if(1===arguments.length){this._ensurePath("mod");val=arguments[0];path=this._path}else if(2===arguments.length&&!utils.isArray(arguments[1])){this._ensurePath("mod");val=slice(arguments);path=this._path}else if(3===arguments.length){val=slice(arguments,1);path=arguments[0]}else{val=arguments[1];path=arguments[0]}var conds=this._conditions[path]||(this._conditions[path]={});conds.$mod=val;return this};Query.prototype.exists=function(){var path,val;if(0===arguments.length){this._ensurePath("exists");path=this._path;val=true}else if(1===arguments.length){if("boolean"===typeof arguments[0]){this._ensurePath("exists");path=this._path;val=arguments[0]}else{path=arguments[0];val=true}}else if(2===arguments.length){path=arguments[0];val=arguments[1]}var conds=this._conditions[path]||(this._conditions[path]={});conds.$exists=val;return this};Query.prototype.elemMatch=function(){if(null==arguments[0])throw new TypeError("Invalid argument");var fn,path,criteria;if("function"===typeof arguments[0]){this._ensurePath("elemMatch");path=this._path;fn=arguments[0]}else if(utils.isObject(arguments[0])){this._ensurePath("elemMatch");path=this._path;criteria=arguments[0]}else if("function"===typeof arguments[1]){path=arguments[0];fn=arguments[1]}else if(arguments[1]&&utils.isObject(arguments[1])){path=arguments[0];criteria=arguments[1]}else{throw new TypeError("Invalid argument")}if(fn){criteria=new Query;fn(criteria);criteria=criteria._conditions}var conds=this._conditions[path]||(this._conditions[path]={});conds.$elemMatch=criteria;return this};Query.prototype.within=function within(){this._ensurePath("within");this._geoComparison=$withinCmd;if(0===arguments.length){return this}if(2===arguments.length){return this.box.apply(this,arguments)}else if(2<arguments.length){return this.polygon.apply(this,arguments)}var area=arguments[0];if(!area)throw new TypeError("Invalid argument");if(area.center)return this.circle(area);if(area.box)return this.box.apply(this,area.box);if(area.polygon)return this.polygon.apply(this,area.polygon);if(area.type&&area.coordinates)return this.geometry(area);throw new TypeError("Invalid argument")};Query.prototype.box=function(){var path,box;if(3===arguments.length){path=arguments[0];box=[arguments[1],arguments[2]]}else if(2===arguments.length){this._ensurePath("box");path=this._path;box=[arguments[0],arguments[1]]}else{throw new TypeError("Invalid argument")}var conds=this._conditions[path]||(this._conditions[path]={});conds[this._geoComparison||$withinCmd]={$box:box};return this};Query.prototype.polygon=function(){var val,path;if("string"==typeof arguments[0]){path=arguments[0];val=slice(arguments,1)}else{this._ensurePath("polygon");path=this._path;val=slice(arguments)}var conds=this._conditions[path]||(this._conditions[path]={});conds[this._geoComparison||$withinCmd]={$polygon:val};return this};Query.prototype.circle=function(){
var path,val;if(1===arguments.length){this._ensurePath("circle");path=this._path;val=arguments[0]}else if(2===arguments.length){path=arguments[0];val=arguments[1]}else{throw new TypeError("Invalid argument")}if(!("radius"in val&&val.center))throw new Error("center and radius are required");var conds=this._conditions[path]||(this._conditions[path]={});var type=val.spherical?"$centerSphere":"$center";var wKey=this._geoComparison||$withinCmd;conds[wKey]={};conds[wKey][type]=[val.center,val.radius];if("unique"in val)conds[wKey].$uniqueDocs=!!val.unique;return this};Query.prototype.near=function near(){var path,val;this._geoComparison="$near";if(0===arguments.length){return this}else if(1===arguments.length){this._ensurePath("near");path=this._path;val=arguments[0]}else if(2===arguments.length){path=arguments[0];val=arguments[1]}else{throw new TypeError("Invalid argument")}if(!val.center){throw new Error("center is required")}var conds=this._conditions[path]||(this._conditions[path]={});var type=val.spherical?"$nearSphere":"$near";if(Array.isArray(val.center)){conds[type]=val.center;var radius="maxDistance"in val?val.maxDistance:null;if(null!=radius){conds.$maxDistance=radius}}else{if(val.center.type!="Point"||!Array.isArray(val.center.coordinates)){throw new Error(util.format("Invalid GeoJSON specified for %s",type))}conds[type]={$geometry:val.center};if("maxDistance"in val){conds[type]["$maxDistance"]=val.maxDistance}}return this};Query.prototype.intersects=function intersects(){this._ensurePath("intersects");this._geoComparison="$geoIntersects";if(0===arguments.length){return this}var area=arguments[0];if(null!=area&&area.type&&area.coordinates)return this.geometry(area);throw new TypeError("Invalid argument")};Query.prototype.geometry=function geometry(){if(!("$within"==this._geoComparison||"$geoWithin"==this._geoComparison||"$near"==this._geoComparison||"$geoIntersects"==this._geoComparison)){throw new Error("geometry() must come after `within()`, `intersects()`, or `near()")}var val,path;if(1===arguments.length){this._ensurePath("geometry");path=this._path;val=arguments[0]}else{throw new TypeError("Invalid argument")}if(!(val.type&&Array.isArray(val.coordinates))){throw new TypeError("Invalid argument")}var conds=this._conditions[path]||(this._conditions[path]={});conds[this._geoComparison]={$geometry:val};return this};Query.prototype.select=function select(){var arg=arguments[0];if(!arg)return this;if(arguments.length!==1){throw new Error("Invalid select: select only takes 1 argument")}this._validate("select");var fields=this._fields||(this._fields={});var type=typeof arg;if("string"==type||"object"==type&&"number"==typeof arg.length&&!Array.isArray(arg)){if("string"==type)arg=arg.split(/\s+/);for(var i=0,len=arg.length;i<len;++i){var field=arg[i];if(!field)continue;var include="-"==field[0]?0:1;if(include===0)field=field.substring(1);fields[field]=include}return this}if(utils.isObject(arg)&&!Array.isArray(arg)){var keys=utils.keys(arg);for(var i=0;i<keys.length;++i){fields[keys[i]]=arg[keys[i]]}return this}throw new TypeError("Invalid select() argument. Must be string or object.")};Query.prototype.slice=function(){if(0===arguments.length)return this;this._validate("slice");var path,val;if(1===arguments.length){var arg=arguments[0];if(typeof arg==="object"&&!Array.isArray(arg)){var keys=Object.keys(arg);var numKeys=keys.length;for(var i=0;i<numKeys;++i){this.slice(keys[i],arg[keys[i]])}return this}this._ensurePath("slice");path=this._path;val=arguments[0]}else if(2===arguments.length){if("number"===typeof arguments[0]){this._ensurePath("slice");path=this._path;val=slice(arguments)}else{path=arguments[0];val=arguments[1]}}else if(3===arguments.length){path=arguments[0];val=slice(arguments,1)}var myFields=this._fields||(this._fields={});myFields[path]={$slice:val};return this};Query.prototype.sort=function(arg){if(!arg)return this;this._validate("sort");var type=typeof arg;if(1===arguments.length&&"string"==type){arg=arg.split(/\s+/);for(var i=0,len=arg.length;i<len;++i){var field=arg[i];if(!field)continue;var ascend="-"==field[0]?-1:1;if(ascend===-1)field=field.substring(1);push(this.options,field,ascend)}return this}if(utils.isObject(arg)){var keys=utils.keys(arg);for(var i=0;i<keys.length;++i){var field=keys[i];push(this.options,field,arg[field])}return this}throw new TypeError("Invalid sort() argument. Must be a string or object.")};function push(opts,field,value){if(value&&value.$meta){var s=opts.sort||(opts.sort={});s[field]={$meta:value.$meta};return}var val=String(value||1).toLowerCase();if(!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)){if(utils.isArray(value))value="["+value+"]";throw new TypeError("Invalid sort value: {"+field+": "+value+" }")}var s=opts.sort||(opts.sort={});var valueStr=value.toString().replace("asc","1").replace("ascending","1").replace("desc","-1").replace("descending","-1");s[field]=parseInt(valueStr,10)}["limit","skip","maxScan","batchSize","comment"].forEach(function(method){Query.prototype[method]=function(v){this._validate(method);this.options[method]=v;return this}});Query.prototype.maxTime=function(v){this._validate("maxTime");this.options.maxTimeMS=v;return this};Query.prototype.snapshot=function(){this._validate("snapshot");this.options.snapshot=arguments.length?!!arguments[0]:true;return this};Query.prototype.hint=function(){if(0===arguments.length)return this;this._validate("hint");var arg=arguments[0];if(utils.isObject(arg)){var hint=this.options.hint||(this.options.hint={});for(var k in arg){hint[k]=arg[k]}return this}throw new TypeError("Invalid hint. "+arg)};Query.prototype.slaveOk=function(v){this.options.slaveOk=arguments.length?!!v:true;return this};Query.prototype.read=function(pref){if(arguments.length>1&&!Query.prototype.read.deprecationWarningIssued){console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead.");Query.prototype.read.deprecationWarningIssued=true}this.options.readPreference=utils.readPref(pref);return this};Query.prototype.tailable=function(){this._validate("tailable");this.options.tailable=arguments.length?!!arguments[0]:true;return this};Query.prototype.merge=function(source){if(!source)return this;if(!Query.canMerge(source))throw new TypeError("Invalid argument. Expected instanceof mquery or plain object");if(source instanceof Query){if(source._conditions){utils.merge(this._conditions,source._conditions)}if(source._fields){this._fields||(this._fields={});utils.merge(this._fields,source._fields)}if(source.options){this.options||(this.options={});utils.merge(this.options,source.options)}if(source._update){this._update||(this._update={});utils.mergeClone(this._update,source._update)}if(source._distinct){this._distinct=source._distinct}return this}utils.merge(this._conditions,source);return this};Query.prototype.find=function(criteria,callback){this.op="find";if("function"===typeof criteria){callback=criteria;criteria=undefined}else if(Query.canMerge(criteria)){this.merge(criteria)}if(!callback)return this;var self=this,conds=this._conditions,options=this._optionsForExec();options.fields=this._fieldsForExec();debug("find",this._collection.collectionName,conds,options);callback=this._wrapCallback("find",callback,{conditions:conds,options:options});this._collection.find(conds,options,utils.tick(callback));return this};Query.prototype.findOne=function(criteria,callback){this.op="findOne";if("function"===typeof criteria){callback=criteria;criteria=undefined}else if(Query.canMerge(criteria)){this.merge(criteria)}if(!callback)return this;var self=this,conds=this._conditions,options=this._optionsForExec();options.fields=this._fieldsForExec();debug("findOne",this._collection.collectionName,conds,options);callback=this._wrapCallback("findOne",callback,{conditions:conds,options:options});this._collection.findOne(conds,options,utils.tick(callback));return this};Query.prototype.count=function(criteria,callback){this.op="count";this._validate();if("function"===typeof criteria){callback=criteria;criteria=undefined}else if(Query.canMerge(criteria)){this.merge(criteria)}if(!callback)return this;var conds=this._conditions,options=this._optionsForExec();debug("count",this._collection.collectionName,conds,options);callback=this._wrapCallback("count",callback,{conditions:conds,options:options});this._collection.count(conds,options,utils.tick(callback));return this};Query.prototype.distinct=function(criteria,field,callback){this.op="distinct";this._validate();if(!callback){switch(typeof field){case"function":callback=field;if("string"==typeof criteria){field=criteria;criteria=undefined}break;case"undefined":case"string":break;default:throw new TypeError("Invalid `field` argument. Must be string or function");break}switch(typeof criteria){case"function":callback=criteria;criteria=field=undefined;break;case"string":field=criteria;criteria=undefined;break}}if("string"==typeof field){this._distinct=field}if(Query.canMerge(criteria)){this.merge(criteria)}if(!callback){return this}if(!this._distinct){throw new Error("No value for `distinct` has been declared")}var conds=this._conditions,options=this._optionsForExec();debug("distinct",this._collection.collectionName,conds,options);callback=this._wrapCallback("distinct",callback,{conditions:conds,options:options});this._collection.distinct(this._distinct,conds,options,utils.tick(callback));return this};Query.prototype.update=function update(criteria,doc,options,callback){this.op="update";var force;switch(arguments.length){case 3:if("function"==typeof options){callback=options;options=undefined}break;case 2:if("function"==typeof doc){callback=doc;doc=criteria;criteria=undefined}break;case 1:switch(typeof criteria){case"function":callback=criteria;criteria=options=doc=undefined;break;case"boolean":force=criteria;criteria=undefined;break;default:doc=criteria;criteria=options=undefined;break}}if(Query.canMerge(criteria)){this.merge(criteria)}if(doc){this._mergeUpdate(doc)}if(utils.isObject(options)){this.setOptions(options)}if(!(force||callback))return this;if(!this._update||!this.options.overwrite&&0===utils.keys(this._update).length){callback&&utils.soon(callback.bind(null,null,0));return this}options=this._optionsForExec();if(!callback)options.safe=false;var criteria=this._conditions;doc=this._updateForExec();debug("update",this._collection.collectionName,criteria,doc,options);callback=this._wrapCallback("update",callback,{conditions:criteria,doc:doc,options:options});this._collection.update(criteria,doc,options,utils.tick(callback));return this};Query.prototype.remove=function(criteria,callback){this.op="remove";var force;if("function"===typeof criteria){callback=criteria;criteria=undefined}else if(Query.canMerge(criteria)){this.merge(criteria)}else if(true===criteria){force=criteria;criteria=undefined}if(!(force||callback))return this;var options=this._optionsForExec();if(!callback)options.safe=false;var conds=this._conditions;debug("remove",this._collection.collectionName,conds,options);callback=this._wrapCallback("remove",callback,{conditions:conds,options:options});this._collection.remove(conds,options,utils.tick(callback));return this};Query.prototype.findOneAndUpdate=function(criteria,doc,options,callback){this.op="findOneAndUpdate";this._validate();switch(arguments.length){case 3:if("function"==typeof options){callback=options;options={}}break;case 2:if("function"==typeof doc){callback=doc;doc=criteria;criteria=undefined}options=undefined;break;case 1:if("function"==typeof criteria){callback=criteria;criteria=options=doc=undefined}else{doc=criteria;criteria=options=undefined}}if(Query.canMerge(criteria)){this.merge(criteria)}if(doc){this._mergeUpdate(doc)}options&&this.setOptions(options);if(!callback)return this;return this._findAndModify("update",callback)};Query.prototype.findOneAndRemove=function(conditions,options,callback){this.op="findOneAndRemove";this._validate();if("function"==typeof options){callback=options;options=undefined}else if("function"==typeof conditions){callback=conditions;conditions=undefined}if(Query.canMerge(conditions)){this.merge(conditions)}options&&this.setOptions(options);if(!callback)return this;return this._findAndModify("remove",callback)};Query.prototype._findAndModify=function(type,callback){assert.equal("function",typeof callback);var opts=this._optionsForExec(),self=this,fields,sort,doc;if("remove"==type){opts.remove=true}else{if(!("new"in opts))opts.new=true;if(!("upsert"in opts))opts.upsert=false;doc=this._updateForExec();if(!doc){if(opts.upsert){doc={$set:{}}}else{return this.findOne(callback)}}}var fields=this._fieldsForExec();if(fields){opts.fields=fields}var conds=this._conditions;debug("findAndModify",this._collection.collectionName,conds,doc,opts);callback=this._wrapCallback("findAndModify",callback,{conditions:conds,doc:doc,options:opts});this._collection.findAndModify(conds,doc,opts,utils.tick(callback));return this};Query.prototype._wrapCallback=function(method,callback,queryInfo){var traceFunction=this._traceFunction||Query.traceFunction;if(traceFunction){queryInfo.collectionName=this._collection.collectionName;var traceCallback=traceFunction&&traceFunction.call(null,method,queryInfo,this);var startTime=(new Date).getTime();return function wrapperCallback(err,result){if(traceCallback){var millis=(new Date).getTime()-startTime;traceCallback.call(null,err,result,millis)}if(callback){callback.apply(null,arguments)}}}return callback};Query.prototype.setTraceFunction=function(traceFunction){this._traceFunction=traceFunction;return this};Query.prototype.exec=function exec(op,callback){switch(typeof op){case"function":callback=op;op=null;break;case"string":this.op=op;break}assert.ok(this.op,"Missing query type: (find, update, etc)");if("update"==this.op||"remove"==this.op){callback||(callback=true)}this[this.op](callback)};Query.prototype.thunk=function(){var self=this;return function(cb){self.exec(cb)}};Query.prototype.then=function(resolve,reject){var self=this;var promise=new Query.Promise(function(success,error){self.exec(function(err,val){if(err)error(err);else success(val);self=success=error=null})});return promise.then(resolve,reject)};Query.prototype.stream=function(streamOptions){if("find"!=this.op)throw new Error("stream() is only available for find");var conds=this._conditions;var options=this._optionsForExec();options.fields=this._fieldsForExec();debug("stream",this._collection.collectionName,conds,options,streamOptions);return this._collection.findStream(conds,options,streamOptions)};Query.prototype.selected=function selected(){return!!(this._fields&&Object.keys(this._fields).length>0)};Query.prototype.selectedInclusively=function selectedInclusively(){if(!this._fields)return false;var keys=Object.keys(this._fields);if(0===keys.length)return false;for(var i=0;i<keys.length;++i){var key=keys[i];if(0===this._fields[key])return false;if(this._fields[key]&&typeof this._fields[key]==="object"&&this._fields[key].$meta){return false}}return true};Query.prototype.selectedExclusively=function selectedExclusively(){if(!this._fields)return false;var keys=Object.keys(this._fields);if(0===keys.length)return false;for(var i=0;i<keys.length;++i){var key=keys[i];if(0===this._fields[key])return true}return false};Query.prototype._mergeUpdate=function(doc){if(!this._update)this._update={};if(doc instanceof Query){if(doc._update){utils.mergeClone(this._update,doc._update)}}else{utils.mergeClone(this._update,doc)}};Query.prototype._optionsForExec=function(){var options=utils.clone(this.options,{retainKeyOrder:true});return options};Query.prototype._fieldsForExec=function(){return utils.clone(this._fields,{retainKeyOrder:true})};Query.prototype._updateForExec=function(){var update=utils.clone(this._update,{retainKeyOrder:true}),ops=utils.keys(update),i=ops.length,ret={},hasKeys,val;while(i--){var op=ops[i];if(this.options.overwrite){ret[op]=update[op];continue}if("$"!==op[0]){if(!ret.$set){if(update.$set){ret.$set=update.$set}else{ret.$set={}}}ret.$set[op]=update[op];ops.splice(i,1);if(!~ops.indexOf("$set"))ops.push("$set")}else if("$set"===op){if(!ret.$set){ret[op]=update[op]}}else{ret[op]=update[op]}}return ret};Query.prototype._ensurePath=function(method){if(!this._path){var msg=method+"() must be used after where() "+"when called with these arguments";throw new Error(msg)}};Query.permissions=require("./permissions");Query._isPermitted=function(a,b){var denied=Query.permissions[b];if(!denied)return true;return true!==denied[a]};Query.prototype._validate=function(action){var fail;var validator;if(undefined===action){validator=Query.permissions[this.op];if("function"!=typeof validator)return true;fail=validator(this)}else if(!Query._isPermitted(action,this.op)){fail=action}if(fail){throw new Error(fail+" cannot be used with "+this.op)}};Query.canMerge=function(conds){return conds instanceof Query||utils.isObject(conds)};Query.setGlobalTraceFunction=function(traceFunction){Query.traceFunction=traceFunction};Query.utils=utils;Query.env=require("./env");Query.Collection=require("./collection");Query.BaseCollection=require("./collection/collection");Query.Promise=require("bluebird");module.exports=exports=Query},{"./collection":74,"./collection/collection":73,"./env":76,"./permissions":78,"./utils":79,assert:88,bluebird:80,debug:81,sliced:83,util:98}],78:[function(require,module,exports){"use strict";var denied=exports;denied.distinct=function(self){if(self._fields&&Object.keys(self._fields).length>0){return"field selection and slice"}var keys=Object.keys(denied.distinct);var err;keys.every(function(option){if(self.options[option]){err=option;return false}return true});return err};denied.distinct.select=denied.distinct.slice=denied.distinct.sort=denied.distinct.limit=denied.distinct.skip=denied.distinct.batchSize=denied.distinct.comment=denied.distinct.maxScan=denied.distinct.snapshot=denied.distinct.hint=denied.distinct.tailable=true;denied.findOneAndUpdate=denied.findOneAndRemove=function(self){var keys=Object.keys(denied.findOneAndUpdate);var err;keys.every(function(option){if(self.options[option]){err=option;return false}return true});return err};denied.findOneAndUpdate.limit=denied.findOneAndUpdate.skip=denied.findOneAndUpdate.batchSize=denied.findOneAndUpdate.maxScan=denied.findOneAndUpdate.snapshot=denied.findOneAndUpdate.hint=denied.findOneAndUpdate.tailable=denied.findOneAndUpdate.comment=true;denied.count=function(self){if(self._fields&&Object.keys(self._fields).length>0){return"field selection and slice"}var keys=Object.keys(denied.count);var err;keys.every(function(option){if(self.options[option]){err=option;return false}return true});return err};denied.count.select=denied.count.slice=denied.count.sort=denied.count.batchSize=denied.count.comment=denied.count.maxScan=denied.count.snapshot=denied.count.tailable=true},{}],79:[function(require,module,exports){(function(process,Buffer){"use strict";var RegExpClone=require("regexp-clone");var clone=exports.clone=function clone(obj,options){if(obj===undefined||obj===null)return obj;if(Array.isArray(obj))return exports.cloneArray(obj,options);if(obj.constructor){if(/ObjectI[dD]$/.test(obj.constructor.name)){return"function"==typeof obj.clone?obj.clone():new obj.constructor(obj.id)}if("ReadPreference"===obj._type&&obj.isValid&&obj.toObject){return"function"==typeof obj.clone?obj.clone():new obj.constructor(obj.mode,clone(obj.tags,options))}if("Binary"==obj._bsontype&&obj.buffer&&obj.value){return"function"==typeof obj.clone?obj.clone():new obj.constructor(obj.value(true),obj.sub_type)}if("Date"===obj.constructor.name||"Function"===obj.constructor.name)return new obj.constructor(+obj);if("RegExp"===obj.constructor.name)return RegExpClone(obj);if("Buffer"===obj.constructor.name)return exports.cloneBuffer(obj)}if(isObject(obj))return exports.cloneObject(obj,options);if(obj.valueOf)return obj.valueOf()};var cloneObject=exports.cloneObject=function cloneObject(obj,options){var retainKeyOrder=options&&options.retainKeyOrder,minimize=options&&options.minimize,ret={},hasKeys,keys,val,k,i;if(retainKeyOrder){for(k in obj){val=clone(obj[k],options);if(!minimize||"undefined"!==typeof val){hasKeys||(hasKeys=true);ret[k]=val}}}else{keys=Object.keys(obj);i=keys.length;while(i--){k=keys[i];val=clone(obj[k],options);if(!minimize||"undefined"!==typeof val){if(!hasKeys)hasKeys=true;ret[k]=val}}}return minimize?hasKeys&&ret:ret};var cloneArray=exports.cloneArray=function cloneArray(arr,options){var ret=[];for(var i=0,l=arr.length;i<l;i++)ret.push(clone(arr[i],options));return ret};var tick=exports.tick=function tick(callback){if("function"!==typeof callback)return;return function(){var args=arguments;soon(function(){callback.apply(this,args)})}};var merge=exports.merge=function merge(to,from){var keys=Object.keys(from),i=keys.length,key;while(i--){key=keys[i];if("undefined"===typeof to[key]){to[key]=from[key]}else{if(exports.isObject(from[key])){merge(to[key],from[key])}else{to[key]=from[key]}}}};var mergeClone=exports.mergeClone=function mergeClone(to,from){var keys=Object.keys(from),i=keys.length,key;while(i--){key=keys[i];if("undefined"===typeof to[key]){to[key]=clone(from[key],{retainKeyOrder:1})}else{if(exports.isObject(from[key])){mergeClone(to[key],from[key])}else{to[key]=clone(from[key],{retainKeyOrder:1})}}}};exports.readPref=function readPref(pref){switch(pref){case"p":pref="primary";break;case"pp":pref="primaryPreferred";break;case"s":pref="secondary";break;case"sp":pref="secondaryPreferred";break;case"n":pref="nearest";break}return pref};var _toString=Object.prototype.toString;var toString=exports.toString=function(arg){return _toString.call(arg)};var isObject=exports.isObject=function(arg){return"[object Object]"==exports.toString(arg)};var isArray=exports.isArray=function(arg){return Array.isArray(arg)||"object"==typeof arg&&"[object Array]"==exports.toString(arg)};exports.keys=Object.keys||function(obj){var keys=[];for(var k in obj)if(obj.hasOwnProperty(k)){keys.push(k)}return keys};exports.create="function"==typeof Object.create?Object.create:create;function create(proto){if(arguments.length>1){throw new Error("Adding properties is not supported")}function F(){}F.prototype=proto;return new F}exports.inherits=function(ctor,superCtor){ctor.prototype=exports.create(superCtor.prototype);ctor.prototype.constructor=ctor};var soon=exports.soon="function"==typeof setImmediate?setImmediate:process.nextTick;exports.cloneBuffer=function(buff){var dupe=new Buffer(buff.length);buff.copy(dupe,0,0,buff.length);return dupe}}).call(this,require("_process"),require("buffer").Buffer)},{_process:96,buffer:91,"regexp-clone":86}],80:[function(require,module,exports){(function(process,global){!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var SomePromiseArray=Promise._SomePromiseArray;function any(promises){var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(1);ret.setUnwrap();ret.init();return promise}Promise.any=function(promises){return any(promises)};Promise.prototype.any=function(){return any(this)}}},{}],2:[function(_dereq_,module,exports){"use strict";var firstLineError;try{throw new Error}catch(e){firstLineError=e}var schedule=_dereq_("./schedule.js");var Queue=_dereq_("./queue.js");var util=_dereq_("./util.js");function Async(){this._isTickUsed=false;this._lateQueue=new Queue(16);this._normalQueue=new Queue(16);this._trampolineEnabled=true;var self=this;this.drainQueues=function(){self._drainQueues()};this._schedule=schedule.isStatic?schedule(this.drainQueues):schedule}Async.prototype.disableTrampolineIfNecessary=function(){if(util.hasDevTools){this._trampolineEnabled=false}};Async.prototype.enableTrampoline=function(){if(!this._trampolineEnabled){this._trampolineEnabled=true;this._schedule=function(fn){setTimeout(fn,0)}}};Async.prototype.haveItemsQueued=function(){return this._normalQueue.length()>0};Async.prototype.throwLater=function(fn,arg){if(arguments.length===1){arg=fn;fn=function(){throw arg}}var domain=this._getDomain();if(domain!==undefined)fn=domain.bind(fn);if(typeof setTimeout!=="undefined"){setTimeout(function(){fn(arg)},0)}else try{this._schedule(function(){fn(arg)})}catch(e){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}};Async.prototype._getDomain=function(){};if(!true){if(util.isNode){var EventsModule=_dereq_("events");var domainGetter=function(){var domain=process.domain;if(domain===null)return undefined;return domain};if(EventsModule.usingDomains){Async.prototype._getDomain=domainGetter}else{var descriptor=Object.getOwnPropertyDescriptor(EventsModule,"usingDomains");if(descriptor){if(!descriptor.configurable){process.on("domainsActivated",function(){Async.prototype._getDomain=domainGetter})}else{var usingDomains=false;Object.defineProperty(EventsModule,"usingDomains",{configurable:false,enumerable:true,get:function(){return usingDomains},set:function(value){if(usingDomains||!value)return;usingDomains=true;Async.prototype._getDomain=domainGetter;util.toFastProperties(process);process.emit("domainsActivated")}})}}}}}function AsyncInvokeLater(fn,receiver,arg){var domain=this._getDomain();if(domain!==undefined)fn=domain.bind(fn);this._lateQueue.push(fn,receiver,arg);this._queueTick()}function AsyncInvoke(fn,receiver,arg){var domain=this._getDomain();if(domain!==undefined)fn=domain.bind(fn);this._normalQueue.push(fn,receiver,arg);this._queueTick()}function AsyncSettlePromises(promise){var domain=this._getDomain();if(domain!==undefined){var fn=domain.bind(promise._settlePromises);this._normalQueue.push(fn,promise,undefined)}else{this._normalQueue._pushOne(promise)}this._queueTick()}if(!util.hasDevTools){Async.prototype.invokeLater=AsyncInvokeLater;Async.prototype.invoke=AsyncInvoke;Async.prototype.settlePromises=AsyncSettlePromises}else{Async.prototype.invokeLater=function(fn,receiver,arg){if(this._trampolineEnabled){AsyncInvokeLater.call(this,fn,receiver,arg)}else{setTimeout(function(){fn.call(receiver,arg)},100)}};Async.prototype.invoke=function(fn,receiver,arg){if(this._trampolineEnabled){AsyncInvoke.call(this,fn,receiver,arg)}else{setTimeout(function(){fn.call(receiver,arg)},0)}};Async.prototype.settlePromises=function(promise){if(this._trampolineEnabled){AsyncSettlePromises.call(this,promise)}else{setTimeout(function(){promise._settlePromises()},0)}}}Async.prototype.invokeFirst=function(fn,receiver,arg){var domain=this._getDomain();if(domain!==undefined)fn=domain.bind(fn);this._normalQueue.unshift(fn,receiver,arg);this._queueTick()};Async.prototype._drainQueue=function(queue){while(queue.length()>0){var fn=queue.shift();if(typeof fn!=="function"){fn._settlePromises();continue}var receiver=queue.shift();var arg=queue.shift();fn.call(receiver,arg)}};Async.prototype._drainQueues=function(){this._drainQueue(this._normalQueue);this._reset();this._drainQueue(this._lateQueue)};Async.prototype._queueTick=function(){if(!this._isTickUsed){this._isTickUsed=true;this._schedule(this.drainQueues)}};Async.prototype._reset=function(){this._isTickUsed=false};module.exports=new Async;module.exports.firstLineError=firstLineError},{"./queue.js":28,"./schedule.js":31,"./util.js":38,events:39}],3:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise){var rejectThis=function(_,e){this._reject(e)};var targetRejected=function(e,context){context.promiseRejectionQueued=true;context.bindingPromise._then(rejectThis,rejectThis,null,this,e)};var bindingResolved=function(thisArg,context){this._setBoundTo(thisArg);if(this._isPending()){this._resolveCallback(context.target)}};var bindingRejected=function(e,context){if(!context.promiseRejectionQueued)this._reject(e)};Promise.prototype.bind=function(thisArg){var maybePromise=tryConvertToPromise(thisArg);var ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();if(maybePromise instanceof Promise){var context={promiseRejectionQueued:false,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,ret._progress,ret,context);maybePromise._then(bindingResolved,bindingRejected,ret._progress,ret,context)}else{ret._setBoundTo(thisArg);ret._resolveCallback(target)}return ret};Promise.prototype._setBoundTo=function(obj){if(obj!==undefined){this._bitField=this._bitField|131072;this._boundTo=obj}else{this._bitField=this._bitField&~131072}};Promise.prototype._isBound=function(){return(this._bitField&131072)===131072};Promise.bind=function(thisArg,value){var maybePromise=tryConvertToPromise(thisArg);var ret=new Promise(INTERNAL);if(maybePromise instanceof Promise){maybePromise._then(function(thisArg){ret._setBoundTo(thisArg);ret._resolveCallback(value)},ret._reject,ret._progress,ret,null)}else{ret._setBoundTo(thisArg);ret._resolveCallback(value)}return ret}}},{}],4:[function(_dereq_,module,exports){"use strict";var old;if(typeof Promise!=="undefined")old=Promise;function noConflict(){try{if(Promise===bluebird)Promise=old}catch(e){}return bluebird}var bluebird=_dereq_("./promise.js")();bluebird.noConflict=noConflict;module.exports=bluebird},{"./promise.js":23}],5:[function(_dereq_,module,exports){"use strict";var cr=Object.create;if(cr){var callerCache=cr(null);var getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0}module.exports=function(Promise){var util=_dereq_("./util.js");var canEvaluate=util.canEvaluate;var isIdentifier=util.isIdentifier;var getMethodCaller;var getGetter;if(!true){var makeMethodCaller=function(methodName){return new Function("ensureMethod"," \n return function(obj) { \n 'use strict' \n var len = this.length; \n ensureMethod(obj, 'methodName'); \n switch(len) { \n case 1: return obj.methodName(this[0]); \n case 2: return obj.methodName(this[0], this[1]); \n case 3: return obj.methodName(this[0], this[1], this[2]); \n case 0: return obj.methodName(); \n default: \n return obj.methodName.apply(obj, this); \n } \n }; \n ".replace(/methodName/g,methodName))(ensureMethod)};var makeGetter=function(propertyName){return new Function("obj"," \n 'use strict'; \n return obj.propertyName; \n ".replace("propertyName",propertyName))};var getCompiled=function(name,compiler,cache){var ret=cache[name];if(typeof ret!=="function"){if(!isIdentifier(name)){return null}ret=compiler(name);cache[name]=ret;
cache[" size"]++;if(cache[" size"]>512){var keys=Object.keys(cache);for(var i=0;i<256;++i)delete cache[keys[i]];cache[" size"]=keys.length-256}}return ret};getMethodCaller=function(name){return getCompiled(name,makeMethodCaller,callerCache)};getGetter=function(name){return getCompiled(name,makeGetter,getterCache)}}function ensureMethod(obj,methodName){var fn;if(obj!=null)fn=obj[methodName];if(typeof fn!=="function"){var message="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'";throw new Promise.TypeError(message)}return fn}function caller(obj){var methodName=this.pop();var fn=ensureMethod(obj,methodName);return fn.apply(obj,this)}Promise.prototype.call=function(methodName){var $_len=arguments.length;var args=new Array($_len-1);for(var $_i=1;$_i<$_len;++$_i){args[$_i-1]=arguments[$_i]}if(!true){if(canEvaluate){var maybeCaller=getMethodCaller(methodName);if(maybeCaller!==null){return this._then(maybeCaller,undefined,undefined,args,undefined)}}}args.push(methodName);return this._then(caller,undefined,undefined,args,undefined)};function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;if(index<0)index=Math.max(0,index+obj.length);return obj[index]}Promise.prototype.get=function(propertyName){var isIndex=typeof propertyName==="number";var getter;if(!isIndex){if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=maybeGetter!==null?maybeGetter:namedGetter}else{getter=namedGetter}}else{getter=indexedGetter}return this._then(getter,undefined,undefined,propertyName,undefined)}}},{"./util.js":38}],6:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var errors=_dereq_("./errors.js");var async=_dereq_("./async.js");var CancellationError=errors.CancellationError;Promise.prototype._cancel=function(reason){if(!this.isCancellable())return this;var parent;var promiseToReject=this;while((parent=promiseToReject._cancellationParent)!==undefined&&parent.isCancellable()){promiseToReject=parent}this._unsetCancellable();promiseToReject._target()._rejectCallback(reason,false,true)};Promise.prototype.cancel=function(reason){if(!this.isCancellable())return this;if(reason===undefined)reason=new CancellationError;async.invokeLater(this._cancel,this,reason);return this};Promise.prototype.cancellable=function(){if(this._cancellable())return this;async.enableTrampoline();this._setCancellable();this._cancellationParent=undefined;return this};Promise.prototype.uncancellable=function(){var ret=this.then();ret._unsetCancellable();return ret};Promise.prototype.fork=function(didFulfill,didReject,didProgress){var ret=this._then(didFulfill,didReject,didProgress,undefined,undefined);ret._setCancellable();ret._cancellationParent=undefined;return ret}}},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){"use strict";module.exports=function(){var async=_dereq_("./async.js");var util=_dereq_("./util.js");var bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;var stackFramePattern=null;var formatStack=null;var indentStackFrames=false;var warn;function CapturedTrace(parent){this._parent=parent;var length=this._length=1+(parent===undefined?0:parent._length);captureStackTrace(this,CapturedTrace);if(length>32)this.uncycle()}util.inherits(CapturedTrace,Error);CapturedTrace.prototype.uncycle=function(){var length=this._length;if(length<2)return;var nodes=[];var stackToIndex={};for(var i=0,node=this;node!==undefined;++i){nodes.push(node);node=node._parent}length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;if(stackToIndex[stack]===undefined){stackToIndex[stack]=i}}for(var i=0;i<length;++i){var currentStack=nodes[i].stack;var index=stackToIndex[currentStack];if(index!==undefined&&index!==i){if(index>0){nodes[index-1]._parent=undefined;nodes[index-1]._length=1}nodes[i]._parent=undefined;nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;if(index<length-1){cycleEdgeNode._parent=nodes[index+1];cycleEdgeNode._parent.uncycle();cycleEdgeNode._length=cycleEdgeNode._parent._length+1}else{cycleEdgeNode._parent=undefined;cycleEdgeNode._length=1}var currentChildLength=cycleEdgeNode._length+1;for(var j=i-2;j>=0;--j){nodes[j]._length=currentChildLength;currentChildLength++}return}}};CapturedTrace.prototype.parent=function(){return this._parent};CapturedTrace.prototype.hasParent=function(){return this._parent!==undefined};CapturedTrace.prototype.attachExtraTrace=function(error){if(error.__stackCleaned__)return;this.uncycle();var parsed=CapturedTrace.parseStackAndMessage(error);var message=parsed.message;var stacks=[parsed.stack];var trace=this;while(trace!==undefined){stacks.push(cleanStack(trace.stack.split("\n")));trace=trace._parent}removeCommonRoots(stacks);removeDuplicateOrEmptyJumps(stacks);util.notEnumerableProp(error,"stack",reconstructStack(message,stacks));util.notEnumerableProp(error,"__stackCleaned__",true)};function reconstructStack(message,stacks){for(var i=0;i<stacks.length-1;++i){stacks[i].push("From previous event:");stacks[i]=stacks[i].join("\n")}if(i<stacks.length){stacks[i]=stacks[i].join("\n")}return message+"\n"+stacks.join("\n")}function removeDuplicateOrEmptyJumps(stacks){for(var i=0;i<stacks.length;++i){if(stacks[i].length===0||i+1<stacks.length&&stacks[i][0]===stacks[i+1][0]){stacks.splice(i,1);i--}}}function removeCommonRoots(stacks){var current=stacks[0];for(var i=1;i<stacks.length;++i){var prev=stacks[i];var currentLastIndex=current.length-1;var currentLastLine=current[currentLastIndex];var commonRootMeetPoint=-1;for(var j=prev.length-1;j>=0;--j){if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}}for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]===line){current.pop();currentLastIndex--}else{break}}current=prev}}function cleanStack(stack){var ret=[];for(var i=0;i<stack.length;++i){var line=stack[i];var isTraceLine=stackFramePattern.test(line)||" (No stack trace)"===line;var isInternalFrame=isTraceLine&&shouldIgnore(line);if(isTraceLine&&!isInternalFrame){if(indentStackFrames&&line.charAt(0)!==" "){line=" "+line}ret.push(line)}}return ret}function stackFramesAsArray(error){var stack=error.stack.replace(/\s+$/g,"").split("\n");for(var i=0;i<stack.length;++i){var line=stack[i];if(" (No stack trace)"===line||stackFramePattern.test(line)){break}}if(i>0){stack=stack.slice(i)}return stack}CapturedTrace.parseStackAndMessage=function(error){var stack=error.stack;var message=error.toString();stack=typeof stack==="string"&&stack.length>0?stackFramesAsArray(error):[" (No stack trace)"];return{message:message,stack:cleanStack(stack)}};CapturedTrace.formatAndLogError=function(error,title){if(typeof console!=="undefined"){var message;if(typeof error==="object"||typeof error==="function"){var stack=error.stack;message=title+formatStack(stack,error)}else{message=title+String(error)}if(typeof warn==="function"){warn(message)}else if(typeof console.log==="function"||typeof console.log==="object"){console.log(message)}}};CapturedTrace.unhandledRejection=function(reason){CapturedTrace.formatAndLogError(reason,"^--- With additional stack trace: ")};CapturedTrace.isSupported=function(){return typeof captureStackTrace==="function"};CapturedTrace.fireRejectionEvent=function(name,localHandler,reason,promise){var localEventFired=false;try{if(typeof localHandler==="function"){localEventFired=true;if(name==="rejectionHandled"){localHandler(promise)}else{localHandler(reason,promise)}}}catch(e){async.throwLater(e)}var globalEventFired=false;try{globalEventFired=fireGlobalEvent(name,reason,promise)}catch(e){globalEventFired=true;async.throwLater(e)}var domEventFired=false;if(fireDomEvent){try{domEventFired=fireDomEvent(name.toLowerCase(),{reason:reason,promise:promise})}catch(e){domEventFired=true;async.throwLater(e)}}if(!globalEventFired&&!localEventFired&&!domEventFired&&name==="unhandledRejection"){CapturedTrace.formatAndLogError(reason,"Unhandled rejection ")}};function formatNonError(obj){var str;if(typeof obj==="function"){str="[function "+(obj.name||"anonymous")+"]"}else{str=obj.toString();var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str)){try{var newStr=JSON.stringify(obj);str=newStr}catch(e){}}if(str.length===0){str="(empty array)"}}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;if(str.length<maxChars){return str}return str.substr(0,maxChars-3)+"..."}var shouldIgnore=function(){return false};var parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function parseLineInfo(line){var matches=line.match(parseLineInfoRegex);if(matches){return{fileName:matches[1],line:parseInt(matches[2],10)}}}CapturedTrace.setBounds=function(firstLineError,lastLineError){if(!CapturedTrace.isSupported())return;var firstStackLines=firstLineError.stack.split("\n");var lastStackLines=lastLineError.stack.split("\n");var firstIndex=-1;var lastIndex=-1;var firstFileName;var lastFileName;for(var i=0;i<firstStackLines.length;++i){var result=parseLineInfo(firstStackLines[i]);if(result){firstFileName=result.fileName;firstIndex=result.line;break}}for(var i=0;i<lastStackLines.length;++i){var result=parseLineInfo(lastStackLines[i]);if(result){lastFileName=result.fileName;lastIndex=result.line;break}}if(firstIndex<0||lastIndex<0||!firstFileName||!lastFileName||firstFileName!==lastFileName||firstIndex>=lastIndex){return}shouldIgnore=function(line){if(bluebirdFramePattern.test(line))return true;var info=parseLineInfo(line);if(info){if(info.fileName===firstFileName&&(firstIndex<=info.line&&info.line<=lastIndex)){return true}}return false}};var captureStackTrace=function stackDetection(){var v8stackFramePattern=/^\s*at\s*/;var v8stackFormatter=function(stack,error){if(typeof stack==="string")return stack;if(error.name!==undefined&&error.message!==undefined){return error.toString()}return formatNonError(error)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit=Error.stackTraceLimit+6;stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;shouldIgnore=function(line){return bluebirdFramePattern.test(line)};return function(receiver,ignoreUntil){Error.stackTraceLimit=Error.stackTraceLimit+6;captureStackTrace(receiver,ignoreUntil);Error.stackTraceLimit=Error.stackTraceLimit-6}}var err=new Error;if(typeof err.stack==="string"&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0){stackFramePattern=/@/;formatStack=v8stackFormatter;indentStackFrames=true;return function captureStackTrace(o){o.stack=(new Error).stack}}var hasStackAfterThrow;try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}if(!("stack"in err)&&hasStackAfterThrow){stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;return function captureStackTrace(o){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6}}formatStack=function(stack,error){if(typeof stack==="string")return stack;if((typeof error==="object"||typeof error==="function")&&error.name!==undefined&&error.message!==undefined){return error.toString()}return formatNonError(error)};return null}([]);var fireDomEvent;var fireGlobalEvent=function(){if(util.isNode){return function(name,reason,promise){if(name==="rejectionHandled"){return process.emit(name,promise)}else{return process.emit(name,reason,promise)}}}else{var customEventWorks=false;var anyEventWorks=true;try{var ev=new self.CustomEvent("test");customEventWorks=ev instanceof CustomEvent}catch(e){}if(!customEventWorks){try{var event=document.createEvent("CustomEvent");event.initCustomEvent("testingtheevent",false,true,{});self.dispatchEvent(event)}catch(e){anyEventWorks=false}}if(anyEventWorks){fireDomEvent=function(type,detail){var event;if(customEventWorks){event=new self.CustomEvent(type,{detail:detail,bubbles:false,cancelable:true})}else if(self.dispatchEvent){event=document.createEvent("CustomEvent");event.initCustomEvent(type,false,true,detail)}return event?!self.dispatchEvent(event):false}}var toWindowMethodNameMap={};toWindowMethodNameMap["unhandledRejection"]=("on"+"unhandledRejection").toLowerCase();toWindowMethodNameMap["rejectionHandled"]=("on"+"rejectionHandled").toLowerCase();return function(name,reason,promise){var methodName=toWindowMethodNameMap[name];var method=self[methodName];if(!method)return false;if(name==="rejectionHandled"){method.call(self,promise)}else{method.call(self,reason,promise)}return true}}}();if(typeof console!=="undefined"&&typeof console.warn!=="undefined"){warn=function(message){console.warn(message)};if(util.isNode&&process.stderr.isTTY){warn=function(message){process.stderr.write(""+message+"\n")}}else if(!util.isNode&&typeof(new Error).stack==="string"){warn=function(message){console.warn("%c"+message,"color: red")}}}return CapturedTrace}},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){"use strict";module.exports=function(NEXT_FILTER){var util=_dereq_("./util.js");var errors=_dereq_("./errors.js");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var keys=_dereq_("./es5.js").keys;var TypeError=errors.TypeError;function CatchFilter(instances,callback,promise){this._instances=instances;this._callback=callback;this._promise=promise}function safePredicate(predicate,e){var safeObject={};var retfilter=tryCatch(predicate).call(safeObject,e);if(retfilter===errorObj)return retfilter;var safeKeys=keys(safeObject);if(safeKeys.length){errorObj.e=new TypeError("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n");return errorObj}return retfilter}CatchFilter.prototype.doFilter=function(e){var cb=this._callback;var promise=this._promise;var boundTo=promise._boundTo;for(var i=0,len=this._instances.length;i<len;++i){var item=this._instances[i];var itemIsErrorType=item===Error||item!=null&&item.prototype instanceof Error;if(itemIsErrorType&&e instanceof item){var ret=tryCatch(cb).call(boundTo,e);if(ret===errorObj){NEXT_FILTER.e=ret.e;return NEXT_FILTER}return ret}else if(typeof item==="function"&&!itemIsErrorType){var shouldHandle=safePredicate(item,e);if(shouldHandle===errorObj){e=errorObj.e;break}else if(shouldHandle){var ret=tryCatch(cb).call(boundTo,e);if(ret===errorObj){NEXT_FILTER.e=ret.e;return NEXT_FILTER}return ret}}}NEXT_FILTER.e=e;return NEXT_FILTER};return CatchFilter}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,CapturedTrace,isDebugging){var contextStack=[];function Context(){this._trace=new CapturedTrace(peekContext())}Context.prototype._pushContext=function(){if(!isDebugging())return;if(this._trace!==undefined){contextStack.push(this._trace)}};Context.prototype._popContext=function(){if(!isDebugging())return;if(this._trace!==undefined){contextStack.pop()}};function createContext(){if(isDebugging())return new Context}function peekContext(){var lastIndex=contextStack.length-1;if(lastIndex>=0){return contextStack[lastIndex]}return undefined}Promise.prototype._peekContext=peekContext;Promise.prototype._pushContext=Context.prototype._pushContext;Promise.prototype._popContext=Context.prototype._popContext;return createContext}},{}],10:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,CapturedTrace){var async=_dereq_("./async.js");var Warning=_dereq_("./errors.js").Warning;var util=_dereq_("./util.js");var canAttachTrace=util.canAttachTrace;var unhandledRejectionHandled;var possiblyUnhandledRejection;var debugging=false||util.isNode&&(!!process.env["BLUEBIRD_DEBUG"]||process.env["NODE_ENV"]==="development");if(debugging){async.disableTrampolineIfNecessary()}Promise.prototype._ensurePossibleRejectionHandled=function(){this._setRejectionIsUnhandled();async.invokeLater(this._notifyUnhandledRejection,this,undefined)};Promise.prototype._notifyUnhandledRejectionIsHandled=function(){CapturedTrace.fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,undefined,this)};Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified();CapturedTrace.fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this)}};Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=this._bitField|524288};Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&~524288};Promise.prototype._isUnhandledRejectionNotified=function(){return(this._bitField&524288)>0};Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=this._bitField|2097152};Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&~2097152;if(this._isUnhandledRejectionNotified()){this._unsetUnhandledRejectionIsNotified();this._notifyUnhandledRejectionIsHandled()}};Promise.prototype._isRejectionUnhandled=function(){return(this._bitField&2097152)>0};Promise.prototype._setCarriedStackTrace=function(capturedTrace){this._bitField=this._bitField|1048576;this._fulfillmentHandler0=capturedTrace};Promise.prototype._isCarryingStackTrace=function(){return(this._bitField&1048576)>0};Promise.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:undefined};Promise.prototype._captureStackTrace=function(){if(debugging){this._trace=new CapturedTrace(this._peekContext())}return this};Promise.prototype._attachExtraTrace=function(error,ignoreSelf){if(debugging&&canAttachTrace(error)){var trace=this._trace;if(trace!==undefined){if(ignoreSelf)trace=trace._parent}if(trace!==undefined){trace.attachExtraTrace(error)}else if(!error.__stackCleaned__){var parsed=CapturedTrace.parseStackAndMessage(error);util.notEnumerableProp(error,"stack",parsed.message+"\n"+parsed.stack.join("\n"));util.notEnumerableProp(error,"__stackCleaned__",true)}}};Promise.prototype._warn=function(message){var warning=new Warning(message);var ctx=this._peekContext();if(ctx){ctx.attachExtraTrace(warning)}else{var parsed=CapturedTrace.parseStackAndMessage(warning);warning.stack=parsed.message+"\n"+parsed.stack.join("\n")}CapturedTrace.formatAndLogError(warning,"")};Promise.onPossiblyUnhandledRejection=function(fn){possiblyUnhandledRejection=typeof fn==="function"?fn:undefined};Promise.onUnhandledRejectionHandled=function(fn){unhandledRejectionHandled=typeof fn==="function"?fn:undefined};Promise.longStackTraces=function(){if(async.haveItemsQueued()&&debugging===false){throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n")}debugging=CapturedTrace.isSupported();if(debugging){async.disableTrampolineIfNecessary()}};Promise.hasLongStackTraces=function(){return debugging&&CapturedTrace.isSupported()};if(!CapturedTrace.isSupported()){Promise.longStackTraces=function(){};debugging=false}return function(){return debugging}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util.js");var isPrimitive=util.isPrimitive;var wrapsPrimitiveReceiver=util.wrapsPrimitiveReceiver;module.exports=function(Promise){var returner=function(){return this};var thrower=function(){throw this};var returnUndefined=function(){};var throwUndefined=function(){throw undefined};var wrapper=function(value,action){if(action===1){return function(){throw value}}else if(action===2){return function(){return value}}};Promise.prototype["return"]=Promise.prototype.thenReturn=function(value){if(value===undefined)return this.then(returnUndefined);if(wrapsPrimitiveReceiver&&isPrimitive(value)){return this._then(wrapper(value,2),undefined,undefined,undefined,undefined)}return this._then(returner,undefined,undefined,value,undefined)};Promise.prototype["throw"]=Promise.prototype.thenThrow=function(reason){if(reason===undefined)return this.then(throwUndefined);if(wrapsPrimitiveReceiver&&isPrimitive(reason)){return this._then(wrapper(reason,1),undefined,undefined,undefined,undefined)}return this._then(thrower,undefined,undefined,reason,undefined)}}},{"./util.js":38}],12:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseReduce=Promise.reduce;Promise.prototype.each=function(fn){return PromiseReduce(this,fn,null,INTERNAL)};Promise.each=function(promises,fn){return PromiseReduce(promises,fn,null,INTERNAL)}}},{}],13:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5.js");var Objectfreeze=es5.freeze;var util=_dereq_("./util.js");var inherits=util.inherits;var notEnumerableProp=util.notEnumerableProp;function subError(nameProperty,defaultMessage){function SubError(message){if(!(this instanceof SubError))return new SubError(message);notEnumerableProp(this,"message",typeof message==="string"?message:defaultMessage);notEnumerableProp(this,"name",nameProperty);if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}else{Error.call(this)}}inherits(SubError,Error);return SubError}var _TypeError,_RangeError;var Warning=subError("Warning","warning");var CancellationError=subError("CancellationError","cancellation error");var TimeoutError=subError("TimeoutError","timeout error");var AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError;_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error");_RangeError=subError("RangeError","range error")}var methods=("join pop push shift unshift slice filter forEach some "+"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");for(var i=0;i<methods.length;++i){if(typeof Array.prototype[methods[i]]==="function"){AggregateError.prototype[methods[i]]=Array.prototype[methods[i]]}}es5.defineProperty(AggregateError.prototype,"length",{value:0,configurable:false,writable:true,enumerable:true});AggregateError.prototype["isOperational"]=true;var level=0;AggregateError.prototype.toString=function(){var indent=Array(level*4+1).join(" ");var ret="\n"+indent+"AggregateError of:"+"\n";level++;indent=Array(level*4+1).join(" ");for(var i=0;i<this.length;++i){var str=this[i]===this?"[Circular AggregateError]":this[i]+"";var lines=str.split("\n");for(var j=0;j<lines.length;++j){lines[j]=indent+lines[j]}str=lines.join("\n");ret+=str+"\n"}level--;return ret};function OperationalError(message){if(!(this instanceof OperationalError))return new OperationalError(message);notEnumerableProp(this,"name","OperationalError");notEnumerableProp(this,"message",message);this.cause=message;this["isOperational"]=true;if(message instanceof Error){notEnumerableProp(this,"message",message.message);notEnumerableProp(this,"stack",message.stack)}else if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}}inherits(OperationalError,Error);var errorTypes=Error["__BluebirdErrorTypes__"];if(!errorTypes){errorTypes=Objectfreeze({CancellationError:CancellationError,TimeoutError:TimeoutError,OperationalError:OperationalError,RejectionError:OperationalError,AggregateError:AggregateError});notEnumerableProp(Error,"__BluebirdErrorTypes__",errorTypes)}module.exports={Error:Error,TypeError:_TypeError,RangeError:_RangeError,CancellationError:errorTypes.CancellationError,OperationalError:errorTypes.OperationalError,TimeoutError:errorTypes.TimeoutError,AggregateError:errorTypes.AggregateError,Warning:Warning}},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){var isES5=function(){"use strict";return this===undefined}();if(isES5){module.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:isES5,propertyIsWritable:function(obj,prop){var descriptor=Object.getOwnPropertyDescriptor(obj,prop);return!!(!descriptor||descriptor.writable||descriptor.set)}}}else{var has={}.hasOwnProperty;var str={}.toString;var proto={}.constructor.prototype;var ObjectKeys=function(o){var ret=[];for(var key in o){if(has.call(o,key)){ret.push(key)}}return ret};var ObjectGetDescriptor=function(o,key){return{value:o[key]}};var ObjectDefineProperty=function(o,key,desc){o[key]=desc.value;return o};var ObjectFreeze=function(obj){return obj};var ObjectGetPrototypeOf=function(obj){try{return Object(obj).constructor.prototype}catch(e){return proto}};var ArrayIsArray=function(obj){try{return str.call(obj)==="[object Array]"}catch(e){return false}};module.exports={isArray:ArrayIsArray,keys:ObjectKeys,names:ObjectKeys,defineProperty:ObjectDefineProperty,getDescriptor:ObjectGetDescriptor,freeze:ObjectFreeze,getPrototypeOf:ObjectGetPrototypeOf,isES5:isES5,propertyIsWritable:function(){return true}}}},{}],15:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseMap=Promise.map;Promise.prototype.filter=function(fn,options){return PromiseMap(this,fn,options,INTERNAL)};Promise.filter=function(promises,fn,options){return PromiseMap(promises,fn,options,INTERNAL)}}},{}],16:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,NEXT_FILTER,tryConvertToPromise){var util=_dereq_("./util.js");var wrapsPrimitiveReceiver=util.wrapsPrimitiveReceiver;var isPrimitive=util.isPrimitive;var thrower=util.thrower;function returnThis(){return this}function throwThis(){throw this}function return$(r){return function(){return r}}function throw$(r){return function(){throw r}}function promisedFinally(ret,reasonOrValue,isFulfilled){var then;if(wrapsPrimitiveReceiver&&isPrimitive(reasonOrValue)){then=isFulfilled?return$(reasonOrValue):throw$(reasonOrValue)}else{then=isFulfilled?returnThis:throwThis}return ret._then(then,thrower,undefined,reasonOrValue,undefined)}function finallyHandler(reasonOrValue){var promise=this.promise;var handler=this.handler;var ret=promise._isBound()?handler.call(promise._boundTo):handler();if(ret!==undefined){var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();return promisedFinally(maybePromise,reasonOrValue,promise.isFulfilled())}}if(promise.isRejected()){NEXT_FILTER.e=reasonOrValue;return NEXT_FILTER}else{return reasonOrValue}}function tapHandler(value){var promise=this.promise;var handler=this.handler;var ret=promise._isBound()?handler.call(promise._boundTo,value):handler(value);if(ret!==undefined){var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();return promisedFinally(maybePromise,value,true)}}return value}Promise.prototype._passThroughHandler=function(handler,isFinally){if(typeof handler!=="function")return this.then();var promiseAndHandler={promise:this,handler:handler};return this._then(isFinally?finallyHandler:tapHandler,isFinally?finallyHandler:undefined,undefined,promiseAndHandler,undefined)};Promise.prototype.lastly=Promise.prototype["finally"]=function(handler){return this._passThroughHandler(handler,true)};Promise.prototype.tap=function(handler){return this._passThroughHandler(handler,false)}}},{"./util.js":38}],17:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise){var errors=_dereq_("./errors.js");var TypeError=errors.TypeError;var util=_dereq_("./util.js");var errorObj=util.errorObj;var tryCatch=util.tryCatch;var yieldHandlers=[];function promiseFromYieldHandler(value,yieldHandlers,traceParent){for(var i=0;i<yieldHandlers.length;++i){traceParent._pushContext();var result=tryCatch(yieldHandlers[i])(value);traceParent._popContext();if(result===errorObj){traceParent._pushContext();var ret=Promise.reject(errorObj.e);traceParent._popContext();return ret}var maybePromise=tryConvertToPromise(result,traceParent);if(maybePromise instanceof Promise)return maybePromise}return null}function PromiseSpawn(generatorFunction,receiver,yieldHandler,stack){var promise=this._promise=new Promise(INTERNAL);promise._captureStackTrace();this._stack=stack;this._generatorFunction=generatorFunction;this._receiver=receiver;this._generator=undefined;this._yieldHandlers=typeof yieldHandler==="function"?[yieldHandler].concat(yieldHandlers):yieldHandlers}PromiseSpawn.prototype.promise=function(){return this._promise};PromiseSpawn.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver);this._receiver=this._generatorFunction=undefined;this._next(undefined)};PromiseSpawn.prototype._continue=function(result){if(result===errorObj){return this._promise._rejectCallback(result.e,false,true)}var value=result.value;if(result.done===true){this._promise._resolveCallback(value)}else{var maybePromise=tryConvertToPromise(value,this._promise);if(!(maybePromise instanceof Promise)){maybePromise=promiseFromYieldHandler(maybePromise,this._yieldHandlers,this._promise);if(maybePromise===null){this._throw(new TypeError("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/4Y4pDk\n\n".replace("%s",value)+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")));return}}maybePromise._then(this._next,this._throw,undefined,this,null)}};PromiseSpawn.prototype._throw=function(reason){this._promise._attachExtraTrace(reason);this._promise._pushContext();var result=tryCatch(this._generator["throw"]).call(this._generator,reason);this._promise._popContext();this._continue(result)};PromiseSpawn.prototype._next=function(value){this._promise._pushContext();var result=tryCatch(this._generator.next).call(this._generator,value);this._promise._popContext();this._continue(result)};Promise.coroutine=function(generatorFunction,options){if(typeof generatorFunction!=="function"){throw new TypeError("generatorFunction must be a function\n\n See http://goo.gl/6Vqhm0\n")}var yieldHandler=Object(options).yieldHandler;var PromiseSpawn$=PromiseSpawn;var stack=(new Error).stack;return function(){var generator=generatorFunction.apply(this,arguments);var spawn=new PromiseSpawn$(undefined,undefined,yieldHandler,stack);spawn._generator=generator;spawn._next(undefined);return spawn.promise()}};Promise.coroutine.addYieldHandler=function(fn){if(typeof fn!=="function")throw new TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");yieldHandlers.push(fn)};Promise.spawn=function(generatorFunction){if(typeof generatorFunction!=="function"){return apiRejection("generatorFunction must be a function\n\n See http://goo.gl/6Vqhm0\n")}var spawn=new PromiseSpawn(generatorFunction,this);var ret=spawn.promise();spawn._run(Promise.spawn);return ret}}},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,INTERNAL){var util=_dereq_("./util.js");var canEvaluate=util.canEvaluate;var tryCatch=util.tryCatch;var errorObj=util.errorObj;var reject;if(!true){if(canEvaluate){var thenCallback=function(i){return new Function("value","holder"," \n 'use strict'; \n holder.pIndex = value; \n holder.checkFulfillment(this); \n ".replace(/Index/g,i))};var caller=function(count){var values=[];for(var i=1;i<=count;++i)values.push("holder.p"+i);return new Function("holder"," \n 'use strict'; \n var callback = holder.fn; \n return callback(values); \n ".replace(/values/g,values.join(", ")))};var thenCallbacks=[];var callers=[undefined];for(var i=1;i<=5;++i){thenCallbacks.push(thenCallback(i));callers.push(caller(i))}var Holder=function(total,fn){this.p1=this.p2=this.p3=this.p4=this.p5=null;
this.fn=fn;this.total=total;this.now=0};Holder.prototype.callers=callers;Holder.prototype.checkFulfillment=function(promise){var now=this.now;now++;var total=this.total;if(now>=total){var handler=this.callers[total];promise._pushContext();var ret=tryCatch(handler)(this);promise._popContext();if(ret===errorObj){promise._rejectCallback(ret.e,false,true)}else{promise._resolveCallback(ret)}}else{this.now=now}};var reject=function(reason){this._reject(reason)}}}Promise.join=function(){var last=arguments.length-1;var fn;if(last>0&&typeof arguments[last]==="function"){fn=arguments[last];if(!true){if(last<6&&canEvaluate){var ret=new Promise(INTERNAL);ret._captureStackTrace();var holder=new Holder(last,fn);var callbacks=thenCallbacks;for(var i=0;i<last;++i){var maybePromise=tryConvertToPromise(arguments[i],ret);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();if(maybePromise._isPending()){maybePromise._then(callbacks[i],reject,undefined,ret,holder)}else if(maybePromise._isFulfilled()){callbacks[i].call(ret,maybePromise._value(),holder)}else{ret._reject(maybePromise._reason())}}else{callbacks[i].call(ret,maybePromise,holder)}}return ret}}}var $_len=arguments.length;var args=new Array($_len);for(var $_i=0;$_i<$_len;++$_i){args[$_i]=arguments[$_i]}if(fn)args.pop();var ret=new PromiseArray(args).promise();return fn!==undefined?ret.spread(fn):ret}}},{"./util.js":38}],19:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL){var async=_dereq_("./async.js");var util=_dereq_("./util.js");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var PENDING={};var EMPTY_ARRAY=[];function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises);this._promise._captureStackTrace();this._callback=fn;this._preservedValues=_filter===INTERNAL?new Array(this.length()):null;this._limit=limit;this._inFlight=0;this._queue=limit>=1?[]:EMPTY_ARRAY;async.invoke(init,this,undefined)}util.inherits(MappingPromiseArray,PromiseArray);function init(){this._init$(undefined,-2)}MappingPromiseArray.prototype._init=function(){};MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values;var length=this.length();var preservedValues=this._preservedValues;var limit=this._limit;if(values[index]===PENDING){values[index]=value;if(limit>=1){this._inFlight--;this._drainQueue();if(this._isResolved())return}}else{if(limit>=1&&this._inFlight>=limit){values[index]=value;this._queue.push(index);return}if(preservedValues!==null)preservedValues[index]=value;var callback=this._callback;var receiver=this._promise._boundTo;this._promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length);this._promise._popContext();if(ret===errorObj)return this._reject(ret.e);var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();if(maybePromise._isPending()){if(limit>=1)this._inFlight++;values[index]=PENDING;return maybePromise._proxyPromiseArray(this,index)}else if(maybePromise._isFulfilled()){ret=maybePromise._value()}else{return this._reject(maybePromise._reason())}}values[index]=ret}var totalResolved=++this._totalResolved;if(totalResolved>=length){if(preservedValues!==null){this._filter(values,preservedValues)}else{this._resolve(values)}}};MappingPromiseArray.prototype._drainQueue=function(){var queue=this._queue;var limit=this._limit;var values=this._values;while(queue.length>0&&this._inFlight<limit){if(this._isResolved())return;var index=queue.pop();this._promiseFulfilled(values[index],index)}};MappingPromiseArray.prototype._filter=function(booleans,values){var len=values.length;var ret=new Array(len);var j=0;for(var i=0;i<len;++i){if(booleans[i])ret[j++]=values[i]}ret.length=j;this._resolve(ret)};MappingPromiseArray.prototype.preservedValues=function(){return this._preservedValues};function map(promises,fn,options,_filter){var limit=typeof options==="object"&&options!==null?options.concurrency:0;limit=typeof limit==="number"&&isFinite(limit)&&limit>=1?limit:0;return new MappingPromiseArray(promises,fn,limit,_filter)}Promise.prototype.map=function(fn,options){if(typeof fn!=="function")return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n");return map(this,fn,options,null).promise()};Promise.map=function(promises,fn,options,_filter){if(typeof fn!=="function")return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n");return map(promises,fn,options,_filter).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){var util=_dereq_("./util.js");var tryCatch=util.tryCatch;Promise.method=function(fn){if(typeof fn!=="function"){throw new Promise.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n")}return function(){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value=tryCatch(fn).apply(this,arguments);ret._popContext();ret._resolveFromSyncValue(value);return ret}};Promise.attempt=Promise["try"]=function(fn,args,ctx){if(typeof fn!=="function"){return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n")}var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value=util.isArray(args)?tryCatch(fn).apply(ctx,args):tryCatch(fn).call(ctx,args);ret._popContext();ret._resolveFromSyncValue(value);return ret};Promise.prototype._resolveFromSyncValue=function(value){if(value===util.errorObj){this._rejectCallback(value.e,false,true)}else{this._resolveCallback(value,true)}}}},{"./util.js":38}],21:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var util=_dereq_("./util.js");var async=_dereq_("./async.js");var tryCatch=util.tryCatch;var errorObj=util.errorObj;function spreadAdapter(val,nodeback){var promise=this;if(!util.isArray(val))return successAdapter.call(promise,val,nodeback);var ret=tryCatch(nodeback).apply(promise._boundTo,[null].concat(val));if(ret===errorObj){async.throwLater(ret.e)}}function successAdapter(val,nodeback){var promise=this;var receiver=promise._boundTo;var ret=val===undefined?tryCatch(nodeback).call(receiver,null):tryCatch(nodeback).call(receiver,null,val);if(ret===errorObj){async.throwLater(ret.e)}}function errorAdapter(reason,nodeback){var promise=this;if(!reason){var target=promise._target();var newReason=target._getCarriedStackTrace();newReason.cause=reason;reason=newReason}var ret=tryCatch(nodeback).call(promise._boundTo,reason);if(ret===errorObj){async.throwLater(ret.e)}}Promise.prototype.asCallback=Promise.prototype.nodeify=function(nodeback,options){if(typeof nodeback=="function"){var adapter=successAdapter;if(options!==undefined&&Object(options).spread){adapter=spreadAdapter}this._then(adapter,errorAdapter,undefined,this,nodeback)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray){var util=_dereq_("./util.js");var async=_dereq_("./async.js");var tryCatch=util.tryCatch;var errorObj=util.errorObj;Promise.prototype.progressed=function(handler){return this._then(undefined,undefined,handler,undefined,undefined)};Promise.prototype._progress=function(progressValue){if(this._isFollowingOrFulfilledOrRejected())return;this._target()._progressUnchecked(progressValue)};Promise.prototype._progressHandlerAt=function(index){return index===0?this._progressHandler0:this[(index<<2)+index-5+2]};Promise.prototype._doProgressWith=function(progression){var progressValue=progression.value;var handler=progression.handler;var promise=progression.promise;var receiver=progression.receiver;var ret=tryCatch(handler).call(receiver,progressValue);if(ret===errorObj){if(ret.e!=null&&ret.e.name!=="StopProgressPropagation"){var trace=util.canAttachTrace(ret.e)?ret.e:new Error(util.toString(ret.e));promise._attachExtraTrace(trace);promise._progress(ret.e)}}else if(ret instanceof Promise){ret._then(promise._progress,null,null,promise,undefined)}else{promise._progress(ret)}};Promise.prototype._progressUnchecked=function(progressValue){var len=this._length();var progress=this._progress;for(var i=0;i<len;i++){var handler=this._progressHandlerAt(i);var promise=this._promiseAt(i);if(!(promise instanceof Promise)){var receiver=this._receiverAt(i);if(typeof handler==="function"){handler.call(receiver,progressValue,promise)}else if(receiver instanceof PromiseArray&&!receiver._isResolved()){receiver._promiseProgressed(progressValue,promise)}continue}if(typeof handler==="function"){async.invoke(this._doProgressWith,this,{handler:handler,promise:promise,receiver:this._receiverAt(i),value:progressValue})}else{async.invoke(progress,promise,progressValue)}}}}},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){"use strict";module.exports=function(){var makeSelfResolutionError=function(){return new TypeError("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")};var reflect=function(){return new Promise.PromiseInspection(this._target())};var apiRejection=function(msg){return Promise.reject(new TypeError(msg))};var util=_dereq_("./util.js");var async=_dereq_("./async.js");var errors=_dereq_("./errors.js");var TypeError=Promise.TypeError=errors.TypeError;Promise.RangeError=errors.RangeError;Promise.CancellationError=errors.CancellationError;Promise.TimeoutError=errors.TimeoutError;Promise.OperationalError=errors.OperationalError;Promise.RejectionError=errors.OperationalError;Promise.AggregateError=errors.AggregateError;var INTERNAL=function(){};var APPLY={};var NEXT_FILTER={e:null};var tryConvertToPromise=_dereq_("./thenables.js")(Promise,INTERNAL);var PromiseArray=_dereq_("./promise_array.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection);var CapturedTrace=_dereq_("./captured_trace.js")();var isDebugging=_dereq_("./debuggability.js")(Promise,CapturedTrace);var createContext=_dereq_("./context.js")(Promise,CapturedTrace,isDebugging);var CatchFilter=_dereq_("./catch_filter.js")(NEXT_FILTER);var PromiseResolver=_dereq_("./promise_resolver.js");var nodebackForPromise=PromiseResolver._nodebackForPromise;var errorObj=util.errorObj;var tryCatch=util.tryCatch;function Promise(resolver){if(typeof resolver!=="function"){throw new TypeError("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n")}if(this.constructor!==Promise){throw new TypeError("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n")}this._bitField=0;this._fulfillmentHandler0=undefined;this._rejectionHandler0=undefined;this._progressHandler0=undefined;this._promise0=undefined;this._receiver0=undefined;this._settledValue=undefined;if(resolver!==INTERNAL)this._resolveFromResolver(resolver)}Promise.prototype.toString=function(){return"[object Promise]"};Promise.prototype.caught=Promise.prototype["catch"]=function(fn){var len=arguments.length;if(len>1){var catchInstances=new Array(len-1),j=0,i;for(i=0;i<len-1;++i){var item=arguments[i];if(typeof item==="function"){catchInstances[j++]=item}else{return Promise.reject(new TypeError("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"))}}catchInstances.length=j;fn=arguments[i];var catchFilter=new CatchFilter(catchInstances,fn,this);return this._then(undefined,catchFilter.doFilter,undefined,catchFilter,undefined)}return this._then(undefined,fn,undefined,undefined,undefined)};Promise.prototype.reflect=function(){return this._then(reflect,reflect,undefined,this,undefined)};Promise.prototype.then=function(didFulfill,didReject,didProgress){if(isDebugging()&&arguments.length>0&&typeof didFulfill!=="function"&&typeof didReject!=="function"){var msg=".then() only accepts functions but was passed: "+util.classString(didFulfill);if(arguments.length>1){msg+=", "+util.classString(didReject)}this._warn(msg)}return this._then(didFulfill,didReject,didProgress,undefined,undefined)};Promise.prototype.done=function(didFulfill,didReject,didProgress){var promise=this._then(didFulfill,didReject,didProgress,undefined,undefined);promise._setIsFinal()};Promise.prototype.spread=function(didFulfill,didReject){return this.all()._then(didFulfill,didReject,undefined,APPLY,undefined)};Promise.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()};Promise.prototype.toJSON=function(){var ret={isFulfilled:false,isRejected:false,fulfillmentValue:undefined,rejectionReason:undefined};if(this.isFulfilled()){ret.fulfillmentValue=this.value();ret.isFulfilled=true}else if(this.isRejected()){ret.rejectionReason=this.reason();ret.isRejected=true}return ret};Promise.prototype.all=function(){return new PromiseArray(this).promise()};Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn)};Promise.is=function(val){return val instanceof Promise};Promise.fromNode=function(fn){var ret=new Promise(INTERNAL);var result=tryCatch(fn)(nodebackForPromise(ret));if(result===errorObj){ret._rejectCallback(result.e,true,true)}return ret};Promise.all=function(promises){return new PromiseArray(promises).promise()};Promise.defer=Promise.pending=function(){var promise=new Promise(INTERNAL);return new PromiseResolver(promise)};Promise.cast=function(obj){var ret=tryConvertToPromise(obj);if(!(ret instanceof Promise)){var val=ret;ret=new Promise(INTERNAL);ret._fulfillUnchecked(val)}return ret};Promise.resolve=Promise.fulfilled=Promise.cast;Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._rejectCallback(reason,true);return ret};Promise.setScheduler=function(fn){if(typeof fn!=="function")throw new TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");var prev=async._schedule;async._schedule=fn;return prev};Promise.prototype._then=function(didFulfill,didReject,didProgress,receiver,internalData){var haveInternalData=internalData!==undefined;var ret=haveInternalData?internalData:new Promise(INTERNAL);if(!haveInternalData){ret._propagateFrom(this,4|1);ret._captureStackTrace()}var target=this._target();if(target!==this){if(receiver===undefined)receiver=this._boundTo;if(!haveInternalData)ret._setIsMigrated()}var callbackIndex=target._addCallbacks(didFulfill,didReject,didProgress,ret,receiver);if(target._isResolved()&&!target._isSettlePromisesQueued()){async.invoke(target._settlePromiseAtPostResolution,target,callbackIndex)}return ret};Promise.prototype._settlePromiseAtPostResolution=function(index){if(this._isRejectionUnhandled())this._unsetRejectionIsUnhandled();this._settlePromiseAt(index)};Promise.prototype._length=function(){return this._bitField&131071};Promise.prototype._isFollowingOrFulfilledOrRejected=function(){return(this._bitField&939524096)>0};Promise.prototype._isFollowing=function(){return(this._bitField&536870912)===536870912};Promise.prototype._setLength=function(len){this._bitField=this._bitField&-131072|len&131071};Promise.prototype._setFulfilled=function(){this._bitField=this._bitField|268435456};Promise.prototype._setRejected=function(){this._bitField=this._bitField|134217728};Promise.prototype._setFollowing=function(){this._bitField=this._bitField|536870912};Promise.prototype._setIsFinal=function(){this._bitField=this._bitField|33554432};Promise.prototype._isFinal=function(){return(this._bitField&33554432)>0};Promise.prototype._cancellable=function(){return(this._bitField&67108864)>0};Promise.prototype._setCancellable=function(){this._bitField=this._bitField|67108864};Promise.prototype._unsetCancellable=function(){this._bitField=this._bitField&~67108864};Promise.prototype._setIsMigrated=function(){this._bitField=this._bitField|4194304};Promise.prototype._unsetIsMigrated=function(){this._bitField=this._bitField&~4194304};Promise.prototype._isMigrated=function(){return(this._bitField&4194304)>0};Promise.prototype._receiverAt=function(index){var ret=index===0?this._receiver0:this[index*5-5+4];if(ret===undefined&&this._isBound()){return this._boundTo}return ret};Promise.prototype._promiseAt=function(index){return index===0?this._promise0:this[index*5-5+3]};Promise.prototype._fulfillmentHandlerAt=function(index){return index===0?this._fulfillmentHandler0:this[index*5-5+0]};Promise.prototype._rejectionHandlerAt=function(index){return index===0?this._rejectionHandler0:this[index*5-5+1]};Promise.prototype._migrateCallbacks=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index);var reject=follower._rejectionHandlerAt(index);var progress=follower._progressHandlerAt(index);var promise=follower._promiseAt(index);var receiver=follower._receiverAt(index);if(promise instanceof Promise)promise._setIsMigrated();this._addCallbacks(fulfill,reject,progress,promise,receiver)};Promise.prototype._addCallbacks=function(fulfill,reject,progress,promise,receiver){var index=this._length();if(index>=131071-5){index=0;this._setLength(0)}if(index===0){this._promise0=promise;if(receiver!==undefined)this._receiver0=receiver;if(typeof fulfill==="function"&&!this._isCarryingStackTrace())this._fulfillmentHandler0=fulfill;if(typeof reject==="function")this._rejectionHandler0=reject;if(typeof progress==="function")this._progressHandler0=progress}else{var base=index*5-5;this[base+3]=promise;this[base+4]=receiver;if(typeof fulfill==="function")this[base+0]=fulfill;if(typeof reject==="function")this[base+1]=reject;if(typeof progress==="function")this[base+2]=progress}this._setLength(index+1);return index};Promise.prototype._setProxyHandlers=function(receiver,promiseSlotValue){var index=this._length();if(index>=131071-5){index=0;this._setLength(0)}if(index===0){this._promise0=promiseSlotValue;this._receiver0=receiver}else{var base=index*5-5;this[base+3]=promiseSlotValue;this[base+4]=receiver}this._setLength(index+1)};Promise.prototype._proxyPromiseArray=function(promiseArray,index){this._setProxyHandlers(promiseArray,index)};Promise.prototype._resolveCallback=function(value,shouldBind){if(this._isFollowingOrFulfilledOrRejected())return;if(value===this)return this._rejectCallback(makeSelfResolutionError(),false,true);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);var propagationFlags=1|(shouldBind?4:0);this._propagateFrom(maybePromise,propagationFlags);var promise=maybePromise._target();if(promise._isPending()){var len=this._length();for(var i=0;i<len;++i){promise._migrateCallbacks(this,i)}this._setFollowing();this._setLength(0);this._setFollowee(promise)}else if(promise._isFulfilled()){this._fulfillUnchecked(promise._value())}else{this._rejectUnchecked(promise._reason(),promise._getCarriedStackTrace())}};Promise.prototype._rejectCallback=function(reason,synchronous,shouldNotMarkOriginatingFromRejection){if(!shouldNotMarkOriginatingFromRejection){util.markAsOriginatingFromRejection(reason)}var trace=util.ensureErrorObject(reason);var hasStack=trace===reason;this._attachExtraTrace(trace,synchronous?hasStack:false);this._reject(reason,hasStack?undefined:trace)};Promise.prototype._resolveFromResolver=function(resolver){var promise=this;this._captureStackTrace();this._pushContext();var synchronous=true;var r=tryCatch(resolver)(function(value){if(promise===null)return;promise._resolveCallback(value);promise=null},function(reason){if(promise===null)return;promise._rejectCallback(reason,synchronous);promise=null});synchronous=false;this._popContext();if(r!==undefined&&r===errorObj&&promise!==null){promise._rejectCallback(r.e,true,true);promise=null}};Promise.prototype._settlePromiseFromHandler=function(handler,receiver,value,promise){if(promise._isRejected())return;promise._pushContext();var x;if(receiver===APPLY&&!this._isRejected()){x=tryCatch(handler).apply(this._boundTo,value)}else{x=tryCatch(handler).call(receiver,value)}promise._popContext();if(x===errorObj||x===promise||x===NEXT_FILTER){var err=x===promise?makeSelfResolutionError():x.e;promise._rejectCallback(err,false,true)}else{promise._resolveCallback(x)}};Promise.prototype._target=function(){var ret=this;while(ret._isFollowing())ret=ret._followee();return ret};Promise.prototype._followee=function(){return this._rejectionHandler0};Promise.prototype._setFollowee=function(promise){this._rejectionHandler0=promise};Promise.prototype._cleanValues=function(){if(this._cancellable()){this._cancellationParent=undefined}};Promise.prototype._propagateFrom=function(parent,flags){if((flags&1)>0&&parent._cancellable()){this._setCancellable();this._cancellationParent=parent}if((flags&4)>0&&parent._isBound()){this._setBoundTo(parent._boundTo)}};Promise.prototype._fulfill=function(value){if(this._isFollowingOrFulfilledOrRejected())return;this._fulfillUnchecked(value)};Promise.prototype._reject=function(reason,carriedStackTrace){if(this._isFollowingOrFulfilledOrRejected())return;this._rejectUnchecked(reason,carriedStackTrace)};Promise.prototype._settlePromiseAt=function(index){var promise=this._promiseAt(index);var isPromise=promise instanceof Promise;if(isPromise&&promise._isMigrated()){promise._unsetIsMigrated();return async.invoke(this._settlePromiseAt,this,index)}var handler=this._isFulfilled()?this._fulfillmentHandlerAt(index):this._rejectionHandlerAt(index);var carriedStackTrace=this._isCarryingStackTrace()?this._getCarriedStackTrace():undefined;var value=this._settledValue;var receiver=this._receiverAt(index);this._clearCallbackDataAtIndex(index);if(typeof handler==="function"){if(!isPromise){handler.call(receiver,value,promise)}else{this._settlePromiseFromHandler(handler,receiver,value,promise)}}else if(receiver instanceof PromiseArray){if(!receiver._isResolved()){if(this._isFulfilled()){receiver._promiseFulfilled(value,promise)}else{receiver._promiseRejected(value,promise)}}}else if(isPromise){if(this._isFulfilled()){promise._fulfill(value)}else{promise._reject(value,carriedStackTrace)}}if(index>=4&&(index&31)===4)async.invokeLater(this._setLength,this,0)};Promise.prototype._clearCallbackDataAtIndex=function(index){if(index===0){if(!this._isCarryingStackTrace()){this._fulfillmentHandler0=undefined}this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=undefined}else{var base=index*5-5;this[base+3]=this[base+4]=this[base+0]=this[base+1]=this[base+2]=undefined}};Promise.prototype._isSettlePromisesQueued=function(){return(this._bitField&-1073741824)===-1073741824};Promise.prototype._setSettlePromisesQueued=function(){this._bitField=this._bitField|-1073741824};Promise.prototype._unsetSettlePromisesQueued=function(){this._bitField=this._bitField&~-1073741824};Promise.prototype._queueSettlePromises=function(){async.settlePromises(this);this._setSettlePromisesQueued()};Promise.prototype._fulfillUnchecked=function(value){if(value===this){var err=makeSelfResolutionError();this._attachExtraTrace(err);return this._rejectUnchecked(err,undefined)}this._setFulfilled();this._settledValue=value;this._cleanValues();if(this._length()>0){this._queueSettlePromises()}};Promise.prototype._rejectUncheckedCheckError=function(reason){var trace=util.ensureErrorObject(reason);this._rejectUnchecked(reason,trace===reason?undefined:trace)};Promise.prototype._rejectUnchecked=function(reason,trace){if(reason===this){var err=makeSelfResolutionError();this._attachExtraTrace(err);return this._rejectUnchecked(err)}this._setRejected();this._settledValue=reason;this._cleanValues();if(this._isFinal()){async.throwLater(function(e){if("stack"in e){async.invokeFirst(CapturedTrace.unhandledRejection,undefined,e)}throw e},trace===undefined?reason:trace);return}if(trace!==undefined&&trace!==reason){this._setCarriedStackTrace(trace)}if(this._length()>0){this._queueSettlePromises()}else{this._ensurePossibleRejectionHandled()}};Promise.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();var len=this._length();for(var i=0;i<len;i++){this._settlePromiseAt(i)}};Promise._makeSelfResolutionError=makeSelfResolutionError;_dereq_("./progress.js")(Promise,PromiseArray);_dereq_("./method.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection);_dereq_("./bind.js")(Promise,INTERNAL,tryConvertToPromise);_dereq_("./finally.js")(Promise,NEXT_FILTER,tryConvertToPromise);_dereq_("./direct_resolve.js")(Promise);_dereq_("./synchronous_inspection.js")(Promise);_dereq_("./join.js")(Promise,PromiseArray,tryConvertToPromise,INTERNAL);Promise.Promise=Promise;_dereq_("./map.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL);_dereq_("./cancel.js")(Promise);_dereq_("./using.js")(Promise,apiRejection,tryConvertToPromise,createContext);_dereq_("./generators.js")(Promise,apiRejection,INTERNAL,tryConvertToPromise);_dereq_("./nodeify.js")(Promise);_dereq_("./call_get.js")(Promise);_dereq_("./props.js")(Promise,PromiseArray,tryConvertToPromise,apiRejection);_dereq_("./race.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection);_dereq_("./reduce.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL);_dereq_("./settle.js")(Promise,PromiseArray);_dereq_("./some.js")(Promise,PromiseArray,apiRejection);_dereq_("./promisify.js")(Promise,INTERNAL);_dereq_("./any.js")(Promise);_dereq_("./each.js")(Promise,INTERNAL);_dereq_("./timers.js")(Promise,INTERNAL);_dereq_("./filter.js")(Promise,INTERNAL);util.toFastProperties(Promise);util.toFastProperties(Promise.prototype);function fillTypes(value){var p=new Promise(INTERNAL);p._fulfillmentHandler0=value;p._rejectionHandler0=value;p._progressHandler0=value;p._promise0=value;p._receiver0=value;p._settledValue=value}fillTypes({a:1});fillTypes({b:2});fillTypes({c:3});fillTypes(1);fillTypes(function(){});fillTypes(undefined);fillTypes(false);fillTypes(new Promise(INTERNAL));CapturedTrace.setBounds(async.firstLineError,util.lastLineError);return Promise}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){var util=_dereq_("./util.js");var isArray=util.isArray;function toResolutionValue(val){switch(val){case-2:return[];case-3:return{}}}function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);var parent;if(values instanceof Promise){parent=values;promise._propagateFrom(parent,1|4)}this._values=values;this._length=0;this._totalResolved=0;this._init(undefined,-2)}PromiseArray.prototype.length=function(){return this._length};PromiseArray.prototype.promise=function(){return this._promise};PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){var values=tryConvertToPromise(this._values,this._promise);if(values instanceof Promise){values=values._target();this._values=values;if(values._isFulfilled()){values=values._value();if(!isArray(values)){var err=new Promise.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");this.__hardReject__(err);return}}else if(values._isPending()){values._then(init,this._reject,undefined,this,resolveValueIfEmpty);return}else{this._reject(values._reason());return}}else if(!isArray(values)){this._promise._reject(apiRejection("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());return}if(values.length===0){if(resolveValueIfEmpty===-5){this._resolveEmptyArray()}else{this._resolve(toResolutionValue(resolveValueIfEmpty))}return}var len=this.getActualLength(values.length);this._length=len;this._values=this.shouldCopyValues()?new Array(len):this._values;var promise=this._promise;for(var i=0;i<len;++i){var isResolved=this._isResolved();var maybePromise=tryConvertToPromise(values[i],promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();if(isResolved){maybePromise._unsetRejectionIsUnhandled()}else if(maybePromise._isPending()){maybePromise._proxyPromiseArray(this,i)}else if(maybePromise._isFulfilled()){this._promiseFulfilled(maybePromise._value(),i)}else{this._promiseRejected(maybePromise._reason(),i)}}else if(!isResolved){this._promiseFulfilled(maybePromise,i)}}};PromiseArray.prototype._isResolved=function(){return this._values===null};PromiseArray.prototype._resolve=function(value){this._values=null;this._promise._fulfill(value)};PromiseArray.prototype.__hardReject__=PromiseArray.prototype._reject=function(reason){this._values=null;this._promise._rejectCallback(reason,false,true)};PromiseArray.prototype._promiseProgressed=function(progressValue,index){this._promise._progress({index:index,value:progressValue})};PromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values)}};PromiseArray.prototype._promiseRejected=function(reason,index){this._totalResolved++;this._reject(reason)};PromiseArray.prototype.shouldCopyValues=function(){return true};PromiseArray.prototype.getActualLength=function(len){return len};return PromiseArray}},{"./util.js":38}],25:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util.js");var maybeWrapAsError=util.maybeWrapAsError;var errors=_dereq_("./errors.js");var TimeoutError=errors.TimeoutError;var OperationalError=errors.OperationalError;var haveGetters=util.haveGetters;var es5=_dereq_("./es5.js");function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}var rErrorKey=/^(?:name|message|stack|cause)$/;function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj);ret.name=obj.name;ret.message=obj.message;ret.stack=obj.stack;var keys=es5.keys(obj);for(var i=0;i<keys.length;++i){var key=keys[i];if(!rErrorKey.test(key)){ret[key]=obj[key]}}return ret}util.markAsOriginatingFromRejection(obj);return obj}function nodebackForPromise(promise){return function(err,value){if(promise===null)return;if(err){var wrapped=wrapAsOperationalError(maybeWrapAsError(err));promise._attachExtraTrace(wrapped);promise._reject(wrapped)}else if(arguments.length>2){var $_len=arguments.length;var args=new Array($_len-1);for(var $_i=1;$_i<$_len;++$_i){args[$_i-1]=arguments[$_i]}promise._fulfill(args)}else{promise._fulfill(value)}promise=null}}var PromiseResolver;if(!haveGetters){PromiseResolver=function(promise){this.promise=promise;this.asCallback=nodebackForPromise(promise);this.callback=this.asCallback}}else{PromiseResolver=function(promise){this.promise=promise}}if(haveGetters){var prop={get:function(){return nodebackForPromise(this.promise)}};es5.defineProperty(PromiseResolver.prototype,"asCallback",prop);es5.defineProperty(PromiseResolver.prototype,"callback",prop)}PromiseResolver._nodebackForPromise=nodebackForPromise;PromiseResolver.prototype.toString=function(){return"[object PromiseResolver]"};PromiseResolver.prototype.resolve=PromiseResolver.prototype.fulfill=function(value){if(!(this instanceof PromiseResolver)){throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n")}this.promise._resolveCallback(value)};PromiseResolver.prototype.reject=function(reason){if(!(this instanceof PromiseResolver)){throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n")}this.promise._rejectCallback(reason)};PromiseResolver.prototype.progress=function(value){
if(!(this instanceof PromiseResolver)){throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n")}this.promise._progress(value)};PromiseResolver.prototype.cancel=function(err){this.promise.cancel(err)};PromiseResolver.prototype.timeout=function(){this.reject(new TimeoutError("timeout"))};PromiseResolver.prototype.isResolved=function(){return this.promise.isResolved()};PromiseResolver.prototype.toJSON=function(){return this.promise.toJSON()};module.exports=PromiseResolver},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var THIS={};var util=_dereq_("./util.js");var nodebackForPromise=_dereq_("./promise_resolver.js")._nodebackForPromise;var withAppended=util.withAppended;var maybeWrapAsError=util.maybeWrapAsError;var canEvaluate=util.canEvaluate;var TypeError=_dereq_("./errors").TypeError;var defaultSuffix="Async";var defaultPromisified={__isPromisified__:true};var noCopyPropsPattern=/^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/;var defaultFilter=function(name,func){return util.isIdentifier(name)&&name.charAt(0)!=="_"&&!util.isClass(func)};function propsFilter(key){return!noCopyPropsPattern.test(key)}function isPromisified(fn){try{return fn.__isPromisified__===true}catch(e){return false}}function hasPromisified(obj,key,suffix){var val=util.getDataPropertyOrDefault(obj,key+suffix,defaultPromisified);return val?isPromisified(val):false}function checkValid(ret,suffix,suffixRegexp){for(var i=0;i<ret.length;i+=2){var key=ret[i];if(suffixRegexp.test(key)){var keyWithoutAsyncSuffix=key.replace(suffixRegexp,"");for(var j=0;j<ret.length;j+=2){if(ret[j]===keyWithoutAsyncSuffix){throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/iWrZbw\n".replace("%s",suffix))}}}}}function promisifiableMethods(obj,suffix,suffixRegexp,filter){var keys=util.inheritedDataKeys(obj);var ret=[];for(var i=0;i<keys.length;++i){var key=keys[i];var value=obj[key];var passesDefaultFilter=filter===defaultFilter?true:defaultFilter(key,value,obj);if(typeof value==="function"&&!isPromisified(value)&&!hasPromisified(obj,key,suffix)&&filter(key,value,obj,passesDefaultFilter)){ret.push(key,value)}}checkValid(ret,suffix,suffixRegexp);return ret}var escapeIdentRegex=function(str){return str.replace(/([$])/,"\\$")};var makeNodePromisifiedEval;if(!true){var switchCaseArgumentOrder=function(likelyArgumentCount){var ret=[likelyArgumentCount];var min=Math.max(0,likelyArgumentCount-1-3);for(var i=likelyArgumentCount-1;i>=min;--i){ret.push(i)}for(var i=likelyArgumentCount+1;i<=3;++i){ret.push(i)}return ret};var argumentSequence=function(argumentCount){return util.filledRange(argumentCount,"_arg","")};var parameterDeclaration=function(parameterCount){return util.filledRange(Math.max(parameterCount,3),"_arg","")};var parameterCount=function(fn){if(typeof fn.length==="number"){return Math.max(Math.min(fn.length,1023+1),0)}return 0};makeNodePromisifiedEval=function(callback,receiver,originalName,fn){var newParameterCount=Math.max(0,parameterCount(fn)-1);var argumentOrder=switchCaseArgumentOrder(newParameterCount);var shouldProxyThis=typeof callback==="string"||receiver===THIS;function generateCallForArgumentCount(count){var args=argumentSequence(count).join(", ");var comma=count>0?", ":"";var ret;if(shouldProxyThis){ret="ret = callback.call(this, {{args}}, nodeback); break;\n"}else{ret=receiver===undefined?"ret = callback({{args}}, nodeback); break;\n":"ret = callback.call(receiver, {{args}}, nodeback); break;\n"}return ret.replace("{{args}}",args).replace(", ",comma)}function generateArgumentSwitchCase(){var ret="";for(var i=0;i<argumentOrder.length;++i){ret+="case "+argumentOrder[i]+":"+generateCallForArgumentCount(argumentOrder[i])}ret+=" \n default: \n var args = new Array(len + 1); \n var i = 0; \n for (var i = 0; i < len; ++i) { \n args[i] = arguments[i]; \n } \n args[i] = nodeback; \n [CodeForCall] \n break; \n ".replace("[CodeForCall]",shouldProxyThis?"ret = callback.apply(this, args);\n":"ret = callback.apply(receiver, args);\n");return ret}var getFunctionCode=typeof callback==="string"?"this != null ? this['"+callback+"'] : fn":"fn";return new Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","INTERNAL","'use strict'; \n var ret = function (Parameters) { \n 'use strict'; \n var len = arguments.length; \n var promise = new Promise(INTERNAL); \n promise._captureStackTrace(); \n var nodeback = nodebackForPromise(promise); \n var ret; \n var callback = tryCatch([GetFunctionCode]); \n switch(len) { \n [CodeForSwitchCase] \n } \n if (ret === errorObj) { \n promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n } \n return promise; \n }; \n ret.__isPromisified__ = true; \n return ret; \n ".replace("Parameters",parameterDeclaration(newParameterCount)).replace("[CodeForSwitchCase]",generateArgumentSwitchCase()).replace("[GetFunctionCode]",getFunctionCode))(Promise,fn,receiver,withAppended,maybeWrapAsError,nodebackForPromise,util.tryCatch,util.errorObj,INTERNAL)}}function makeNodePromisifiedClosure(callback,receiver,_,fn){var defaultThis=function(){return this}();var method=callback;if(typeof method==="string"){callback=fn}function promisified(){var _receiver=receiver;if(receiver===THIS)_receiver=this;var promise=new Promise(INTERNAL);promise._captureStackTrace();var cb=typeof method==="string"&&this!==defaultThis?this[method]:callback;var fn=nodebackForPromise(promise);try{cb.apply(_receiver,withAppended(arguments,fn))}catch(e){promise._rejectCallback(maybeWrapAsError(e),true,true)}return promise}promisified.__isPromisified__=true;return promisified}var makeNodePromisified=canEvaluate?makeNodePromisifiedEval:makeNodePromisifiedClosure;function promisifyAll(obj,suffix,filter,promisifier){var suffixRegexp=new RegExp(escapeIdentRegex(suffix)+"$");var methods=promisifiableMethods(obj,suffix,suffixRegexp,filter);for(var i=0,len=methods.length;i<len;i+=2){var key=methods[i];var fn=methods[i+1];var promisifiedKey=key+suffix;obj[promisifiedKey]=promisifier===makeNodePromisified?makeNodePromisified(key,THIS,key,fn,suffix):promisifier(fn,function(){return makeNodePromisified(key,THIS,key,fn,suffix)})}util.toFastProperties(obj);return obj}function promisify(callback,receiver){return makeNodePromisified(callback,receiver,undefined,callback)}Promise.promisify=function(fn,receiver){if(typeof fn!=="function"){throw new TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n")}if(isPromisified(fn)){return fn}var ret=promisify(fn,arguments.length<2?THIS:receiver);util.copyDescriptors(fn,ret,propsFilter);return ret};Promise.promisifyAll=function(target,options){if(typeof target!=="function"&&typeof target!=="object"){throw new TypeError("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n")}options=Object(options);var suffix=options.suffix;if(typeof suffix!=="string")suffix=defaultSuffix;var filter=options.filter;if(typeof filter!=="function")filter=defaultFilter;var promisifier=options.promisifier;if(typeof promisifier!=="function")promisifier=makeNodePromisified;if(!util.isIdentifier(suffix)){throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n")}var keys=util.inheritedDataKeys(target);for(var i=0;i<keys.length;++i){var value=target[keys[i]];if(keys[i]!=="constructor"&&util.isClass(value)){promisifyAll(value.prototype,suffix,filter,promisifier);promisifyAll(value,suffix,filter,promisifier)}}return promisifyAll(target,suffix,filter,promisifier)}}},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,apiRejection){var util=_dereq_("./util.js");var isObject=util.isObject;var es5=_dereq_("./es5.js");function PropertiesPromiseArray(obj){var keys=es5.keys(obj);var len=keys.length;var values=new Array(len*2);for(var i=0;i<len;++i){var key=keys[i];values[i]=obj[key];values[i+len]=key}this.constructor$(values)}util.inherits(PropertiesPromiseArray,PromiseArray);PropertiesPromiseArray.prototype._init=function(){this._init$(undefined,-3)};PropertiesPromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){var val={};var keyOffset=this.length();for(var i=0,len=this.length();i<len;++i){val[this._values[i+keyOffset]]=this._values[i]}this._resolve(val)}};PropertiesPromiseArray.prototype._promiseProgressed=function(value,index){this._promise._progress({key:this._values[index+this.length()],value:value})};PropertiesPromiseArray.prototype.shouldCopyValues=function(){return false};PropertiesPromiseArray.prototype.getActualLength=function(len){return len>>1};function props(promises){var ret;var castValue=tryConvertToPromise(promises);if(!isObject(castValue)){return apiRejection("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}else if(castValue instanceof Promise){ret=castValue._then(Promise.props,undefined,undefined,undefined,undefined)}else{ret=new PropertiesPromiseArray(castValue).promise()}if(castValue instanceof Promise){ret._propagateFrom(castValue,4)}return ret}Promise.prototype.props=function(){return props(this)};Promise.props=function(promises){return props(promises)}}},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){"use strict";function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j<len;++j){dst[j+dstIndex]=src[j+srcIndex];src[j+srcIndex]=void 0}}function Queue(capacity){this._capacity=capacity;this._length=0;this._front=0}Queue.prototype._willBeOverCapacity=function(size){return this._capacity<size};Queue.prototype._pushOne=function(arg){var length=this.length();this._checkCapacity(length+1);var i=this._front+length&this._capacity-1;this[i]=arg;this._length=length+1};Queue.prototype._unshiftOne=function(value){var capacity=this._capacity;this._checkCapacity(this.length()+1);var front=this._front;var i=(front-1&capacity-1^capacity)-capacity;this[i]=value;this._front=i;this._length=this.length()+1};Queue.prototype.unshift=function(fn,receiver,arg){this._unshiftOne(arg);this._unshiftOne(receiver);this._unshiftOne(fn)};Queue.prototype.push=function(fn,receiver,arg){var length=this.length()+3;if(this._willBeOverCapacity(length)){this._pushOne(fn);this._pushOne(receiver);this._pushOne(arg);return}var j=this._front+length-3;this._checkCapacity(length);var wrapMask=this._capacity-1;this[j+0&wrapMask]=fn;this[j+1&wrapMask]=receiver;this[j+2&wrapMask]=arg;this._length=length};Queue.prototype.shift=function(){var front=this._front,ret=this[front];this[front]=undefined;this._front=front+1&this._capacity-1;this._length--;return ret};Queue.prototype.length=function(){return this._length};Queue.prototype._checkCapacity=function(size){if(this._capacity<size){this._resizeTo(this._capacity<<1)}};Queue.prototype._resizeTo=function(capacity){var oldCapacity=this._capacity;this._capacity=capacity;var front=this._front;var length=this._length;var moveItemsCount=front+length&oldCapacity-1;arrayMove(this,0,this,oldCapacity,moveItemsCount)};module.exports=Queue},{}],29:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){var isArray=_dereq_("./util.js").isArray;var raceLater=function(promise){return promise.then(function(array){return race(array,promise)})};function race(promises,parent){var maybePromise=tryConvertToPromise(promises);if(maybePromise instanceof Promise){return raceLater(maybePromise)}else if(!isArray(promises)){return apiRejection("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")}var ret=new Promise(INTERNAL);if(parent!==undefined){ret._propagateFrom(parent,4|1)}var fulfill=ret._fulfill;var reject=ret._reject;for(var i=0,len=promises.length;i<len;++i){var val=promises[i];if(val===undefined&&!(i in promises)){continue}Promise.cast(val)._then(fulfill,reject,undefined,ret,null)}return ret}Promise.race=function(promises){return race(promises,undefined)};Promise.prototype.race=function(){return race(this,undefined)}}},{"./util.js":38}],30:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL){var async=_dereq_("./async.js");var util=_dereq_("./util.js");var tryCatch=util.tryCatch;var errorObj=util.errorObj;function ReductionPromiseArray(promises,fn,accum,_each){this.constructor$(promises);this._promise._captureStackTrace();this._preservedValues=_each===INTERNAL?[]:null;this._zerothIsAccum=accum===undefined;this._gotAccum=false;this._reducingIndex=this._zerothIsAccum?1:0;this._valuesPhase=undefined;var maybePromise=tryConvertToPromise(accum,this._promise);var rejected=false;var isPromise=maybePromise instanceof Promise;if(isPromise){maybePromise=maybePromise._target();if(maybePromise._isPending()){maybePromise._proxyPromiseArray(this,-1)}else if(maybePromise._isFulfilled()){accum=maybePromise._value();this._gotAccum=true}else{this._reject(maybePromise._reason());rejected=true}}if(!(isPromise||this._zerothIsAccum))this._gotAccum=true;this._callback=fn;this._accum=accum;if(!rejected)async.invoke(init,this,undefined)}function init(){this._init$(undefined,-5)}util.inherits(ReductionPromiseArray,PromiseArray);ReductionPromiseArray.prototype._init=function(){};ReductionPromiseArray.prototype._resolveEmptyArray=function(){if(this._gotAccum||this._zerothIsAccum){this._resolve(this._preservedValues!==null?[]:this._accum)}};ReductionPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values;values[index]=value;var length=this.length();var preservedValues=this._preservedValues;var isEach=preservedValues!==null;var gotAccum=this._gotAccum;var valuesPhase=this._valuesPhase;var valuesPhaseIndex;if(!valuesPhase){valuesPhase=this._valuesPhase=new Array(length);for(valuesPhaseIndex=0;valuesPhaseIndex<length;++valuesPhaseIndex){valuesPhase[valuesPhaseIndex]=0}}valuesPhaseIndex=valuesPhase[index];if(index===0&&this._zerothIsAccum){this._accum=value;this._gotAccum=gotAccum=true;valuesPhase[index]=valuesPhaseIndex===0?1:2}else if(index===-1){this._accum=value;this._gotAccum=gotAccum=true}else{if(valuesPhaseIndex===0){valuesPhase[index]=1}else{valuesPhase[index]=2;this._accum=value}}if(!gotAccum)return;var callback=this._callback;var receiver=this._promise._boundTo;var ret;for(var i=this._reducingIndex;i<length;++i){valuesPhaseIndex=valuesPhase[i];if(valuesPhaseIndex===2){this._reducingIndex=i+1;continue}if(valuesPhaseIndex!==1)return;value=values[i];this._promise._pushContext();if(isEach){preservedValues.push(value);ret=tryCatch(callback).call(receiver,value,i,length)}else{ret=tryCatch(callback).call(receiver,this._accum,value,i,length)}this._promise._popContext();if(ret===errorObj)return this._reject(ret.e);var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();if(maybePromise._isPending()){valuesPhase[i]=4;return maybePromise._proxyPromiseArray(this,i)}else if(maybePromise._isFulfilled()){ret=maybePromise._value()}else{return this._reject(maybePromise._reason())}}this._reducingIndex=i+1;this._accum=ret}this._resolve(isEach?preservedValues:this._accum)};function reduce(promises,fn,initialValue,_each){if(typeof fn!=="function")return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n");var array=new ReductionPromiseArray(promises,fn,initialValue,_each);return array.promise()}Promise.prototype.reduce=function(fn,initialValue){return reduce(this,fn,initialValue,null)};Promise.reduce=function(promises,fn,initialValue,_each){return reduce(promises,fn,initialValue,_each)}}},{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){"use strict";var schedule;var noAsyncScheduler=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(_dereq_("./util.js").isNode){var version=process.versions.node.split(".").map(Number);schedule=version[0]===0&&version[1]>10||version[0]>0?function(fn){global.setImmediate(fn)}:process.nextTick;if(!schedule){if(typeof setImmediate!=="undefined"){schedule=setImmediate}else if(typeof setTimeout!=="undefined"){schedule=setTimeout}else{schedule=noAsyncScheduler}}}else if(typeof MutationObserver!=="undefined"){schedule=function(fn){var div=document.createElement("div");var observer=new MutationObserver(fn);observer.observe(div,{attributes:true});return function(){div.classList.toggle("foo")}};schedule.isStatic=true}else if(typeof setImmediate!=="undefined"){schedule=function(fn){setImmediate(fn)}}else if(typeof setTimeout!=="undefined"){schedule=function(fn){setTimeout(fn,0)}}else{schedule=noAsyncScheduler}module.exports=schedule},{"./util.js":38}],32:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray){var PromiseInspection=Promise.PromiseInspection;var util=_dereq_("./util.js");function SettledPromiseArray(values){this.constructor$(values)}util.inherits(SettledPromiseArray,PromiseArray);SettledPromiseArray.prototype._promiseResolved=function(index,inspection){this._values[index]=inspection;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values)}};SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;ret._bitField=268435456;ret._settledValue=value;this._promiseResolved(index,ret)};SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;ret._bitField=134217728;ret._settledValue=reason;this._promiseResolved(index,ret)};Promise.settle=function(promises){return new SettledPromiseArray(promises).promise()};Promise.prototype.settle=function(){return new SettledPromiseArray(this).promise()}}},{"./util.js":38}],33:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection){var util=_dereq_("./util.js");var RangeError=_dereq_("./errors.js").RangeError;var AggregateError=_dereq_("./errors.js").AggregateError;var isArray=util.isArray;function SomePromiseArray(values){this.constructor$(values);this._howMany=0;this._unwrap=false;this._initialized=false}util.inherits(SomePromiseArray,PromiseArray);SomePromiseArray.prototype._init=function(){if(!this._initialized){return}if(this._howMany===0){this._resolve([]);return}this._init$(undefined,-5);var isArrayResolved=isArray(this._values);if(!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()){this._reject(this._getRangeError(this.length()))}};SomePromiseArray.prototype.init=function(){this._initialized=true;this._init()};SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=true};SomePromiseArray.prototype.howMany=function(){return this._howMany};SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count};SomePromiseArray.prototype._promiseFulfilled=function(value){this._addFulfilled(value);if(this._fulfilled()===this.howMany()){this._values.length=this.howMany();if(this.howMany()===1&&this._unwrap){this._resolve(this._values[0])}else{this._resolve(this._values)}}};SomePromiseArray.prototype._promiseRejected=function(reason){this._addRejected(reason);if(this.howMany()>this._canPossiblyFulfill()){var e=new AggregateError;for(var i=this.length();i<this._values.length;++i){e.push(this._values[i])}this._reject(e)}};SomePromiseArray.prototype._fulfilled=function(){return this._totalResolved};SomePromiseArray.prototype._rejected=function(){return this._values.length-this.length()};SomePromiseArray.prototype._addRejected=function(reason){this._values.push(reason)};SomePromiseArray.prototype._addFulfilled=function(value){this._values[this._totalResolved++]=value};SomePromiseArray.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()};SomePromiseArray.prototype._getRangeError=function(count){var message="Input array must contain at least "+this._howMany+" items but contains only "+count+" items";return new RangeError(message)};SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))};function some(promises,howMany){if((howMany|0)!==howMany||howMany<0){return apiRejection("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n")}var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(howMany);ret.init();return promise}Promise.some=function(promises,howMany){return some(promises,howMany)};Promise.prototype.some=function(howMany){return some(this,howMany)};Promise._SomePromiseArray=SomePromiseArray}},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function PromiseInspection(promise){if(promise!==undefined){promise=promise._target();this._bitField=promise._bitField;this._settledValue=promise._settledValue}else{this._bitField=0;this._settledValue=undefined}}PromiseInspection.prototype.value=function(){if(!this.isFulfilled()){throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n")}return this._settledValue};PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(!this.isRejected()){throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n")}return this._settledValue};PromiseInspection.prototype.isFulfilled=Promise.prototype._isFulfilled=function(){return(this._bitField&268435456)>0};PromiseInspection.prototype.isRejected=Promise.prototype._isRejected=function(){return(this._bitField&134217728)>0};PromiseInspection.prototype.isPending=Promise.prototype._isPending=function(){return(this._bitField&402653184)===0};PromiseInspection.prototype.isResolved=Promise.prototype._isResolved=function(){return(this._bitField&402653184)>0};Promise.prototype.isPending=function(){return this._target()._isPending()};Promise.prototype.isRejected=function(){return this._target()._isRejected()};Promise.prototype.isFulfilled=function(){return this._target()._isFulfilled()};Promise.prototype.isResolved=function(){return this._target()._isResolved()};Promise.prototype._value=function(){return this._settledValue};Promise.prototype._reason=function(){this._unsetRejectionIsUnhandled();return this._settledValue};Promise.prototype.value=function(){var target=this._target();if(!target.isFulfilled()){throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n")}return target._settledValue};Promise.prototype.reason=function(){var target=this._target();if(!target.isRejected()){throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n")}target._unsetRejectionIsUnhandled();return target._settledValue};Promise.PromiseInspection=PromiseInspection}},{}],35:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var util=_dereq_("./util.js");var errorObj=util.errorObj;var isObject=util.isObject;function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise){return obj}else if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);obj._then(ret._fulfillUnchecked,ret._rejectUncheckedCheckError,ret._progressUnchecked,ret,null);return ret}var then=util.tryCatch(getThen)(obj);if(then===errorObj){if(context)context._pushContext();var ret=Promise.reject(then.e);if(context)context._popContext();return ret}else if(typeof then==="function"){return doThenable(obj,then,context)}}return obj}function getThen(obj){return obj.then}var hasProp={}.hasOwnProperty;function isAnyBluebirdPromise(obj){return hasProp.call(obj,"_promise0")}function doThenable(x,then,context){var promise=new Promise(INTERNAL);var ret=promise;if(context)context._pushContext();promise._captureStackTrace();if(context)context._popContext();var synchronous=true;var result=util.tryCatch(then).call(x,resolveFromThenable,rejectFromThenable,progressFromThenable);synchronous=false;if(promise&&result===errorObj){promise._rejectCallback(result.e,true,true);promise=null}function resolveFromThenable(value){if(!promise)return;if(x===value){promise._rejectCallback(Promise._makeSelfResolutionError(),false,true)}else{promise._resolveCallback(value)}promise=null}function rejectFromThenable(reason){if(!promise)return;promise._rejectCallback(reason,synchronous,true);promise=null}function progressFromThenable(value){if(!promise)return;if(typeof promise._progress==="function"){promise._progress(value)}}return ret}return tryConvertToPromise}},{"./util.js":38}],36:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var util=_dereq_("./util.js");var TimeoutError=Promise.TimeoutError;var afterTimeout=function(promise,message){if(!promise.isPending())return;if(typeof message!=="string"){message="operation timed out"}var err=new TimeoutError(message);util.markAsOriginatingFromRejection(err);promise._attachExtraTrace(err);promise._cancel(err)};var afterValue=function(value){return delay(+this).thenReturn(value)};var delay=Promise.delay=function(value,ms){if(ms===undefined){ms=value;value=undefined;var ret=new Promise(INTERNAL);setTimeout(function(){ret._fulfill()},ms);return ret}ms=+ms;return Promise.resolve(value)._then(afterValue,null,null,ms,undefined)};Promise.prototype.delay=function(ms){return delay(this,ms)};function successClear(value){var handle=this;if(handle instanceof Number)handle=+handle;clearTimeout(handle);return value}function failureClear(reason){var handle=this;if(handle instanceof Number)handle=+handle;clearTimeout(handle);throw reason}Promise.prototype.timeout=function(ms,message){ms=+ms;var ret=this.then().cancellable();ret._cancellationParent=this;var handle=setTimeout(function timeoutTimeout(){afterTimeout(ret,message)},ms);return ret._then(successClear,failureClear,undefined,handle,undefined)}}},{"./util.js":38}],37:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext){var TypeError=_dereq_("./errors.js").TypeError;var inherits=_dereq_("./util.js").inherits;var PromiseInspection=Promise.PromiseInspection;function inspectionMapper(inspections){var len=inspections.length;for(var i=0;i<len;++i){var inspection=inspections[i];if(inspection.isRejected()){return Promise.reject(inspection.error())}inspections[i]=inspection._settledValue}return inspections}function thrower(e){setTimeout(function(){throw e},0)}function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);if(maybePromise!==thenable&&typeof thenable._isDisposable==="function"&&typeof thenable._getDisposer==="function"&&thenable._isDisposable()){maybePromise._setDisposable(thenable._getDisposer())}return maybePromise}function dispose(resources,inspection){var i=0;var len=resources.length;var ret=Promise.defer();function iterator(){if(i>=len)return ret.resolve();var maybePromise=castPreservingDisposable(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise)}catch(e){return thrower(e)}if(maybePromise instanceof Promise){return maybePromise._then(iterator,thrower,null,null,null)}}iterator()}iterator();return ret.promise}function disposerSuccess(value){var inspection=new PromiseInspection;inspection._settledValue=value;inspection._bitField=268435456;return dispose(this,inspection).thenReturn(value)}function disposerFail(reason){var inspection=new PromiseInspection;inspection._settledValue=reason;inspection._bitField=134217728;return dispose(this,inspection).thenThrow(reason)}function Disposer(data,promise,context){this._data=data;this._promise=promise;this._context=context}Disposer.prototype.data=function(){return this._data};Disposer.prototype.promise=function(){return this._promise};Disposer.prototype.resource=function(){if(this.promise().isFulfilled()){return this.promise().value()}return null};Disposer.prototype.tryDispose=function(inspection){var resource=this.resource();var context=this._context;if(context!==undefined)context._pushContext();var ret=resource!==null?this.doDispose(resource,inspection):null;if(context!==undefined)context._popContext();this._promise._unsetDisposable();this._data=null;return ret};Disposer.isDisposer=function(d){return d!=null&&typeof d.resource==="function"&&typeof d.tryDispose==="function"};function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}inherits(FunctionDisposer,Disposer);FunctionDisposer.prototype.doDispose=function(resource,inspection){var fn=this.data();return fn.call(resource,resource,inspection)};function maybeUnwrapDisposer(value){if(Disposer.isDisposer(value)){this.resources[this.index]._setDisposable(value);return value.promise()}return value}Promise.using=function(){var len=arguments.length;if(len<2)return apiRejection("you must pass at least 2 arguments to Promise.using");var fn=arguments[len-1];if(typeof fn!=="function")return apiRejection("fn must be a function\n\n See http://goo.gl/916lJJ\n");len--;var resources=new Array(len);for(var i=0;i<len;++i){var resource=arguments[i];if(Disposer.isDisposer(resource)){var disposer=resource;resource=resource.promise();resource._setDisposable(disposer)}else{var maybePromise=tryConvertToPromise(resource);if(maybePromise instanceof Promise){resource=maybePromise._then(maybeUnwrapDisposer,null,null,{resources:resources,index:i},undefined)}}resources[i]=resource}var promise=Promise.settle(resources).then(inspectionMapper).then(function(vals){promise._pushContext();var ret;try{ret=fn.apply(undefined,vals)}finally{promise._popContext()}return ret})._then(disposerSuccess,disposerFail,undefined,resources,undefined);resources.promise=promise;return promise};Promise.prototype._setDisposable=function(disposer){this._bitField=this._bitField|262144;this._disposer=disposer};Promise.prototype._isDisposable=function(){return(this._bitField&262144)>0};Promise.prototype._getDisposer=function(){return this._disposer};Promise.prototype._unsetDisposable=function(){this._bitField=this._bitField&~262144;
this._disposer=undefined};Promise.prototype.disposer=function(fn){if(typeof fn==="function"){return new FunctionDisposer(fn,this,createContext())}throw new TypeError}}},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5.js");var canEvaluate=typeof navigator=="undefined";var haveGetters=function(){try{var o={};es5.defineProperty(o,"f",{get:function(){return 3}});return o.f===3}catch(e){return false}}();var errorObj={e:{}};var tryCatchTarget;function tryCatcher(){try{return tryCatchTarget.apply(this,arguments)}catch(e){errorObj.e=e;return errorObj}}function tryCatch(fn){tryCatchTarget=fn;return tryCatcher}var inherits=function(Child,Parent){var hasProp={}.hasOwnProperty;function T(){this.constructor=Child;this.constructor$=Parent;for(var propertyName in Parent.prototype){if(hasProp.call(Parent.prototype,propertyName)&&propertyName.charAt(propertyName.length-1)!=="$"){this[propertyName+"$"]=Parent.prototype[propertyName]}}}T.prototype=Parent.prototype;Child.prototype=new T;return Child.prototype};function isPrimitive(val){return val==null||val===true||val===false||typeof val==="string"||typeof val==="number"}function isObject(value){return!isPrimitive(value)}function maybeWrapAsError(maybeError){if(!isPrimitive(maybeError))return maybeError;return new Error(safeToString(maybeError))}function withAppended(target,appendee){var len=target.length;var ret=new Array(len+1);var i;for(i=0;i<len;++i){ret[i]=target[i]}ret[i]=appendee;return ret}function getDataPropertyOrDefault(obj,key,defaultValue){if(es5.isES5){var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null){return desc.get==null&&desc.set==null?desc.value:defaultValue}}else{return{}.hasOwnProperty.call(obj,key)?obj[key]:undefined}}function notEnumerableProp(obj,name,value){if(isPrimitive(obj))return obj;var descriptor={value:value,configurable:true,enumerable:false,writable:true};es5.defineProperty(obj,name,descriptor);return obj}var wrapsPrimitiveReceiver=function(){return this!=="string"}.call("string");function thrower(r){throw r}var inheritedDataKeys=function(){if(es5.isES5){var oProto=Object.prototype;var getKeys=Object.getOwnPropertyNames;return function(obj){var ret=[];var visitedKeys=Object.create(null);while(obj!=null&&obj!==oProto){var keys;try{keys=getKeys(obj)}catch(e){return ret}for(var i=0;i<keys.length;++i){var key=keys[i];if(visitedKeys[key])continue;visitedKeys[key]=true;var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null&&desc.get==null&&desc.set==null){ret.push(key)}}obj=es5.getPrototypeOf(obj)}return ret}}else{return function(obj){var ret=[];for(var key in obj){ret.push(key)}return ret}}}();function isClass(fn){try{if(typeof fn==="function"){var keys=es5.names(fn.prototype);if(es5.isES5)return keys.length>1;return keys.length>0&&!(keys.length===1&&keys[0]==="constructor")}return false}catch(e){return false}}function toFastProperties(obj){function f(){}f.prototype=obj;var l=8;while(l--)new f;return obj;eval(obj)}var rident=/^[a-z$_][a-z$_0-9]*$/i;function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){var ret=new Array(count);for(var i=0;i<count;++i){ret[i]=prefix+i+suffix}return ret}function safeToString(obj){try{return obj+""}catch(e){return"[no string representation]"}}function markAsOriginatingFromRejection(e){try{notEnumerableProp(e,"isOperational",true)}catch(ignore){}}function originatesFromRejection(e){if(e==null)return false;return e instanceof Error["__BluebirdErrorTypes__"].OperationalError||e["isOperational"]===true}function canAttachTrace(obj){return obj instanceof Error&&es5.propertyIsWritable(obj,"stack")}var ensureErrorObject=function(){if(!("stack"in new Error)){return function(value){if(canAttachTrace(value))return value;try{throw new Error(safeToString(value))}catch(err){return err}}}else{return function(value){if(canAttachTrace(value))return value;return new Error(safeToString(value))}}}();function classString(obj){return{}.toString.call(obj)}function copyDescriptors(from,to,filter){var keys=es5.names(from);for(var i=0;i<keys.length;++i){var key=keys[i];if(filter(key)){es5.defineProperty(to,key,es5.getDescriptor(from,key))}}}var ret={isClass:isClass,isIdentifier:isIdentifier,inheritedDataKeys:inheritedDataKeys,getDataPropertyOrDefault:getDataPropertyOrDefault,thrower:thrower,isArray:es5.isArray,haveGetters:haveGetters,notEnumerableProp:notEnumerableProp,isPrimitive:isPrimitive,isObject:isObject,canEvaluate:canEvaluate,errorObj:errorObj,tryCatch:tryCatch,inherits:inherits,withAppended:withAppended,maybeWrapAsError:maybeWrapAsError,wrapsPrimitiveReceiver:wrapsPrimitiveReceiver,toFastProperties:toFastProperties,filledRange:filledRange,toString:safeToString,canAttachTrace:canAttachTrace,ensureErrorObject:ensureErrorObject,originatesFromRejection:originatesFromRejection,markAsOriginatingFromRejection:markAsOriginatingFromRejection,classString:classString,copyDescriptors:copyDescriptors,hasDevTools:typeof chrome!=="undefined"&&chrome&&typeof chrome.loadTimes==="function",isNode:typeof process!=="undefined"&&classString(process).toLowerCase()==="[object process]"};try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5.js":14}],39:[function(_dereq_,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}throw TypeError('Uncaught, unspecified "error" event.')}}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}},{}]},{},[4])(4)});if(typeof window!=="undefined"&&window!==null){window.P=window.Promise}else if(typeof self!=="undefined"&&self!==null){self.P=self.Promise}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:96}],81:[function(require,module,exports){exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:localstorage();exports.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function useColors(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){exports.storage.removeItem("debug")}else{exports.storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}},{"./debug":82}],82:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false}}for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true}}return false}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:85}],83:[function(require,module,exports){module.exports=exports=require("./lib/sliced")},{"./lib/sliced":84}],84:[function(require,module,exports){module.exports=function(args,slice,sliceEnd){var ret=[];var len=args.length;if(0===len)return ret;var start=slice<0?Math.max(0,slice+len):slice||0;if(sliceEnd!==undefined){len=sliceEnd<0?sliceEnd+len:sliceEnd}while(len-->start){ret[len-start]=args[len]}return ret}},{}],85:[function(require,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){str=""+str;if(str.length>1e4)return;var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],86:[function(require,module,exports){var toString=Object.prototype.toString;function isRegExp(o){return"object"==typeof o&&"[object RegExp]"==toString.call(o)}module.exports=exports=function(regexp){if(!isRegExp(regexp)){throw new TypeError("Not a RegExp")}var flags=[];if(regexp.global)flags.push("g");if(regexp.multiline)flags.push("m");if(regexp.ignoreCase)flags.push("i");return new RegExp(regexp.source,flags.join(""))}},{}],87:[function(require,module,exports){module.exports=require(84)},{}],88:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&(isNaN(value)||!isFinite(value))){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(isArguments(a)){if(!isArguments(b)){return false}a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}try{var ka=objectKeys(a),kb=objectKeys(b),key,i}catch(e){return false}if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":90}],89:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],90:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":89,_process:96,inherits:95}],91:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new Error("First argument needs to be a number, array or string.");var buf;if(TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){
buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.byteLength=function(str,encoding){var ret;str=str.toString();switch(encoding||"utf8"){case"hex":ret=str.length/2;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"ascii":case"binary":case"raw":ret=str.length;break;case"base64":ret=base64ToBytes(str).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;default:throw new Error("Unknown encoding")}return ret};Buffer.concat=function(list,totalLength){assert(isArray(list),"Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.compare=function(a,b){assert(Buffer.isBuffer(a)&&Buffer.isBuffer(b),"Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y){return-1}if(y<x){return 1}return 0};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;assert(strLen%2===0,"Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);assert(!isNaN(byte),"Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toString=function(encoding,start,end){var self=this;encoding=String(encoding||"utf8").toLowerCase();start=Number(start)||0;end=end===undefined?self.length:Number(end);if(end===start)return"";var ret;switch(encoding){case"hex":ret=hexSlice(self,start,end);break;case"utf8":case"utf-8":ret=utf8Slice(self,start,end);break;case"ascii":ret=asciiSlice(self,start,end);break;case"binary":ret=binarySlice(self,start,end);break;case"base64":ret=base64Slice(self,start,end);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leSlice(self,start,end);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.equals=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.compare=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;assert(end>=start,"sourceEnd < sourceStart");assert(target_start>=0&&target_start<target.length,"targetStart out of bounds");assert(start>=0&&start<source.length,"sourceStart out of bounds");assert(end>=0&&end<=source.length,"sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<100||!TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;return this[offset]};function readUInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){val=buf[offset];if(offset+1<len)val|=buf[offset+1]<<8}else{val=buf[offset]<<8;if(offset+1<len)val|=buf[offset+1]}return val}Buffer.prototype.readUInt16LE=function(offset,noAssert){return readUInt16(this,offset,true,noAssert)};Buffer.prototype.readUInt16BE=function(offset,noAssert){return readUInt16(this,offset,false,noAssert)};function readUInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){if(offset+2<len)val=buf[offset+2]<<16;if(offset+1<len)val|=buf[offset+1]<<8;val|=buf[offset];if(offset+3<len)val=val+(buf[offset+3]<<24>>>0)}else{if(offset+1<len)val=buf[offset+1]<<16;if(offset+2<len)val|=buf[offset+2]<<8;if(offset+3<len)val|=buf[offset+3];val=val+(buf[offset]<<24>>>0)}return val}Buffer.prototype.readUInt32LE=function(offset,noAssert){return readUInt32(this,offset,true,noAssert)};Buffer.prototype.readUInt32BE=function(offset,noAssert){return readUInt32(this,offset,false,noAssert)};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;var neg=this[offset]&128;if(neg)return(255-this[offset]+1)*-1;else return this[offset]};function readInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt16(buf,offset,littleEndian,true);var neg=val&32768;if(neg)return(65535-val+1)*-1;else return val}Buffer.prototype.readInt16LE=function(offset,noAssert){return readInt16(this,offset,true,noAssert)};Buffer.prototype.readInt16BE=function(offset,noAssert){return readInt16(this,offset,false,noAssert)};function readInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt32(buf,offset,littleEndian,true);var neg=val&2147483648;if(neg)return(4294967295-val+1)*-1;else return val}Buffer.prototype.readInt32LE=function(offset,noAssert){return readInt32(this,offset,true,noAssert)};Buffer.prototype.readInt32BE=function(offset,noAssert){return readInt32(this,offset,false,noAssert)};function readFloat(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+3<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,23,4)}Buffer.prototype.readFloatLE=function(offset,noAssert){return readFloat(this,offset,true,noAssert)};Buffer.prototype.readFloatBE=function(offset,noAssert){return readFloat(this,offset,false,noAssert)};function readDouble(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+7<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,52,8)}Buffer.prototype.readDoubleLE=function(offset,noAssert){return readDouble(this,offset,true,noAssert)};Buffer.prototype.readDoubleBE=function(offset,noAssert){return readDouble(this,offset,false,noAssert)};Buffer.prototype.writeUInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"trying to write beyond buffer length");verifuint(value,255)}if(offset>=this.length)return;this[offset]=value;return offset+1};function writeUInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"trying to write beyond buffer length");verifuint(value,65535)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}return offset+2}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return writeUInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return writeUInt16(this,value,offset,false,noAssert)};function writeUInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"trying to write beyond buffer length");verifuint(value,4294967295)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}return offset+4}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return writeUInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return writeUInt32(this,value,offset,false,noAssert)};Buffer.prototype.writeInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to write beyond buffer length");verifsint(value,127,-128)}if(offset>=this.length)return;if(value>=0)this.writeUInt8(value,offset,noAssert);else this.writeUInt8(255+value+1,offset,noAssert);return offset+1};function writeInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to write beyond buffer length");verifsint(value,32767,-32768)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt16(buf,value,offset,littleEndian,noAssert);else writeUInt16(buf,65535+value+1,offset,littleEndian,noAssert);return offset+2}Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return writeInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return writeInt16(this,value,offset,false,noAssert)};function writeInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifsint(value,2147483647,-2147483648)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt32(buf,value,offset,littleEndian,noAssert);else writeUInt32(buf,4294967295+value+1,offset,littleEndian,noAssert);return offset+4}Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return writeInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return writeInt32(this,value,offset,false,noAssert)};function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,3.4028234663852886e38,-3.4028234663852886e38)}var len=buf.length;if(offset>=len)return;ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+7<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,1.7976931348623157e308,-1.7976931348623157e308)}var len=buf.length;if(offset>=len)return;ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;assert(end>=start,"end < start");if(end===start)return;if(this.length===0)return;assert(start>=0&&start<this.length,"start out of bounds");assert(end>=0&&end<=this.length,"end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.inspect=function(){var out=[];var len=this.length;for(var i=0;i<len;i++){out[i]=toHex(this[i]);if(i===exports.INSPECT_MAX_BYTES){out[i+1]="...";break}}return"<Buffer "+out.join(" ")+">"};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new Error("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArray(subject){return(Array.isArray||function(subject){return Object.prototype.toString.call(subject)==="[object Array]"})(subject)}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}function verifuint(value,max){assert(typeof value==="number","cannot write a non-number as a number");assert(value>=0,"specified a negative value for writing an unsigned value");assert(value<=max,"value is larger than maximum value for type");assert(Math.floor(value)===value,"value has a fractional component")}function verifsint(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value");assert(Math.floor(value)===value,"value has a fractional component")}function verifIEEE754(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value")}function assert(test,message){if(!test)throw new Error(message||"Failed assertion")}},{"base64-js":92,ieee754:93}],92:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],93:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],94:[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}},{}],95:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],96:[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")}},{}],97:[function(require,module,exports){module.exports=require(89)},{}],98:[function(require,module,exports){module.exports=require(90)},{"./support/isBuffer":97,_process:96,inherits:95}],mongoose:[function(require,module,exports){(function(Buffer){exports.Error=require("./error");exports.Schema=require("./schema");exports.Types=require("./types");exports.VirtualType=require("./virtualtype");exports.SchemaType=require("./schematype.js");exports.utils=require("./utils.js");exports.Document=require("./document_provider.js")();if(typeof window!=="undefined"){window.mongoose=module.exports;window.Buffer=Buffer;
}}).call(this,require("buffer").Buffer)},{"./document_provider.js":5,"./error":11,"./schema":25,"./schematype.js":38,"./types":44,"./utils.js":47,"./virtualtype":48,buffer:91}]},{},[]);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){(function(global){(function(){var undefined;var VERSION="4.0.0";var BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512;var UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2;var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...";var HOT_COUNT=150,HOT_SPAN=16;var LARGE_ARRAY_SIZE=200;var LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3;var FUNC_ERROR_TEXT="Expected a function";var HASH_UNDEFINED="__lodash_hash_undefined__";var INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=0/0;var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;var PLACEHOLDER="__lodash_placeholder__";var argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]";var arrayBufferTag="[object ArrayBuffer]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);var reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/;var reEscapeChar=/\\(\\)?/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reHasHexPrefix=/^0x/i;var reIsBadHex=/^[-+]0x[0-9a-f]+$/i;var reIsBinary=/^0b[01]+$/i;var reIsHostCtor=/^\[object .+?Constructor\]$/;var reIsOctal=/^0o[0-7]+$/i;var reIsUint=/^(?:0|[1-9]\d*)$/;var reLatin1=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;var reNoMatch=/($^)/;var reUnescapedString=/['\n\r\u2028\u2029\\]/g;var rsAstralRange="\\ud800-\\udfff",rsComboRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsQuoteRange="\\u2018\\u2019\\u201c\\u201d",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsQuoteRange+rsSpaceRange;var rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsModifier="(?:\\ud83c[\\udffb-\\udfff])",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d";var rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")";var reComboMark=RegExp(rsCombo,"g");var reComplexSymbol=RegExp(rsSymbol+rsSeq,"g");var reHasComplexSymbol=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");var reBasicWord=/[a-zA-Z0-9]+/g;var reComplexWord=RegExp([rsUpper+"?"+rsLower+"+(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+",rsDigits+"(?:"+rsLowerMisc+"+)?",rsEmoji].join("|"),"g");var reHasComplexWord=/[a-z][A-Z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;var contextProps=["Array","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Reflect","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"];var templateCounter=-1;var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=false;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss"};var htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","`":"&#96;"};var htmlUnescapes={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&#96;":"`"};var objectTypes={"function":true,object:true};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"};var freeParseFloat=parseFloat,freeParseInt=parseInt;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType?exports:null;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType?module:null;var freeGlobal=checkGlobal(freeExports&&freeModule&&typeof global=="object"&&global);var freeSelf=checkGlobal(objectTypes[typeof self]&&self);var freeWindow=checkGlobal(objectTypes[typeof window]&&window);var moduleExports=freeModule&&freeModule.exports===freeExports?freeExports:null;var thisGlobal=checkGlobal(objectTypes[typeof this]&&this);var root=freeGlobal||freeWindow!==(thisGlobal&&thisGlobal.window)&&freeWindow||freeSelf||thisGlobal||Function("return this")();function addMapEntry(map,pair){map.set(pair[0],pair[1]);return map}function addSetEntry(set,value){set.add(value);return set}function apply(func,thisArg,args){var length=args?args.length:0;switch(length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayConcat(array,other){var index=-1,length=array.length,othIndex=-1,othLength=other.length,result=Array(length+othLength);while(++index<length){result[index]=array[index]}while(++othIndex<othLength){result[index++]=other[othIndex]}return result}function arrayEach(array,iteratee){var index=-1,length=array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break}}return array}function arrayEachRight(array,iteratee){var length=array.length;while(length--){if(iteratee(array[length],length,array)===false){break}}return array}function arrayEvery(array,predicate){var index=-1,length=array.length;while(++index<length){if(!predicate(array[index],index,array)){return false}}return true}function arrayFilter(array,predicate){var index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[++resIndex]=value}}return result}function arrayIncludes(array,value){return!!array.length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){var index=-1,length=array.length;while(++index<length){if(comparator(value,array[index])){return true}}return false}function arrayMap(array,iteratee){var index=-1,length=array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array)}return result}function arrayPush(array,values){var index=-1,length=values.length,offset=array.length;while(++index<length){array[offset+index]=values[index]}return array}function arrayReduce(array,iteratee,accumulator,initFromArray){var index=-1,length=array.length;if(initFromArray&&length){accumulator=array[++index]}while(++index<length){accumulator=iteratee(accumulator,array[index],index,array)}return accumulator}function arrayReduceRight(array,iteratee,accumulator,initFromArray){var length=array.length;if(initFromArray&&length){accumulator=array[--length]}while(length--){accumulator=iteratee(accumulator,array[length],length,array)}return accumulator}function arraySome(array,predicate){var index=-1,length=array.length;while(++index<length){if(predicate(array[index],index,array)){return true}}return false}function baseExtremum(array,iteratee,comparator){var index=-1,length=array.length;while(++index<length){var value=array[index],current=iteratee(value);if(current!=null&&(computed===undefined?current===current:comparator(current,computed))){var computed=current,result=value}}return result}function baseFind(collection,predicate,eachFunc,retKey){var result;eachFunc(collection,function(value,key,collection){if(predicate(value,key,collection)){result=retKey?key:value;return false}});return result}function baseFindIndex(array,predicate,fromRight){var length=array.length,index=fromRight?length:-1;while(fromRight?index--:++index<length){if(predicate(array[index],index,array)){return index}}return-1}function baseIndexOf(array,value,fromIndex){if(value!==value){return indexOfNaN(array,fromIndex)}var index=fromIndex-1,length=array.length;while(++index<length){if(array[index]===value){return index}}return-1}function baseReduce(collection,iteratee,accumulator,initFromCollection,eachFunc){eachFunc(collection,function(value,index,collection){accumulator=initFromCollection?(initFromCollection=false,value):iteratee(accumulator,value,index,collection)});return accumulator}function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value}return array}function baseSum(array,iteratee){var result,index=-1,length=array.length;while(++index<length){var current=iteratee(array[index]);if(current!==undefined){result=result===undefined?current:result+current}}return result}function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index<n){result[index]=iteratee(index)}return result}function baseToPairs(object,props){return arrayMap(props,function(key){return[key,object[key]]})}function baseUnary(func){return function(value){return func(value)}}function baseValues(object,props){return arrayMap(props,function(key){return object[key]})}function charsStartIndex(strSymbols,chrSymbols){var index=-1,length=strSymbols.length;while(++index<length&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index}function charsEndIndex(strSymbols,chrSymbols){var index=strSymbols.length;while(index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index}function checkGlobal(value){return value&&value.Object===Object?value:null}function compareAscending(value,other){if(value!==other){var valIsNull=value===null,valIsUndef=value===undefined,valIsReflexive=value===value;var othIsNull=other===null,othIsUndef=other===undefined,othIsReflexive=other===other;if(value>other&&!othIsNull||!valIsReflexive||valIsNull&&!othIsUndef&&othIsReflexive||valIsUndef&&othIsReflexive){return 1}if(value<other&&!valIsNull||!othIsReflexive||othIsNull&&!valIsUndef&&valIsReflexive||othIsUndef&&valIsReflexive){return-1}}return 0}function compareMultiple(object,other,orders){var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;while(++index<length){var result=compareAscending(objCriteria[index],othCriteria[index]);if(result){if(index>=ordersLength){return result}var order=orders[index];return result*(order=="desc"?-1:1)}}return object.index-other.index}function deburrLetter(letter){return deburredLetters[letter]}function escapeHtmlChar(chr){return htmlEscapes[chr]}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function indexOfNaN(array,fromIndex,fromRight){var length=array.length,index=fromIndex+(fromRight?0:-1);while(fromRight?index--:++index<length){var other=array[index];if(other!==other){return index}}return-1}function isHostObject(value){var result=false;if(value!=null&&typeof value.toString!="function"){try{result=!!(value+"")}catch(e){}}return result}function isIndex(value,length){value=typeof value=="number"||reIsUint.test(value)?+value:-1;length=length==null?MAX_SAFE_INTEGER:length;return value>-1&&value%1==0&&value<length}function iteratorToArray(iterator){var data,result=[];while(!(data=iterator.next()).done){result.push(data.value)}return result}function mapToArray(map){var index=-1,result=Array(map.size);map.forEach(function(value,key){result[++index]=[key,value]});return result}function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){if(array[index]===placeholder){array[index]=PLACEHOLDER;result[++resIndex]=index}}return result}function setToArray(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=value});return result}function stringSize(string){if(!(string&&reHasComplexSymbol.test(string))){return string.length}var result=reComplexSymbol.lastIndex=0;while(reComplexSymbol.test(string)){result++}return result}function stringToArray(string){return string.match(reComplexSymbol)}function unescapeHtmlChar(chr){return htmlUnescapes[chr]}function runInContext(context){context=context?_.defaults({},context,_.pick(root,contextProps)):root;var Date=context.Date,Error=context.Error,Math=context.Math,RegExp=context.RegExp,TypeError=context.TypeError;var arrayProto=context.Array.prototype,objectProto=context.Object.prototype;var funcToString=context.Function.prototype.toString;var hasOwnProperty=objectProto.hasOwnProperty;var idCounter=0;var objectCtorString=funcToString.call(Object);var objectToString=objectProto.toString;var oldDash=root._;var reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var _Symbol=context.Symbol,Reflect=context.Reflect,Uint8Array=context.Uint8Array,clearTimeout=context.clearTimeout,enumerate=Reflect?Reflect.enumerate:undefined,getPrototypeOf=Object.getPrototypeOf,getOwnPropertySymbols=Object.getOwnPropertySymbols,iteratorSymbol=typeof(iteratorSymbol=_Symbol&&_Symbol.iterator)=="symbol"?iteratorSymbol:undefined,propertyIsEnumerable=objectProto.propertyIsEnumerable,setTimeout=context.setTimeout,splice=arrayProto.splice;var nativeCeil=Math.ceil,nativeFloor=Math.floor,nativeIsFinite=context.isFinite,nativeJoin=arrayProto.join,nativeKeys=Object.keys,nativeMax=Math.max,nativeMin=Math.min,nativeParseInt=context.parseInt,nativeRandom=Math.random,nativeReverse=arrayProto.reverse;var Map=getNative(context,"Map"),Set=getNative(context,"Set"),WeakMap=getNative(context,"WeakMap"),nativeCreate=getNative(Object,"create");var metaMap=WeakMap&&new WeakMap;var mapCtorString=Map?funcToString.call(Map):"",setCtorString=Set?funcToString.call(Set):"";var symbolProto=_Symbol?_Symbol.prototype:undefined,symbolValueOf=_Symbol?symbolProto.valueOf:undefined,symbolToString=_Symbol?symbolProto.toString:undefined;var realNames={};function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper){return value}if(hasOwnProperty.call(value,"__wrapped__")){return wrapperClone(value)}}return new LodashWrapper(value)}function baseLodash(){}function LodashWrapper(value,chainAll){this.__wrapped__=value;this.__actions__=[];this.__chain__=!!chainAll;this.__index__=0;this.__values__=undefined}lodash.templateSettings={escape:reEscape,evaluate:reEvaluate,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function LazyWrapper(value){this.__wrapped__=value;this.__actions__=[];this.__dir__=1;this.__filtered__=false;this.__iteratees__=[];this.__takeCount__=MAX_ARRAY_LENGTH;this.__views__=[]}function lazyClone(){var result=new LazyWrapper(this.__wrapped__);result.__actions__=copyArray(this.__actions__);result.__dir__=this.__dir__;result.__filtered__=this.__filtered__;result.__iteratees__=copyArray(this.__iteratees__);result.__takeCount__=this.__takeCount__;result.__views__=copyArray(this.__views__);return result}function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1;result.__filtered__=true}else{result=this.clone();result.__dir__*=-1}return result}function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=dir<0,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||arrLength<LARGE_ARRAY_SIZE||arrLength==length&&takeCount==length){return baseWrapperValue(array,this.__actions__)}var result=[];outer:while(length--&&resIndex<takeCount){index+=dir;var iterIndex=-1,value=array[index];while(++iterIndex<iterLength){var data=iteratees[iterIndex],iteratee=data.iteratee,type=data.type,computed=iteratee(value);if(type==LAZY_MAP_FLAG){value=computed}else if(!computed){if(type==LAZY_FILTER_FLAG){continue outer}else{break outer}}}result[resIndex++]=value}return result}function Hash(){}function hashDelete(hash,key){return hashHas(hash,key)&&delete hash[key]}function hashGet(hash,key){if(nativeCreate){var result=hash[key];return result===HASH_UNDEFINED?undefined:result}return hasOwnProperty.call(hash,key)?hash[key]:undefined}function hashHas(hash,key){return nativeCreate?hash[key]!==undefined:hasOwnProperty.call(hash,key)}function hashSet(hash,key,value){hash[key]=nativeCreate&&value===undefined?HASH_UNDEFINED:value}function MapCache(values){var index=-1,length=values?values.length:0;this.clear();while(++index<length){var entry=values[index];this.set(entry[0],entry[1])}}function mapClear(){this.__data__={hash:new Hash,map:Map?new Map:[],string:new Hash}}function mapDelete(key){var data=this.__data__;if(isKeyable(key)){return hashDelete(typeof key=="string"?data.string:data.hash,key)}return Map?data.map["delete"](key):assocDelete(data.map,key)}function mapGet(key){var data=this.__data__;if(isKeyable(key)){return hashGet(typeof key=="string"?data.string:data.hash,key)}return Map?data.map.get(key):assocGet(data.map,key)}function mapHas(key){var data=this.__data__;if(isKeyable(key)){return hashHas(typeof key=="string"?data.string:data.hash,key)}return Map?data.map.has(key):assocHas(data.map,key)}function mapSet(key,value){var data=this.__data__;if(isKeyable(key)){hashSet(typeof key=="string"?data.string:data.hash,key,value)}else if(Map){data.map.set(key,value)}else{assocSet(data.map,key,value)}return this}function SetCache(values){var index=-1,length=values?values.length:0;this.__data__=new MapCache;while(++index<length){this.push(values[index])}}function cacheHas(cache,value){var map=cache.__data__;if(isKeyable(value)){var data=map.__data__,hash=typeof value=="string"?data.string:data.hash;return hash[value]===HASH_UNDEFINED}return map.has(value)}function cachePush(value){var map=this.__data__;if(isKeyable(value)){var data=map.__data__,hash=typeof value=="string"?data.string:data.hash;hash[value]=HASH_UNDEFINED}else{map.set(value,HASH_UNDEFINED)}}function Stack(values){var index=-1,length=values?values.length:0;this.clear();while(++index<length){var entry=values[index];this.set(entry[0],entry[1])}}function stackClear(){this.__data__={array:[],map:null}}function stackDelete(key){var data=this.__data__,array=data.array;return array?assocDelete(array,key):data.map["delete"](key)}function stackGet(key){var data=this.__data__,array=data.array;return array?assocGet(array,key):data.map.get(key)}function stackHas(key){var data=this.__data__,array=data.array;return array?assocHas(array,key):data.map.has(key)}function stackSet(key,value){var data=this.__data__,array=data.array;if(array){if(array.length<LARGE_ARRAY_SIZE-1){assocSet(array,key,value)}else{data.array=null;data.map=new MapCache(array)}}var map=data.map;if(map){map.set(key,value)}return this}function assocDelete(array,key){var index=assocIndexOf(array,key);if(index<0){return false}var lastIndex=array.length-1;if(index==lastIndex){array.pop()}else{splice.call(array,index,1)}return true}function assocGet(array,key){var index=assocIndexOf(array,key);return index<0?undefined:array[index][1]}function assocHas(array,key){return assocIndexOf(array,key)>-1}function assocIndexOf(array,key){var length=array.length;while(length--){if(eq(array[length][0],key)){return length}}return-1}function assocSet(array,key,value){var index=assocIndexOf(array,key);if(index<0){array.push([key,value])}else{array[index][1]=value}}function assignInDefaults(objValue,srcValue,key,object){if(objValue===undefined||eq(objValue,objectProto[key])&&!hasOwnProperty.call(object,key)){return srcValue}return objValue}function assignMergeValue(object,key,value){if(value!==undefined&&!eq(object[key],value)||typeof key=="number"&&value===undefined&&!(key in object)){object[key]=value}}function assignValue(object,key,value){var objValue=object[key];if(!eq(objValue,value)||eq(objValue,objectProto[key])&&!hasOwnProperty.call(object,key)||value===undefined&&!(key in object)){object[key]=value}}function baseAssign(object,source){return object&&copyObject(source,keys(source),object)}function baseAt(object,paths){var index=-1,isNil=object==null,length=paths.length,result=Array(length);while(++index<length){result[index]=isNil?undefined:get(object,paths[index])}return result}function baseClamp(number,lower,upper){if(number===number){if(upper!==undefined){number=number<=upper?number:upper}if(lower!==undefined){number=number>=lower?number:lower}}return number}function baseClone(value,isDeep,customizer,key,object,stack){var result;if(customizer){result=object?customizer(value,key,object,stack):customizer(value)}if(result!==undefined){return result}if(!isObject(value)){return value}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return copyArray(value,result)}}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(tag==objectTag||tag==argsTag||isFunc&&!object){if(isHostObject(value)){return object?value:{}}result=initCloneObject(isFunc?{}:value);if(!isDeep){return copySymbols(value,baseAssign(result,value))}}else{return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{}}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked){return stacked}stack.set(value,result);(isArr?arrayEach:baseForOwn)(value,function(subValue,key){assignValue(result,key,baseClone(subValue,isDeep,customizer,key,value,stack))});return isArr?result:copySymbols(value,result)}function baseConforms(source){var props=keys(source),length=props.length;return function(object){if(object==null){return!length}var index=length;while(index--){var key=props[index],predicate=source[key],value=object[key];if(value===undefined&&!(key in Object(object))||!predicate(value)){return false}}return true}}var baseCreate=function(){function object(){}return function(prototype){if(isObject(prototype)){object.prototype=prototype;var result=new object;object.prototype=undefined}return result||{}}}();function baseDelay(func,wait,args){if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=true,length=array.length,result=[],valuesLength=values.length;if(!length){return result}if(iteratee){values=arrayMap(values,baseUnary(iteratee))}if(comparator){includes=arrayIncludesWith;isCommon=false}else if(values.length>=LARGE_ARRAY_SIZE){includes=cacheHas;isCommon=false;values=new SetCache(values)}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;if(isCommon&&computed===computed){var valuesIndex=valuesLength;while(valuesIndex--){if(values[valuesIndex]===computed){continue outer}}result.push(value)}else if(!includes(values,computed,comparator)){result.push(value)}}return result}var baseEach=createBaseEach(baseForOwn);var baseEachRight=createBaseEach(baseForOwnRight,true);function baseEvery(collection,predicate){var result=true;baseEach(collection,function(value,index,collection){result=!!predicate(value,index,collection);return result});return result}function baseFill(array,value,start,end){var length=array.length;start=toInteger(start);if(start<0){start=-start>length?0:length+start}end=end===undefined||end>length?length:toInteger(end);if(end<0){end+=length}end=start>end?0:toLength(end);while(start<end){array[start++]=value}return array}function baseFilter(collection,predicate){var result=[];baseEach(collection,function(value,index,collection){if(predicate(value,index,collection)){result.push(value)}});return result}function baseFlatten(array,isDeep,isStrict,result){result||(result=[]);var index=-1,length=array.length;while(++index<length){var value=array[index];if(isArrayLikeObject(value)&&(isStrict||isArray(value)||isArguments(value))){if(isDeep){baseFlatten(value,isDeep,isStrict,result)}else{arrayPush(result,value)}}else if(!isStrict){result[result.length]=value}}return result}var baseFor=createBaseFor();var baseForRight=createBaseFor(true);function baseForIn(object,iteratee){return object==null?object:baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path+""]:baseToPath(path);var index=0,length=path.length;while(object!=null&&index<length){object=object[path[index++]]}return index&&index==length?object:undefined}function baseHas(object,key){return hasOwnProperty.call(object,key)||typeof object=="object"&&key in object&&getPrototypeOf(object)===null}function baseHasIn(object,key){return key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number<nativeMax(start,end)}function baseIntersection(arrays,iteratee,comparator){var includes=comparator?arrayIncludesWith:arrayIncludes,othLength=arrays.length,othIndex=othLength,caches=Array(othLength),result=[];while(othIndex--){var array=arrays[othIndex];if(othIndex&&iteratee){array=arrayMap(array,baseUnary(iteratee))}caches[othIndex]=!comparator&&(iteratee||array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,length=array.length,seen=caches[0];outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;if(!(seen?cacheHas(seen,computed):includes(result,computed,comparator))){var othIndex=othLength;while(--othIndex){var cache=caches[othIndex];if(!(cache?cacheHas(cache,computed):includes(arrays[othIndex],computed,comparator))){continue outer}}if(seen){seen.push(computed)}result.push(value)}}return result}function baseInvoke(object,path,args){if(!isKey(path,object)){path=baseToPath(path);object=parent(object,path);path=last(path)}var func=object==null?object:object[path];return func==null?undefined:apply(func,object,args)}function baseIsEqual(value,other,customizer,bitmask,stack){if(value===other){return true}if(value==null||other==null||!isObject(value)&&!isObjectLike(other)){return value!==value&&other!==other}return baseIsEqualDeep(value,other,baseIsEqual,customizer,bitmask,stack)}function baseIsEqualDeep(object,other,equalFunc,customizer,bitmask,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;if(!objIsArr){objTag=getTag(object);if(objTag==argsTag){objTag=objectTag}else if(objTag!=objectTag){objIsArr=isTypedArray(object)}}if(!othIsArr){othTag=getTag(other);if(othTag==argsTag){othTag=objectTag}else if(othTag!=objectTag){othIsArr=isTypedArray(other)}}var objIsObj=objTag==objectTag&&!isHostObject(object),othIsObj=othTag==objectTag&&!isHostObject(other),isSameTag=objTag==othTag;if(isSameTag&&!(objIsArr||objIsObj)){return equalByTag(object,other,objTag,equalFunc,customizer,bitmask)}var isPartial=bitmask&PARTIAL_COMPARE_FLAG;if(!isPartial){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othIsWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(objIsWrapped||othIsWrapped){return equalFunc(objIsWrapped?object.value():object,othIsWrapped?other.value():other,customizer,bitmask,stack)}}if(!isSameTag){return false}stack||(stack=new Stack);return(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,bitmask,stack)}function baseIsMatch(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(object==null){return!length}object=Object(object);while(index--){var data=matchData[index];if(noCustomizer&&data[2]?data[1]!==object[data[0]]:!(data[0]in object)){return false}}while(++index<length){data=matchData[index];var key=data[0],objValue=object[key],srcValue=data[1];if(noCustomizer&&data[2]){if(objValue===undefined&&!(key in object)){return false}}else{var stack=new Stack,result=customizer?customizer(objValue,srcValue,key,object,source,stack):undefined;if(!(result===undefined?baseIsEqual(srcValue,objValue,customizer,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG,stack):result)){return false}}}return true}function baseIteratee(value){
var type=typeof value;if(type=="function"){return value}if(value==null){return identity}if(type=="object"){return isArray(value)?baseMatchesProperty(value[0],value[1]):baseMatches(value)}return property(value)}function baseKeys(object){return nativeKeys(Object(object))}function baseKeysIn(object){object=object==null?object:Object(object);var result=[];for(var key in object){result.push(key)}return result}if(enumerate&&!propertyIsEnumerable.call({valueOf:1},"valueOf")){baseKeysIn=function(object){return iteratorToArray(enumerate(object))}}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)});return result}function baseMatches(source){var matchData=getMatchData(source);if(matchData.length==1&&matchData[0][2]){var key=matchData[0][0],value=matchData[0][1];return function(object){if(object==null){return false}return object[key]===value&&(value!==undefined||key in Object(object))}}return function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,customizer,stack){if(object===source){return}var props=isArray(source)||isTypedArray(source)?undefined:keysIn(source);arrayEach(props||source,function(srcValue,key){if(props){key=srcValue;srcValue=source[key]}if(isObject(srcValue)){stack||(stack=new Stack);baseMergeDeep(object,source,key,baseMerge,customizer,stack)}else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;if(newValue===undefined){newValue=srcValue}assignMergeValue(object,key,newValue)}})}function baseMergeDeep(object,source,key,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue)||stack.get(objValue);if(stacked){assignMergeValue(object,key,stacked);return}var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;if(isCommon){newValue=srcValue;if(isArray(srcValue)||isTypedArray(srcValue)){newValue=isArray(objValue)?objValue:isArrayLikeObject(objValue)?copyArray(objValue):baseClone(srcValue)}else if(isPlainObject(srcValue)||isArguments(srcValue)){newValue=isArguments(objValue)?toPlainObject(objValue):isObject(objValue)?objValue:baseClone(srcValue)}else{isCommon=isFunction(srcValue)}}stack.set(srcValue,newValue);if(isCommon){mergeFunc(newValue,srcValue,customizer,stack)}assignMergeValue(object,key,newValue)}function baseOrderBy(collection,iteratees,orders){var index=-1,toIteratee=getIteratee();iteratees=arrayMap(iteratees.length?iteratees:Array(1),function(iteratee){return toIteratee(iteratee)});var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){object=Object(object);return arrayReduce(props,function(result,key){if(key in object){result[key]=object[key]}return result},{})}function basePickBy(object,predicate){var result={};baseForIn(object,function(value,key){if(predicate(value)){result[key]=value}});return result}function baseProperty(key){return function(object){return object==null?undefined:object[key]}}function basePropertyDeep(path){return function(object){return baseGet(object,path)}}function basePullAll(array,values){return basePullAllBy(array,values)}function basePullAllBy(array,values,iteratee){var index=-1,length=values.length,seen=array;if(iteratee){seen=arrayMap(array,function(value){return iteratee(value)})}while(++index<length){var fromIndex=0,value=values[index],computed=iteratee?iteratee(value):value;while((fromIndex=baseIndexOf(seen,computed,fromIndex))>-1){if(seen!==array){splice.call(seen,fromIndex,1)}splice.call(array,fromIndex,1)}}return array}function basePullAt(array,indexes){var length=array?indexes.length:0,lastIndex=length-1;while(length--){var index=indexes[length];if(lastIndex==length||index!=previous){var previous=index;if(isIndex(index)){splice.call(array,index,1)}else if(!isKey(index,array)){var path=baseToPath(index),object=parent(array,path);if(object!=null){delete object[last(path)]}}else{delete array[index]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);while(length--){result[fromRight?length:++index]=start;start+=step}return result}function baseSet(object,path,value,customizer){path=isKey(path,object)?[path+""]:baseToPath(path);var index=-1,length=path.length,lastIndex=length-1,nested=object;while(nested!=null&&++index<length){var key=path[index];if(isObject(nested)){var newValue=value;if(index!=lastIndex){var objValue=nested[key];newValue=customizer?customizer(objValue,key,nested):undefined;if(newValue===undefined){newValue=objValue==null?isIndex(path[index+1])?[]:{}:objValue}}assignValue(nested,key,newValue)}nested=nested[key]}return object}var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func};function baseSlice(array,start,end){var index=-1,length=array.length;if(start<0){start=-start>length?0:length+start}end=end>length?length:end;if(end<0){end+=length}length=start>end?0:end-start>>>0;start>>>=0;var result=Array(length);while(++index<length){result[index]=array[index+start]}return result}function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return!result});return!!result}function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(typeof value=="number"&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){while(low<high){var mid=low+high>>>1,computed=array[mid];if((retHighest?computed<=value:computed<value)&&computed!==null){low=mid+1}else{high=mid}}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=value===null,valIsUndef=value===undefined;while(low<high){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),isDef=computed!==undefined,isReflexive=computed===computed;if(valIsNaN){var setLow=isReflexive||retHighest}else if(valIsNull){setLow=isReflexive&&isDef&&(retHighest||computed!=null)}else if(valIsUndef){setLow=isReflexive&&(retHighest||isDef)}else if(computed==null){setLow=false}else{setLow=retHighest?computed<=value:computed<value}if(setLow){low=mid+1}else{high=mid}}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array){return baseSortedUniqBy(array)}function baseSortedUniqBy(array,iteratee){var index=0,length=array.length,value=array[0],computed=iteratee?iteratee(value):value,seen=computed,resIndex=0,result=[value];while(++index<length){value=array[index],computed=iteratee?iteratee(value):value;if(!eq(computed,seen)){seen=computed;result[++resIndex]=value}}return result}function baseToPath(value){return isArray(value)?value:stringToPath(value)}function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=true,result=[],seen=result;if(comparator){isCommon=false;includes=arrayIncludesWith}else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set){return setToArray(set)}isCommon=false;includes=cacheHas;seen=new SetCache}else{seen=iteratee?[]:result}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;if(isCommon&&computed===computed){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer}}if(iteratee){seen.push(computed)}result.push(value)}else if(!includes(seen,computed,comparator)){if(seen!==result){seen.push(computed)}result.push(value)}}return result}function baseUnset(object,path){path=isKey(path,object)?[path+""]:baseToPath(path);object=parent(object,path);var key=last(path);return object!=null&&has(object,key)?delete object[key]:true}function baseWhile(array,predicate,isDrop,fromRight){var length=array.length,index=fromRight?length:-1;while((fromRight?index--:++index<length)&&predicate(array[index],index,array)){}return isDrop?baseSlice(array,fromRight?0:index,fromRight?index+1:length):baseSlice(array,fromRight?index+1:0,fromRight?length:index)}function baseWrapperValue(value,actions){var result=value;if(result instanceof LazyWrapper){result=result.value()}return arrayReduce(actions,function(result,action){return action.func.apply(action.thisArg,arrayPush([result],action.args))},result)}function baseXor(arrays,iteratee,comparator){var index=-1,length=arrays.length;while(++index<length){var result=result?arrayPush(baseDifference(result,arrays[index],iteratee,comparator),baseDifference(arrays[index],result,iteratee,comparator)):arrays[index]}return result&&result.length?baseUniq(result,iteratee,comparator):[]}function cloneBuffer(buffer){var Ctor=buffer.constructor,result=new Ctor(buffer.byteLength),view=new Uint8Array(result);view.set(new Uint8Array(buffer));return result}function cloneMap(map){var Ctor=map.constructor;return arrayReduce(mapToArray(map),addMapEntry,new Ctor)}function cloneRegExp(regexp){var Ctor=regexp.constructor,result=new Ctor(regexp.source,reFlags.exec(regexp));result.lastIndex=regexp.lastIndex;return result}function cloneSet(set){var Ctor=set.constructor;return arrayReduce(setToArray(set),addSetEntry,new Ctor)}function cloneSymbol(symbol){return _Symbol?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=typedArray.buffer,Ctor=typedArray.constructor;return new Ctor(isDeep?cloneBuffer(buffer):buffer,typedArray.byteOffset,typedArray.length)}function composeArgs(args,partials,holders){var holdersLength=holders.length,argsIndex=-1,argsLength=nativeMax(args.length-holdersLength,0),leftIndex=-1,leftLength=partials.length,result=Array(leftLength+argsLength);while(++leftIndex<leftLength){result[leftIndex]=partials[leftIndex]}while(++argsIndex<holdersLength){result[holders[argsIndex]]=args[argsIndex]}while(argsLength--){result[leftIndex++]=args[argsIndex++]}return result}function composeArgsRight(args,partials,holders){var holdersIndex=-1,holdersLength=holders.length,argsIndex=-1,argsLength=nativeMax(args.length-holdersLength,0),rightIndex=-1,rightLength=partials.length,result=Array(argsLength+rightLength);while(++argsIndex<argsLength){result[argsIndex]=args[argsIndex]}var offset=argsIndex;while(++rightIndex<rightLength){result[offset+rightIndex]=partials[rightIndex]}while(++holdersIndex<holdersLength){result[offset+holders[holdersIndex]]=args[argsIndex++]}return result}function copyArray(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index]}return array}function copyObject(source,props,object){return copyObjectWith(source,props,object)}function copyObjectWith(source,props,object,customizer){object||(object={});var index=-1,length=props.length;while(++index<length){var key=props[index],newValue=customizer?customizer(object[key],source[key],key,object,source):source[key];assignValue(object,key,newValue)}return object}function copySymbols(source,object){return copyObject(source,getSymbols(source),object)}function createAggregator(setter,initializer){return function(collection,iteratee){var result=initializer?initializer():{};iteratee=getIteratee(iteratee);if(isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];setter(result,value,iteratee(value),collection)}}else{baseEach(collection,function(value,key,collection){setter(result,value,iteratee(value),collection)})}return result}}function createAssigner(assigner){return rest(function(object,sources){var index=-1,length=sources.length,customizer=length>1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;customizer=typeof customizer=="function"?(length--,customizer):undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined:customizer;length=1}object=Object(object);while(++index<length){var source=sources[index];if(source){assigner(object,source,customizer)}}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){if(collection==null){return collection}if(!isArrayLike(collection)){return eachFunc(collection,iteratee)}var length=collection.length,index=fromRight?length:-1,iterable=Object(collection);while(fromRight?index--:++index<length){if(iteratee(iterable[index],index,iterable)===false){break}}return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;while(length--){var key=props[fromRight?length:++index];if(iteratee(iterable[key],key,iterable)===false){break}}return object}}function createBaseWrapper(func,bitmask,thisArg){var isBind=bitmask&BIND_FLAG,Ctor=createCtorWrapper(func);function wrapper(){var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return fn.apply(isBind?thisArg:this,arguments)}return wrapper}function createCaseFirst(methodName){return function(string){string=toString(string);var strSymbols=reHasComplexSymbol.test(string)?stringToArray(string):undefined,chr=strSymbols?strSymbols[0]:string.charAt(0),trailing=strSymbols?strSymbols.slice(1).join(""):string.slice(1);return chr[methodName]()+trailing}}function createCompounder(callback){return function(string){return arrayReduce(words(deburr(string)),callback,"")}}function createCtorWrapper(Ctor){return function(){var args=arguments;switch(args.length){case 0:return new Ctor;case 1:return new Ctor(args[0]);case 2:return new Ctor(args[0],args[1]);case 3:return new Ctor(args[0],args[1],args[2]);case 4:return new Ctor(args[0],args[1],args[2],args[3]);case 5:return new Ctor(args[0],args[1],args[2],args[3],args[4]);case 6:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5]);case 7:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5],args[6])}var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,args);return isObject(result)?result:thisBinding}}function createCurryWrapper(func,bitmask,arity){var Ctor=createCtorWrapper(func);function wrapper(){var length=arguments.length,index=length,args=Array(length),fn=this&&this!==root&&this instanceof wrapper?Ctor:func,placeholder=wrapper.placeholder;while(index--){args[index]=arguments[index]}var holders=length<3&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);length-=holders.length;return length<arity?createRecurryWrapper(func,bitmask,createHybridWrapper,placeholder,undefined,args,holders,undefined,undefined,arity-length):apply(fn,this,args)}return wrapper}function createFlow(fromRight){return rest(function(funcs){funcs=baseFlatten(funcs);var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;if(fromRight){funcs.reverse()}while(index--){var func=funcs[index];if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}if(prereq&&!wrapper&&getFuncName(func)=="wrapper"){var wrapper=new LodashWrapper([],true)}}index=wrapper?index:length;while(++index<length){func=funcs[index];var funcName=getFuncName(func),data=funcName=="wrapper"?getData(func):undefined;if(data&&isLaziable(data[0])&&data[1]==(ARY_FLAG|CURRY_FLAG|PARTIAL_FLAG|REARG_FLAG)&&!data[4].length&&data[9]==1){wrapper=wrapper[getFuncName(data[0])].apply(wrapper,data[3])}else{wrapper=func.length==1&&isLaziable(func)?wrapper[funcName]():wrapper.thru(func)}}return function(){var args=arguments,value=args[0];if(wrapper&&args.length==1&&isArray(value)&&value.length>=LARGE_ARRAY_SIZE){return wrapper.plant(value).value()}var index=0,result=length?funcs[index].apply(this,args):value;while(++index<length){result=funcs[index].call(this,result)}return result}})}function createHybridWrapper(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurry=bitmask&CURRY_FLAG,isCurryRight=bitmask&CURRY_RIGHT_FLAG,isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtorWrapper(func);function wrapper(){var length=arguments.length,index=length,args=Array(length);while(index--){args[index]=arguments[index]}if(partials){args=composeArgs(args,partials,holders)}if(partialsRight){args=composeArgsRight(args,partialsRight,holdersRight)}if(isCurry||isCurryRight){var placeholder=wrapper.placeholder,argsHolders=replaceHolders(args,placeholder);length-=argsHolders.length;if(length<arity){return createRecurryWrapper(func,bitmask,createHybridWrapper,placeholder,thisArg,args,argsHolders,argPos,ary,arity-length)}}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;if(argPos){args=reorder(args,argPos)}else if(isFlip&&args.length>1){args.reverse()}if(isAry&&ary<args.length){args.length=ary}if(this&&this!==root&&this instanceof wrapper){fn=Ctor||createCtorWrapper(fn)}return fn.apply(thisBinding,args)}return wrapper}function createOver(arrayFunc){return rest(function(iteratees){iteratees=arrayMap(baseFlatten(iteratees),getIteratee());return rest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(string,length,chars){length=toInteger(length);var strLength=stringSize(string);if(!length||strLength>=length){return""}var padLength=length-strLength;chars=chars===undefined?" ":chars+"";var result=repeat(chars,nativeCeil(padLength/stringSize(chars)));return reHasComplexSymbol.test(chars)?stringToArray(result).slice(0,padLength).join(""):result.slice(0,padLength)}function createPartialWrapper(func,bitmask,thisArg,partials){var isBind=bitmask&BIND_FLAG,Ctor=createCtorWrapper(func);function wrapper(){var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;while(++leftIndex<leftLength){args[leftIndex]=partials[leftIndex]}while(argsLength--){args[leftIndex++]=arguments[++argsIndex]}return apply(fn,isBind?thisArg:this,args)}return wrapper}function createRange(fromRight){return function(start,end,step){if(step&&typeof step!="number"&&isIterateeCall(start,end,step)){end=step=undefined}start=toNumber(start);start=start===start?start:0;if(end===undefined){end=start;start=0}else{end=toNumber(end)||0}step=step===undefined?start<end?1:-1:toNumber(step)||0;return baseRange(start,end,step,fromRight)}}function createRecurryWrapper(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newArgPos=argPos?copyArray(argPos):undefined,newsHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG;bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG);if(!(bitmask&CURRY_BOUND_FLAG)){bitmask&=~(BIND_FLAG|BIND_KEY_FLAG)}var newData=[func,bitmask,thisArg,newPartials,newsHolders,newPartialsRight,newHoldersRight,newArgPos,ary,arity],result=wrapFunc.apply(undefined,newData);if(isLaziable(func)){setData(result,newData)}result.placeholder=placeholder;return result}function createRound(methodName){var func=Math[methodName];return function(number,precision){number=toNumber(number);precision=toInteger(precision);if(precision){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));pair=(toString(value)+"e").split("e");return+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}var createSet=!(Set&&new Set([1,2]).size===2)?noop:function(values){return new Set(values)};function createWrapper(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}var length=partials?partials.length:0;if(!length){bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG);partials=holders=undefined}ary=ary===undefined?ary:nativeMax(toInteger(ary),0);arity=arity===undefined?arity:toInteger(arity);length-=holders?holders.length:0;if(bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data){mergeData(newData,data)}func=newData[0];bitmask=newData[1];thisArg=newData[2];partials=newData[3];holders=newData[4];arity=newData[9]=newData[9]==null?isBindKey?0:func.length:nativeMax(newData[9]-length,0);if(!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)){bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)}if(!bitmask||bitmask==BIND_FLAG){var result=createBaseWrapper(func,bitmask,thisArg)}else if(bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG){result=createCurryWrapper(func,bitmask,arity)}else if((bitmask==PARTIAL_FLAG||bitmask==(BIND_FLAG|PARTIAL_FLAG))&&!holders.length){result=createPartialWrapper(func,bitmask,thisArg,partials)}else{result=createHybridWrapper.apply(undefined,newData)}var setter=data?baseSetData:setData;return setter(result,newData)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var index=-1,isPartial=bitmask&PARTIAL_COMPARE_FLAG,isUnordered=bitmask&UNORDERED_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength)){return false}var stacked=stack.get(array);if(stacked){return stacked==other}var result=true;stack.set(array,other);while(++index<arrLength){var arrValue=array[index],othValue=other[index];if(customizer){var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack)}if(compared!==undefined){if(compared){continue}result=false;break}if(isUnordered){if(!arraySome(other,function(othValue){return arrValue===othValue||equalFunc(arrValue,othValue,customizer,bitmask,stack)})){result=false;break}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,customizer,bitmask,stack))){result=false;break}}stack["delete"](array);return result}function equalByTag(object,other,tag,equalFunc,customizer,bitmask){switch(tag){case arrayBufferTag:if(object.byteLength!=other.byteLength||!equalFunc(new Uint8Array(object),new Uint8Array(other))){return false}return true;case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:object==+other;case regexpTag:case stringTag:return object==other+"";case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&PARTIAL_COMPARE_FLAG;convert||(convert=setToArray);return(isPartial||object.size==other.size)&&equalFunc(convert(object),convert(other),customizer,bitmask|UNORDERED_COMPARE_FLAG);case symbolTag:return!!_Symbol&&symbolValueOf.call(object)==symbolValueOf.call(other)}return false}function equalObjects(object,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,isUnordered=bitmask&UNORDERED_COMPARE_FLAG,objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial){return false}var index=objLength;while(index--){var key=objProps[index];if(!(isPartial?key in other:baseHas(other,key))||!(isUnordered||key==othProps[index])){return false}}var stacked=stack.get(object);if(stacked){return stacked==other}var result=true;stack.set(object,other);var skipCtor=isPartial;while(++index<objLength){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer){var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack)}if(!(compared===undefined?objValue===othValue||equalFunc(objValue,othValue,customizer,bitmask,stack):compared)){result=false;break}skipCtor||(skipCtor=key=="constructor")}if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&("constructor"in object&&"constructor"in other)&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)){result=false}}stack["delete"](object);return result}var getData=!metaMap?noop:function(func){return metaMap.get(func)};function getFuncName(func){var result=func.name+"",array=realNames[result],length=array?array.length:0;while(length--){var data=array[length],otherFunc=data.func;if(otherFunc==null||otherFunc==func){return data.name}}return result}function getIteratee(){var result=lodash.iteratee||iteratee;result=result===iteratee?baseIteratee:result;return arguments.length?result(arguments[0],arguments[1]):result}var getLength=baseProperty("length");function getMatchData(object){var result=toPairs(object),length=result.length;while(length--){result[length][2]=isStrictComparable(result[length][1])}return result}function getNative(object,key){var value=object==null?undefined:object[key];return isNative(value)?value:undefined}var getSymbols=getOwnPropertySymbols||function(){return[]};function getTag(value){return objectToString.call(value)}if(Map&&getTag(new Map)!=mapTag||Set&&getTag(new Set)!=setTag){getTag=function(value){var result=objectToString.call(value),Ctor=result==objectTag?value.constructor:null,ctorString=typeof Ctor=="function"?funcToString.call(Ctor):"";if(ctorString){if(ctorString==mapCtorString){return mapTag}if(ctorString==setCtorString){return setTag}}return result}}function getView(start,end,transforms){var index=-1,length=transforms.length;while(++index<length){var data=transforms[index],size=data.size;switch(data.type){case"drop":start+=size;break;case"dropRight":end-=size;break;case"take":end=nativeMin(end,start+size);break;case"takeRight":start=nativeMax(start,end-size);break}}return{start:start,end:end}}function hasPath(object,path,hasFunc){if(object==null){return false}var result=hasFunc(object,path);if(!result&&!isKey(path)){path=baseToPath(path);object=parent(object,path);if(object!=null){path=last(path);result=hasFunc(object,path)}}return result||isLength(object&&object.length)&&isIndex(path,object.length)&&(isArray(object)||isString(object)||isArguments(object))}function initCloneArray(array){var length=array.length,result=array.constructor(length);if(length&&typeof array[0]=="string"&&hasOwnProperty.call(array,"index")){result.index=array.index;result.input=array.input}return result}function initCloneObject(object){var Ctor=object.constructor;return baseCreate(isFunction(Ctor)?Ctor.prototype:undefined)}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return cloneBuffer(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:return cloneTypedArray(object,isDeep);case mapTag:return cloneMap(object);case numberTag:case stringTag:return new Ctor(object);case regexpTag:return cloneRegExp(object);case setTag:return cloneSet(object);case symbolTag:return cloneSymbol(object)}}function indexKeys(object){var length=object?object.length:undefined;return isLength(length)&&(isArray(object)||isString(object)||isArguments(object))?baseTimes(length,String):null}function isIterateeCall(value,index,object){if(!isObject(object)){return false}var type=typeof index;if(type=="number"?isArrayLike(object)&&isIndex(index,object.length):type=="string"&&index in object){return eq(object[index],value)}return false}function isKey(value,object){if(typeof value=="number"){return true}return!isArray(value)&&(reIsPlainProp.test(value)||!reIsDeepProp.test(value)||object!=null&&value in Object(object))}function isKeyable(value){var type=typeof value;return type=="number"||type=="boolean"||type=="string"&&value!=="__proto__"||value==null}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if(typeof other!="function"||!(funcName in LazyWrapper.prototype)){return false}if(func===other){return true}var data=getData(other);return!!data&&func===data[0]}function isPrototype(value){var Ctor=value&&value.constructor,proto=typeof Ctor=="function"&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=newBitmask<(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG);var isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!(isCommon||isCombo)){return data}if(srcBitmask&BIND_FLAG){data[2]=source[2];newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG}var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):copyArray(value);data[4]=partials?replaceHolders(data[3],PLACEHOLDER):copyArray(source[4])}value=source[5];if(value){partials=data[5];data[5]=partials?composeArgsRight(partials,value,source[6]):copyArray(value);data[6]=partials?replaceHolders(data[5],PLACEHOLDER):copyArray(source[6])}value=source[7];if(value){data[7]=copyArray(value)}if(srcBitmask&ARY_FLAG){data[8]=data[8]==null?source[8]:nativeMin(data[8],source[8])}if(data[9]==null){data[9]=source[9]}data[0]=source[0];data[1]=newBitmask;return data}function mergeDefaults(objValue,srcValue,key,object,source,stack){if(isObject(objValue)&&isObject(srcValue)){stack.set(srcValue,objValue);baseMerge(objValue,srcValue,mergeDefaults,stack)}return objValue===undefined?baseClone(srcValue):objValue}function parent(object,path){return path.length==1?object:get(object,baseSlice(path,0,-1))}function reorder(array,indexes){var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=copyArray(array);while(length--){var index=indexes[length];array[length]=isIndex(index,arrLength)?oldArray[index]:undefined}return array}var setData=function(){var count=0,lastCalled=0;return function(key,value){var stamp=now(),remaining=HOT_SPAN-(stamp-lastCalled);lastCalled=stamp;if(remaining>0){if(++count>=HOT_COUNT){return key}}else{count=0}return baseSetData(key,value)}}();function stringToPath(string){var result=[];toString(string).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)});return result}function toArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function toFunction(value){return typeof value=="function"?value:identity}function wrapperClone(wrapper){if(wrapper instanceof LazyWrapper){return wrapper.clone()}var result=new LodashWrapper(wrapper.__wrapped__,wrapper.__chain__);result.__actions__=copyArray(wrapper.__actions__);result.__index__=wrapper.__index__;result.__values__=wrapper.__values__;return result}function chunk(array,size){size=nativeMax(toInteger(size),0);var length=array?array.length:0;if(!length||size<1){return[]}var index=0,resIndex=-1,result=Array(nativeCeil(length/size));while(index<length){result[++resIndex]=baseSlice(array,index,index+=size)}return result}function compact(array){var index=-1,length=array?array.length:0,resIndex=-1,result=[];while(++index<length){var value=array[index];if(value){result[++resIndex]=value}}return result}var concat=rest(function(array,values){values=baseFlatten(values);return arrayConcat(isArray(array)?array:[Object(array)],values);
});var difference=rest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,false,true)):[]});var differenceBy=rest(function(array,values){var iteratee=last(values);if(isArrayLikeObject(iteratee)){iteratee=undefined}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,false,true),getIteratee(iteratee)):[]});var differenceWith=rest(function(array,values){var comparator=last(values);if(isArrayLikeObject(comparator)){comparator=undefined}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,false,true),undefined,comparator):[]});function drop(array,n,guard){var length=array?array.length:0;if(!length){return[]}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,n<0?0:n,length)}function dropRight(array,n,guard){var length=array?array.length:0;if(!length){return[]}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,0,n<0?0:n)}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true,true):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true):[]}function fill(array,value,start,end){var length=array?array.length:0;if(!length){return[]}if(start&&typeof start!="number"&&isIterateeCall(array,value,start)){start=0;end=length}return baseFill(array,value,start,end)}function findIndex(array,predicate){return array&&array.length?baseFindIndex(array,getIteratee(predicate,3)):-1}function findLastIndex(array,predicate){return array&&array.length?baseFindIndex(array,getIteratee(predicate,3),true):-1}function flatMap(array,iteratee){var length=array?array.length:0;return length?baseFlatten(arrayMap(array,getIteratee(iteratee,3))):[]}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,true):[]}function fromPairs(pairs){var index=-1,length=pairs?pairs.length:0,result={};while(++index<length){var pair=pairs[index];baseSet(result,pair[0],pair[1])}return result}function head(array){return array?array[0]:undefined}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1}fromIndex=toInteger(fromIndex);if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0)}return baseIndexOf(array,value,fromIndex)}function initial(array){return dropRight(array,1)}var intersection=rest(function(arrays){var mapped=arrayMap(arrays,toArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[]});var intersectionBy=rest(function(arrays){var iteratee=last(arrays),mapped=arrayMap(arrays,toArrayLikeObject);if(iteratee===last(mapped)){iteratee=undefined}else{mapped.pop()}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,getIteratee(iteratee)):[]});var intersectionWith=rest(function(arrays){var comparator=last(arrays),mapped=arrayMap(arrays,toArrayLikeObject);if(comparator===last(mapped)){comparator=undefined}else{mapped.pop()}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,undefined,comparator):[]});function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1}var index=length;if(fromIndex!==undefined){index=toInteger(fromIndex);index=(index<0?nativeMax(length+index,0):nativeMin(index,length-1))+1}if(value!==value){return indexOfNaN(array,index,true)}while(index--){if(array[index]===value){return index}}return-1}var pull=rest(pullAll);function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAllBy(array,values,getIteratee(iteratee)):array}var pullAt=rest(function(array,indexes){indexes=arrayMap(baseFlatten(indexes),String);var result=baseAt(array,indexes);basePullAt(array,indexes.sort(compareAscending));return result});function remove(array,predicate){var result=[];if(!(array&&array.length)){return result}var index=-1,indexes=[],length=array.length;predicate=getIteratee(predicate,3);while(++index<length){var value=array[index];if(predicate(value,index,array)){result.push(value);indexes.push(index)}}basePullAt(array,indexes);return result}function reverse(array){return array?nativeReverse.call(array):array}function slice(array,start,end){var length=array?array.length:0;if(!length){return[]}if(end&&typeof end!="number"&&isIterateeCall(array,start,end)){start=0;end=length}else{start=start==null?0:toInteger(start);end=end===undefined?length:toInteger(end)}return baseSlice(array,start,end)}function sortedIndex(array,value){return baseSortedIndex(array,value)}function sortedIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee))}function sortedIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value);if(index<length&&eq(array[index],value)){return index}}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,true)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee),true)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,true)-1;if(eq(array[index],value)){return index}}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniqBy(array,getIteratee(iteratee)):[]}function tail(array){return drop(array,1)}function take(array,n,guard){if(!(array&&array.length)){return[]}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,0,n<0?0:n)}function takeRight(array,n,guard){var length=array?array.length:0;if(!length){return[]}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,n<0?0:n,length)}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),false,true):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}var union=rest(function(arrays){return baseUniq(baseFlatten(arrays,false,true))});var unionBy=rest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined}return baseUniq(baseFlatten(arrays,false,true),getIteratee(iteratee))});var unionWith=rest(function(arrays){var comparator=last(arrays);if(isArrayLikeObject(comparator)){comparator=undefined}return baseUniq(baseFlatten(arrays,false,true),undefined,comparator)});function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!(array&&array.length)){return[]}var length=0;array=arrayFilter(array,function(group){if(isArrayLikeObject(group)){length=nativeMax(group.length,length);return true}});return baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!(array&&array.length)){return[]}var result=unzip(array);if(iteratee==null){return result}return arrayMap(result,function(group){return apply(iteratee,undefined,group)})}var without=rest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[]});var xor=rest(function(arrays){return baseXor(arrayFilter(arrays,isArrayLikeObject))});var xorBy=rest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined}return baseXor(arrayFilter(arrays,isArrayLikeObject),getIteratee(iteratee))});var xorWith=rest(function(arrays){var comparator=last(arrays);if(isArrayLikeObject(comparator)){comparator=undefined}return baseXor(arrayFilter(arrays,isArrayLikeObject),undefined,comparator)});var zip=rest(unzip);function zipObject(props,values){var index=-1,length=props?props.length:0,valsLength=values?values.length:0,result={};while(++index<length){baseSet(result,props[index],index<valsLength?values[index]:undefined)}return result}var zipWith=rest(function(arrays){var length=arrays.length,iteratee=length>1?arrays[length-1]:undefined;iteratee=typeof iteratee=="function"?(arrays.pop(),iteratee):undefined;return unzipWith(arrays,iteratee)});function chain(value){var result=lodash(value);result.__chain__=true;return result}function tap(value,interceptor){interceptor(value);return value}function thru(value,interceptor){return interceptor(value)}var wrapperAt=rest(function(paths){paths=baseFlatten(paths);var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};if(length>1||this.__actions__.length||!(value instanceof LazyWrapper)||!isIndex(start)){return this.thru(interceptor)}value=value.slice(start,+start+(length?1:0));value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined});return new LodashWrapper(value,this.__chain__).thru(function(array){if(length&&!array.length){array.push(undefined)}return array})});function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperFlatMap(iteratee){return this.map(iteratee).flatten()}function wrapperNext(){if(this.__values__===undefined){this.__values__=toArray(this.value())}var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){var result,parent=this;while(parent instanceof baseLodash){var clone=wrapperClone(parent);clone.__index__=0;clone.__values__=undefined;if(result){previous.__wrapped__=clone}else{result=clone}var previous=clone;parent=parent.__wrapped__}previous.__wrapped__=value;return result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;if(this.__actions__.length){wrapped=new LazyWrapper(this)}wrapped=wrapped.reverse();wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined});return new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:result[key]=1});function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined}return func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function find(collection,predicate){predicate=getIteratee(predicate,3);if(isArray(collection)){var index=baseFindIndex(collection,predicate);return index>-1?collection[index]:undefined}return baseFind(collection,predicate,baseEach)}function findLast(collection,predicate){predicate=getIteratee(predicate,3);if(isArray(collection)){var index=baseFindIndex(collection,predicate,true);return index>-1?collection[index]:undefined}return baseFind(collection,predicate,baseEachRight)}function forEach(collection,iteratee){return typeof iteratee=="function"&&isArray(collection)?arrayEach(collection,iteratee):baseEach(collection,toFunction(iteratee))}function forEachRight(collection,iteratee){return typeof iteratee=="function"&&isArray(collection)?arrayEachRight(collection,iteratee):baseEachRight(collection,toFunction(iteratee))}var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value)}else{result[key]=[value]}});function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection);fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0)}return isString(collection)?fromIndex<=length&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}var invokeMap=rest(function(collection,path,args){var index=-1,isFunc=typeof path=="function",isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value){var func=isFunc?path:isProp&&value!=null?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)});return result});var keyBy=createAggregator(function(result,value,key){result[key]=value});function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){if(collection==null){return[]}if(!isArray(iteratees)){iteratees=iteratees==null?[]:[iteratees]}orders=guard?undefined:orders;if(!isArray(orders)){orders=orders==null?[]:[orders]}return baseOrderBy(collection,iteratees,orders)}var partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]});function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initFromCollection=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initFromCollection,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initFromCollection=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initFromCollection,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;predicate=getIteratee(predicate,3);return func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function sample(collection){var array=isArrayLike(collection)?collection:values(collection),length=array.length;return length>0?array[baseRandom(0,length-1)]:undefined}function sampleSize(collection,n){var index=-1,result=toArray(collection),length=result.length,lastIndex=length-1;n=baseClamp(toInteger(n),0,length);while(++index<n){var rand=baseRandom(index,lastIndex),value=result[rand];result[rand]=result[index];result[index]=value}result.length=n;return result}function shuffle(collection){return sampleSize(collection,MAX_ARRAY_LENGTH)}function size(collection){if(collection==null){return 0}if(isArrayLike(collection)){var result=collection.length;return result&&isString(collection)?stringSize(collection):result}return keys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined}return func(collection,getIteratee(predicate,3))}var sortBy=rest(function(collection,iteratees){if(collection==null){return[]}var length=iteratees.length;if(length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])){iteratees=[]}else if(length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])){iteratees.length=1}return baseOrderBy(collection,baseFlatten(iteratees),[])});var now=Date.now;function after(n,func){if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}n=toInteger(n);return function(){if(--n<1){return func.apply(this,arguments)}}}function ary(func,n,guard){n=guard?undefined:n;n=func&&n==null?func.length:n;return createWrapper(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}n=toInteger(n);return function(){if(--n>0){result=func.apply(this,arguments)}if(n<=1){func=undefined}return result}}var bind=rest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,bind.placeholder);bitmask|=PARTIAL_FLAG}return createWrapper(func,bitmask,thisArg,partials,holders)});var bindKey=rest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,bindKey.placeholder);bitmask|=PARTIAL_FLAG}return createWrapper(key,bitmask,object,partials,holders)});function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrapper(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curry.placeholder;return result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrapper(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curryRight.placeholder;return result}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,leading=false,maxWait=false,trailing=true;if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}wait=toNumber(wait)||0;if(isObject(options)){leading=!!options.leading;maxWait="maxWait"in options&&nativeMax(toNumber(options.maxWait)||0,wait);trailing="trailing"in options?!!options.trailing:trailing}function cancel(){if(timeoutId){clearTimeout(timeoutId)}if(maxTimeoutId){clearTimeout(maxTimeoutId)}lastCalled=0;args=maxTimeoutId=thisArg=timeoutId=trailingCall=undefined}function complete(isCalled,id){if(id){clearTimeout(id)}maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=undefined}}}function delayed(){var remaining=wait-(now()-stamp);if(remaining<=0||remaining>wait){complete(trailingCall,maxTimeoutId)}else{timeoutId=setTimeout(delayed,remaining)}}function flush(){if(timeoutId&&trailingCall||maxTimeoutId&&trailing){result=func.apply(thisArg,args)}cancel();return result}function maxDelayed(){complete(trailing,timeoutId)}function debounced(){args=arguments;stamp=now();thisArg=this;trailingCall=trailing&&(timeoutId||!leading);if(maxWait===false){var leadingCall=leading&&!timeoutId}else{if(!maxTimeoutId&&!leading){lastCalled=stamp}var remaining=maxWait-(stamp-lastCalled),isCalled=remaining<=0||remaining>maxWait;if(isCalled){if(maxTimeoutId){maxTimeoutId=clearTimeout(maxTimeoutId)}lastCalled=stamp;result=func.apply(thisArg,args)}else if(!maxTimeoutId){maxTimeoutId=setTimeout(maxDelayed,remaining)}}if(isCalled&&timeoutId){timeoutId=clearTimeout(timeoutId)}else if(!timeoutId&&wait!==maxWait){timeoutId=setTimeout(delayed,wait)}if(leadingCall){isCalled=true;result=func.apply(thisArg,args)}if(isCalled&&!timeoutId&&!maxTimeoutId){args=thisArg=undefined}return result}debounced.cancel=cancel;debounced.flush=flush;return debounced}var defer=rest(function(func,args){return baseDelay(func,1,args)});var delay=rest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});function flip(func){return createWrapper(func,FLIP_FLAG)}function memoize(func,resolver){if(typeof func!="function"||resolver&&typeof resolver!="function"){throw new TypeError(FUNC_ERROR_TEXT)}var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key)}var result=func.apply(this,args);memoized.cache=cache.set(key,result);return result};memoized.cache=new memoize.Cache;return memoized}function negate(predicate){if(typeof predicate!="function"){throw new TypeError(FUNC_ERROR_TEXT)}return function(){return!predicate.apply(this,arguments)}}function once(func){return before(2,func)}var overArgs=rest(function(func,transforms){transforms=arrayMap(baseFlatten(transforms),getIteratee());var funcsLength=transforms.length;return rest(function(args){var index=-1,length=nativeMin(args.length,funcsLength);while(++index<length){args[index]=transforms[index].call(this,args[index])}return apply(func,this,args)})});var partial=rest(function(func,partials){var holders=replaceHolders(partials,partial.placeholder);return createWrapper(func,PARTIAL_FLAG,undefined,partials,holders)});var partialRight=rest(function(func,partials){var holders=replaceHolders(partials,partialRight.placeholder);return createWrapper(func,PARTIAL_RIGHT_FLAG,undefined,partials,holders)});var rearg=rest(function(func,indexes){return createWrapper(func,REARG_FLAG,undefined,undefined,undefined,baseFlatten(indexes))});function rest(func,start){if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}start=nativeMax(start===undefined?func.length-1:toInteger(start),0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index<length){array[index]=args[start+index]}switch(start){case 0:return func.call(this,array);case 1:return func.call(this,args[0],array);case 2:return func.call(this,args[0],args[1],array)}var otherArgs=Array(start+1);index=-1;while(++index<start){otherArgs[index]=args[index]}otherArgs[start]=array;return apply(func,this,otherArgs)}}function spread(func){if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}return function(array){return apply(func,this,array)}}function throttle(func,wait,options){var leading=true,trailing=true;if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}if(isObject(options)){leading="leading"in options?!!options.leading:leading;trailing="trailing"in options?!!options.trailing:trailing}return debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){wrapper=wrapper==null?identity:wrapper;return partial(wrapper,value)}function clone(value){return baseClone(value)}function cloneWith(value,customizer){return baseClone(value,false,customizer)}function cloneDeep(value){return baseClone(value,true)}function cloneDeepWith(value,customizer){return baseClone(value,true,customizer)}function eq(value,other){return value===other||value!==value&&other!==other}function gt(value,other){return value>other}function gte(value,other){return value>=other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}var isArray=Array.isArray;function isArrayLike(value){return value!=null&&!(typeof value=="function"&&isFunction(value))&&isLength(getLength(value))}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===true||value===false||isObjectLike(value)&&objectToString.call(value)==boolTag}function isDate(value){return isObjectLike(value)&&objectToString.call(value)==dateTag}function isElement(value){return!!value&&value.nodeType===1&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){return!isObjectLike(value)||isFunction(value.splice)?!size(value):!keys(value).length}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer=typeof customizer=="function"?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)&&typeof value.message=="string"&&objectToString.call(value)==errorTag}function isFinite(value){return typeof value=="number"&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return typeof value=="number"&&value==toInteger(value)}function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}function isObjectLike(value){return!!value&&typeof value=="object"}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){customizer=typeof customizer=="function"?customizer:undefined;return baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(value==null){return false}if(isFunction(value)){return reIsNative.test(funcToString.call(value))}return isObjectLike(value)&&(isHostObject(value)?reIsNative:reIsHostCtor).test(value)}function isNull(value){return value===null}function isNil(value){return value==null}function isNumber(value){return typeof value=="number"||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag||isHostObject(value)){return false}var proto=objectProto;if(typeof value.constructor=="function"){proto=getPrototypeOf(value)}if(proto===null){return true}var Ctor=proto.constructor;return typeof Ctor=="function"&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isRegExp(value){return isObject(value)&&objectToString.call(value)==regexpTag}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER}function isString(value){return typeof value=="string"||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return typeof value=="symbol"||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objectToString.call(value)]}function isUndefined(value){return value===undefined}function lt(value,other){return value<other}function lte(value,other){return value<=other}function toArray(value){if(!value){return[]}if(isArrayLike(value)){return isString(value)?stringToArray(value):copyArray(value)}if(iteratorSymbol&&value[iteratorSymbol]){return iteratorToArray(value[iteratorSymbol]())}var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toInteger(value){if(!value){return value===0?value:0}value=toNumber(value);if(value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER}var remainder=value%1;return value===value?remainder?value-remainder:value:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if(isObject(value)){var other=isFunction(value.valueOf)?value.valueOf():value;value=isObject(other)?other+"":other}if(typeof value!="string"){return value===0?value:+value}value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){if(typeof value=="string"){return value}if(value==null){return""}if(isSymbol(value)){return _Symbol?symbolToString.call(value):""}var result=value+"";return result=="0"&&1/value==-INFINITY?"-0":result}var assign=createAssigner(function(object,source){copyObject(source,keys(source),object)});var assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)});var assignInWith=createAssigner(function(object,source,customizer){copyObjectWith(source,keysIn(source),object,customizer)});var assignWith=createAssigner(function(object,source,customizer){copyObjectWith(source,keys(source),object,customizer)});var at=rest(function(object,paths){return baseAt(object,baseFlatten(paths))});function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}var defaults=rest(function(args){args.push(undefined,assignInDefaults);return apply(assignInWith,undefined,args)});var defaultsDeep=rest(function(args){args.push(undefined,mergeDefaults);return apply(mergeWith,undefined,args)});function findKey(object,predicate){return baseFind(object,getIteratee(predicate,3),baseForOwn,true)}function findLastKey(object,predicate){return baseFind(object,getIteratee(predicate,3),baseForOwnRight,true)}function forIn(object,iteratee){return object==null?object:baseFor(object,toFunction(iteratee),keysIn)}function forInRight(object,iteratee){return object==null?object:baseForRight(object,toFunction(iteratee),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,toFunction(iteratee))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,toFunction(iteratee))}function functions(object){return object==null?[]:baseFunctions(object,keys(object))}function functionsIn(object){return object==null?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=object==null?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return hasPath(object,path,baseHas)}function hasIn(object,path){return hasPath(object,path,baseHasIn)}function invert(object,multiVal,guard){return arrayReduce(keys(object),function(result,key){var value=object[key];if(multiVal&&!guard){if(hasOwnProperty.call(result,value)){result[value].push(key)}else{result[value]=[key]}}else{result[value]=key}return result},{})}var invoke=rest(baseInvoke);function keys(object){var isProto=isPrototype(object);if(!(isProto||isArrayLike(object))){return baseKeys(object)}var indexes=indexKeys(object),skipIndexes=!!indexes,result=indexes||[],length=result.length;for(var key in object){if(baseHas(object,key)&&!(skipIndexes&&(key=="length"||isIndex(key,length)))&&!(isProto&&key=="constructor")){result.push(key)}}return result}function keysIn(object){var index=-1,isProto=isPrototype(object),props=baseKeysIn(object),propsLength=props.length,indexes=indexKeys(object),skipIndexes=!!indexes,result=indexes||[],length=result.length;while(++index<propsLength){var key=props[index];if(!(skipIndexes&&(key=="length"||isIndex(key,length)))&&!(key=="constructor"&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key)}}return result}function mapKeys(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){result[iteratee(value,key,object)]=value});return result}function mapValues(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){result[key]=iteratee(value,key,object)});return result}var merge=createAssigner(function(object,source){baseMerge(object,source)});var mergeWith=createAssigner(function(object,source,customizer){baseMerge(object,source,customizer)});var omit=rest(function(object,props){if(object==null){return{}}props=arrayMap(baseFlatten(props),String);return basePick(object,baseDifference(keysIn(object),props))});function omitBy(object,predicate){predicate=getIteratee(predicate);return basePickBy(object,function(value){return!predicate(value)})}var pick=rest(function(object,props){return object==null?{}:basePick(object,baseFlatten(props))});function pickBy(object,predicate){return object==null?{}:basePickBy(object,getIteratee(predicate))}function result(object,path,defaultValue){if(!isKey(path,object)){path=baseToPath(path);var result=get(object,path);object=parent(object,path)}else{result=object==null?undefined:object[path]}if(result===undefined){result=defaultValue}return isFunction(result)?result.call(object):result}function set(object,path,value){return object==null?object:baseSet(object,path,value)}function setWith(object,path,value,customizer){customizer=typeof customizer=="function"?customizer:undefined;return object==null?object:baseSet(object,path,value,customizer)}function toPairs(object){return baseToPairs(object,keys(object))}function toPairsIn(object){return baseToPairs(object,keysIn(object))}function transform(object,iteratee,accumulator){var isArr=isArray(object)||isTypedArray(object);iteratee=getIteratee(iteratee,4);if(accumulator==null){if(isArr||isObject(object)){var Ctor=object.constructor;if(isArr){accumulator=isArray(object)?new Ctor:[];
}else{accumulator=baseCreate(isFunction(Ctor)?Ctor.prototype:undefined)}}else{accumulator={}}}(isArr?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object)});return accumulator}function unset(object,path){return object==null?true:baseUnset(object,path)}function values(object){return object?baseValues(object,keys(object)):[]}function valuesIn(object){return object==null?baseValues(object,keysIn(object)):[]}function clamp(number,lower,upper){if(upper===undefined){upper=lower;lower=undefined}if(upper!==undefined){upper=toNumber(upper);upper=upper===upper?upper:0}if(lower!==undefined){lower=toNumber(lower);lower=lower===lower?lower:0}return baseClamp(toNumber(number),lower,upper)}function inRange(number,start,end){start=toNumber(start)||0;if(end===undefined){end=start;start=0}else{end=toNumber(end)||0}number=toNumber(number);return baseInRange(number,start,end)}function random(lower,upper,floating){if(floating&&typeof floating!="boolean"&&isIterateeCall(lower,upper,floating)){upper=floating=undefined}if(floating===undefined){if(typeof upper=="boolean"){floating=upper;upper=undefined}else if(typeof lower=="boolean"){floating=lower;lower=undefined}}if(lower===undefined&&upper===undefined){lower=0;upper=1}else{lower=toNumber(lower)||0;if(upper===undefined){upper=lower;lower=0}else{upper=toNumber(upper)||0}}if(lower>upper){var temp=lower;lower=upper;upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return result+(index?capitalize(word):word)});function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){string=toString(string);return string&&string.replace(reLatin1,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string);target=typeof target=="string"?target:target+"";var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);position-=target.length;return position>=0&&string.indexOf(target,position)==position}function escape(string){string=toString(string);return string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){string=toString(string);return string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}var kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()});var lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()});var lowerFirst=createCaseFirst("toLowerCase");var upperFirst=createCaseFirst("toUpperCase");function pad(string,length,chars){string=toString(string);length=toInteger(length);var strLength=stringSize(string);if(!length||strLength>=length){return string}var mid=(length-strLength)/2,leftLength=nativeFloor(mid),rightLength=nativeCeil(mid);return createPadding("",leftLength,chars)+string+createPadding("",rightLength,chars)}function padEnd(string,length,chars){string=toString(string);return string+createPadding(string,length,chars)}function padStart(string,length,chars){string=toString(string);return createPadding(string,length,chars)+string}function parseInt(string,radix,guard){if(guard||radix==null){radix=0}else if(radix){radix=+radix}string=toString(string).replace(reTrim,"");return nativeParseInt(string,radix||(reHasHexPrefix.test(string)?16:10))}function repeat(string,n){string=toString(string);n=toInteger(n);var result="";if(!string||n<1||n>MAX_SAFE_INTEGER){return result}do{if(n%2){result+=string}n=nativeFloor(n/2);string+=string}while(n);return result}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}var snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()});function split(string,separator,limit){return toString(string).split(separator,limit)}var startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+capitalize(word)});function startsWith(string,target,position){string=toString(string);position=baseClamp(toInteger(position),0,string.length);return string.lastIndexOf(target,position)==position}function template(string,options,guard){var settings=lodash.templateSettings;if(guard&&isIterateeCall(string,options,guard)){options=undefined}string=toString(string);options=assignInWith({},options,settings,assignInDefaults);var imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys);var isEscaping,isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");var sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){isEscaping=true;source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable;if(!variable){source="with (obj) {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});result.source=source;if(isError(result)){throw result}return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){string=toString(string);if(!string){return string}if(guard||chars===undefined){return string.replace(reTrim,"")}chars=chars+"";if(!chars){return string}var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars);return strSymbols.slice(charsStartIndex(strSymbols,chrSymbols),charsEndIndex(strSymbols,chrSymbols)+1).join("")}function trimEnd(string,chars,guard){string=toString(string);if(!string){return string}if(guard||chars===undefined){return string.replace(reTrimEnd,"")}chars=chars+"";if(!chars){return string}var strSymbols=stringToArray(string);return strSymbols.slice(0,charsEndIndex(strSymbols,stringToArray(chars))+1).join("")}function trimStart(string,chars,guard){string=toString(string);if(!string){return string}if(guard||chars===undefined){return string.replace(reTrimStart,"")}chars=chars+"";if(!chars){return string}var strSymbols=stringToArray(string);return strSymbols.slice(charsStartIndex(strSymbols,stringToArray(chars))).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length;omission="omission"in options?toString(options.omission):omission}string=toString(string);var strLength=string.length;if(reHasComplexSymbol.test(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength){return string}var end=length-stringSize(omission);if(end<1){return omission}var result=strSymbols?strSymbols.slice(0,end).join(""):string.slice(0,end);if(separator===undefined){return result+omission}if(strSymbols){end+=result.length-end}if(isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;if(!separator.global){separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")}separator.lastIndex=0;while(match=separator.exec(substring)){var newEnd=match.index}result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(separator,end)!=end){var index=result.lastIndexOf(separator);if(index>-1){result=result.slice(0,index)}}return result+omission}function unescape(string){string=toString(string);return string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}var upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()});function words(string,pattern,guard){string=toString(string);pattern=guard?undefined:pattern;if(pattern===undefined){pattern=reHasComplexWord.test(string)?reComplexWord:reBasicWord}return string.match(pattern)||[]}var attempt=rest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}});var bindAll=rest(function(object,methodNames){arrayEach(baseFlatten(methodNames),function(key){object[key]=bind(object[key],object)});return object});function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();pairs=!length?[]:arrayMap(pairs,function(pair){if(typeof pair[1]!="function"){throw new TypeError(FUNC_ERROR_TEXT)}return[toIteratee(pair[0]),pair[1]]});return rest(function(args){var index=-1;while(++index<length){var pair=pairs[index];if(apply(pair[0],this,args)){return apply(pair[1],this,args)}}})}function conforms(source){return baseConforms(baseClone(source,true))}function constant(value){return function(){return value}}var flow=createFlow();var flowRight=createFlow(true);function identity(value){return value}function iteratee(func){return isObjectLike(func)&&!isArray(func)?matches(func):baseIteratee(func)}function matches(source){return baseMatches(baseClone(source,true))}function matchesProperty(path,srcValue){return baseMatchesProperty(path,baseClone(srcValue,true))}var method=rest(function(path,args){return function(object){return baseInvoke(object,path,args)}});var methodOf=rest(function(object,args){return function(path){return baseInvoke(object,path,args)}});function mixin(object,source,options){var props=keys(source),methodNames=baseFunctions(source,props);if(options==null&&!(isObject(source)&&(methodNames.length||!props.length))){options=source;source=object;object=this;methodNames=baseFunctions(source,keys(source))}var chain=isObject(options)&&"chain"in options?options.chain:true,isFunc=isFunction(object);arrayEach(methodNames,function(methodName){var func=source[methodName];object[methodName]=func;if(isFunc){object.prototype[methodName]=function(){var chainAll=this.__chain__;if(chain||chainAll){var result=object(this.__wrapped__),actions=result.__actions__=copyArray(this.__actions__);actions.push({func:func,args:arguments,thisArg:object});result.__chain__=chainAll;return result}return func.apply(object,arrayPush([this.value()],arguments))}}});return object}function noConflict(){root._=oldDash;return this}function noop(){}function nthArg(n){n=toInteger(n);return function(){return arguments[n]}}var over=createOver(arrayMap);var overEvery=createOver(arrayEvery);var overSome=createOver(arraySome);function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}function propertyOf(object){return function(path){return object==null?undefined:baseGet(object,path)}}var range=createRange();var rangeRight=createRange(true);function times(n,iteratee){n=toInteger(n);if(n<1||n>MAX_SAFE_INTEGER){return[]}var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=toFunction(iteratee);n-=MAX_ARRAY_LENGTH;var result=baseTimes(length,iteratee);while(++index<n){iteratee(index)}return result}function toPath(value){return isArray(value)?arrayMap(value,String):stringToPath(value)}function uniqueId(prefix){var id=++idCounter;return toString(prefix)+id}function add(augend,addend){var result;if(augend!==undefined){result=augend}if(addend!==undefined){result=result===undefined?addend:result+addend}return result}var ceil=createRound("ceil");var floor=createRound("floor");function max(array){return array&&array.length?baseExtremum(array,identity,gt):undefined}function maxBy(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee),gt):undefined}function mean(array){return sum(array)/(array?array.length:0)}function min(array){return array&&array.length?baseExtremum(array,identity,lt):undefined}function minBy(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee),lt):undefined}var round=createRound("round");function subtract(minuend,subtrahend){var result;if(minuend!==undefined){result=minuend}if(subtrahend!==undefined){result=result===undefined?subtrahend:result-subtrahend}return result}function sum(array){return array&&array.length?baseSum(array,identity):undefined}function sumBy(array,iteratee){return array&&array.length?baseSum(array,getIteratee(iteratee)):undefined}lodash.prototype=baseLodash.prototype;LodashWrapper.prototype=baseCreate(baseLodash.prototype);LodashWrapper.prototype.constructor=LodashWrapper;LazyWrapper.prototype=baseCreate(baseLodash.prototype);LazyWrapper.prototype.constructor=LazyWrapper;Hash.prototype=nativeCreate?nativeCreate(null):objectProto;MapCache.prototype.clear=mapClear;MapCache.prototype["delete"]=mapDelete;MapCache.prototype.get=mapGet;MapCache.prototype.has=mapHas;MapCache.prototype.set=mapSet;SetCache.prototype.push=cachePush;Stack.prototype.clear=stackClear;Stack.prototype["delete"]=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;memoize.Cache=MapCache;lodash.after=after;lodash.ary=ary;lodash.assign=assign;lodash.assignIn=assignIn;lodash.assignInWith=assignInWith;lodash.assignWith=assignWith;lodash.at=at;lodash.before=before;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.chain=chain;lodash.chunk=chunk;lodash.compact=compact;lodash.concat=concat;lodash.cond=cond;lodash.conforms=conforms;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.curry=curry;lodash.curryRight=curryRight;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defaultsDeep=defaultsDeep;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.differenceBy=differenceBy;lodash.differenceWith=differenceWith;lodash.drop=drop;lodash.dropRight=dropRight;lodash.dropRightWhile=dropRightWhile;lodash.dropWhile=dropWhile;lodash.fill=fill;lodash.filter=filter;lodash.flatMap=flatMap;lodash.flatten=flatten;lodash.flattenDeep=flattenDeep;lodash.flip=flip;lodash.flow=flow;lodash.flowRight=flowRight;lodash.fromPairs=fromPairs;lodash.functions=functions;lodash.functionsIn=functionsIn;lodash.groupBy=groupBy;lodash.initial=initial;lodash.intersection=intersection;lodash.intersectionBy=intersectionBy;lodash.intersectionWith=intersectionWith;lodash.invert=invert;lodash.invokeMap=invokeMap;lodash.iteratee=iteratee;lodash.keyBy=keyBy;lodash.keys=keys;lodash.keysIn=keysIn;lodash.map=map;lodash.mapKeys=mapKeys;lodash.mapValues=mapValues;lodash.matches=matches;lodash.matchesProperty=matchesProperty;lodash.memoize=memoize;lodash.merge=merge;lodash.mergeWith=mergeWith;lodash.method=method;lodash.methodOf=methodOf;lodash.mixin=mixin;lodash.negate=negate;lodash.nthArg=nthArg;lodash.omit=omit;lodash.omitBy=omitBy;lodash.once=once;lodash.orderBy=orderBy;lodash.over=over;lodash.overArgs=overArgs;lodash.overEvery=overEvery;lodash.overSome=overSome;lodash.partial=partial;lodash.partialRight=partialRight;lodash.partition=partition;lodash.pick=pick;lodash.pickBy=pickBy;lodash.property=property;lodash.propertyOf=propertyOf;lodash.pull=pull;lodash.pullAll=pullAll;lodash.pullAllBy=pullAllBy;lodash.pullAt=pullAt;lodash.range=range;lodash.rangeRight=rangeRight;lodash.rearg=rearg;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.reverse=reverse;lodash.sampleSize=sampleSize;lodash.set=set;lodash.setWith=setWith;lodash.shuffle=shuffle;lodash.slice=slice;lodash.sortBy=sortBy;lodash.sortedUniq=sortedUniq;lodash.sortedUniqBy=sortedUniqBy;lodash.split=split;lodash.spread=spread;lodash.tail=tail;lodash.take=take;lodash.takeRight=takeRight;lodash.takeRightWhile=takeRightWhile;lodash.takeWhile=takeWhile;lodash.tap=tap;lodash.throttle=throttle;lodash.thru=thru;lodash.toArray=toArray;lodash.toPairs=toPairs;lodash.toPairsIn=toPairsIn;lodash.toPath=toPath;lodash.toPlainObject=toPlainObject;lodash.transform=transform;lodash.unary=unary;lodash.union=union;lodash.unionBy=unionBy;lodash.unionWith=unionWith;lodash.uniq=uniq;lodash.uniqBy=uniqBy;lodash.uniqWith=uniqWith;lodash.unset=unset;lodash.unzip=unzip;lodash.unzipWith=unzipWith;lodash.values=values;lodash.valuesIn=valuesIn;lodash.without=without;lodash.words=words;lodash.wrap=wrap;lodash.xor=xor;lodash.xorBy=xorBy;lodash.xorWith=xorWith;lodash.zip=zip;lodash.zipObject=zipObject;lodash.zipWith=zipWith;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assignIn;lodash.extendWith=assignInWith;mixin(lodash,lodash);lodash.add=add;lodash.attempt=attempt;lodash.camelCase=camelCase;lodash.capitalize=capitalize;lodash.ceil=ceil;lodash.clamp=clamp;lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.cloneDeepWith=cloneDeepWith;lodash.cloneWith=cloneWith;lodash.deburr=deburr;lodash.endsWith=endsWith;lodash.eq=eq;lodash.escape=escape;lodash.escapeRegExp=escapeRegExp;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.floor=floor;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.get=get;lodash.gt=gt;lodash.gte=gte;lodash.has=has;lodash.hasIn=hasIn;lodash.head=head;lodash.identity=identity;lodash.includes=includes;lodash.indexOf=indexOf;lodash.inRange=inRange;lodash.invoke=invoke;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isArrayLike=isArrayLike;lodash.isArrayLikeObject=isArrayLikeObject;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isEqualWith=isEqualWith;lodash.isError=isError;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isInteger=isInteger;lodash.isLength=isLength;lodash.isMatch=isMatch;lodash.isMatchWith=isMatchWith;lodash.isNaN=isNaN;lodash.isNative=isNative;lodash.isNil=isNil;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isObjectLike=isObjectLike;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isSafeInteger=isSafeInteger;lodash.isString=isString;lodash.isSymbol=isSymbol;lodash.isTypedArray=isTypedArray;lodash.isUndefined=isUndefined;lodash.join=join;lodash.kebabCase=kebabCase;lodash.last=last;lodash.lastIndexOf=lastIndexOf;lodash.lowerCase=lowerCase;lodash.lowerFirst=lowerFirst;lodash.lt=lt;lodash.lte=lte;lodash.max=max;lodash.maxBy=maxBy;lodash.mean=mean;lodash.min=min;lodash.minBy=minBy;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.pad=pad;lodash.padEnd=padEnd;lodash.padStart=padStart;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.repeat=repeat;lodash.replace=replace;lodash.result=result;lodash.round=round;lodash.runInContext=runInContext;lodash.sample=sample;lodash.size=size;lodash.snakeCase=snakeCase;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.sortedIndexBy=sortedIndexBy;lodash.sortedIndexOf=sortedIndexOf;lodash.sortedLastIndex=sortedLastIndex;lodash.sortedLastIndexBy=sortedLastIndexBy;lodash.sortedLastIndexOf=sortedLastIndexOf;lodash.startCase=startCase;lodash.startsWith=startsWith;lodash.subtract=subtract;lodash.sum=sum;lodash.sumBy=sumBy;lodash.template=template;lodash.times=times;lodash.toInteger=toInteger;lodash.toLength=toLength;lodash.toLower=toLower;lodash.toNumber=toNumber;lodash.toSafeInteger=toSafeInteger;lodash.toString=toString;lodash.toUpper=toUpper;lodash.trim=trim;lodash.trimEnd=trimEnd;lodash.trimStart=trimStart;lodash.truncate=truncate;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.upperCase=upperCase;lodash.upperFirst=upperFirst;lodash.first=head;mixin(lodash,function(){var source={};baseForOwn(lodash,function(func,methodName){if(!hasOwnProperty.call(lodash.prototype,methodName)){source[methodName]=func}});return source}(),{chain:false});lodash.VERSION=VERSION;arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash});arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index){return new LazyWrapper(this)}n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();if(filtered){result.__takeCount__=nativeMin(n,result.__takeCount__)}else{result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")})}return result};LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}});arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type});result.__filtered__=result.__filtered__||isFilter;return result}});arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}});arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}});LazyWrapper.prototype.compact=function(){return this.filter(identity)};LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()};LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)};LazyWrapper.prototype.invokeMap=rest(function(path,args){if(typeof path=="function"){return new LazyWrapper(this)}return this.map(function(value){return baseInvoke(value,path,args)})});LazyWrapper.prototype.reject=function(predicate){predicate=getIteratee(predicate,3);return this.filter(function(value){return!predicate(value)})};LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;if(result.__filtered__&&(start>0||end<0)){return new LazyWrapper(result)}if(start<0){result=result.takeRight(-start)}else if(start){result=result.drop(start)}if(end!==undefined){end=toInteger(end);result=end<0?result.dropRight(-end):result.take(end-start)}return result};LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()};LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)};baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+(methodName=="last"?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);if(!lodashFunc){return}lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value);var interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};if(useLazy&&checkIteratee&&typeof iteratee=="function"&&iteratee.length!=1){isLazy=useLazy=false}var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined});return new LodashWrapper(result,chainAll)}if(isUnwrapped&&onlyLazy){return func.apply(this,args)}result=this.thru(interceptor);return isUnwrapped?isTaker?result.value()[0]:result.value():result}});arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){return func.apply(this.value(),args)}return this[chainName](function(value){return func.apply(value,args)})}});baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}});realNames[createHybridWrapper(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}];LazyWrapper.prototype.clone=lazyClone;LazyWrapper.prototype.reverse=lazyReverse;LazyWrapper.prototype.value=lazyValue;lodash.prototype.at=wrapperAt;lodash.prototype.chain=wrapperChain;lodash.prototype.commit=wrapperCommit;lodash.prototype.flatMap=wrapperFlatMap;lodash.prototype.next=wrapperNext;lodash.prototype.plant=wrapperPlant;lodash.prototype.reverse=wrapperReverse;lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue;if(iteratorSymbol){lodash.prototype[iteratorSymbol]=wrapperToIterator}return lodash}var _=runInContext();(freeWindow||freeSelf||{})._=_;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}freeExports._=_}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],lodash:[function(require,module,exports){module.exports=require("./lodash.js")},{"./lodash.js":1}]},{},[]);var mongoose=require("mongoose");var _=require("lodash");var ThingSchema=new mongoose.Schema({name:{type:String,required:true},quantity:{type:Number,required:true},age:{type:Number,required:true},things:[{quantity:{type:Number,required:true},name:{type:String,required:true},weight:{type:Number,required:true}}]});var doc1=new mongoose.Document({things:[{}]},ThingSchema);doc1.validate(function(result){document.getElementById("log1").innerHTML="<ul>"+_.map(Object.keys(result.errors),function(key){return"<li>"+key+"</li>"}).join("")+"</ul>";console.log(result.errors)});var doc2=new mongoose.Document({name:"Thingamajig",quantity:2,things:[{}]},ThingSchema);doc2.validate(function(result){document.getElementById("log2").innerHTML="<ul>"+_.map(Object.keys(result.errors),function(key){return"<li>"+key+"</li>"}).join("")+"</ul>";console.log(result.errors)});
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"mongoose": "4.4.2",
"lodash": "4.0.0"
}
}
<!-- contents of this file will be placed inside the <body> -->
<h3>Error messages with an empty doc:</h3>
<p id="log1"></p>
<h3>Error messages with values for doc.name and doc.quantity:</h3>
<p id="log2"></p>
<!-- contents of this file will be placed inside the <head> -->
<style>
textarea {
box-sizing: border-box;
display: inline-block;
height: 500px;
width: 45%;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment