forked from mWater/minimongo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimongo.min.js
More file actions
21 lines (21 loc) · 130 KB
/
Copy pathminimongo.min.js
File metadata and controls
21 lines (21 loc) · 130 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={i:moduleId,l:false,exports:{}};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.l=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.d=function(exports,name,getter){if(!__webpack_require__.o(exports,name)){Object.defineProperty(exports,name,{configurable:false,enumerable:true,get:getter})}};__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};__webpack_require__.d(getter,"a",getter);return getter};__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)};__webpack_require__.p="";return __webpack_require__(__webpack_require__.s=11)})([function(module,exports,__webpack_require__){var async,bowser,compileDocumentSelector,compileSort,deg2rad,getDistanceFromLatLngInM,isLocalStorageSupported,pointInPolygon,processGeoIntersectsOperator,processNearOperator,_;_=__webpack_require__(1);async=__webpack_require__(3);bowser=__webpack_require__(15);compileDocumentSelector=__webpack_require__(2).compileDocumentSelector;compileSort=__webpack_require__(2).compileSort;isLocalStorageSupported=function(){var e;if(!window.localStorage){return false}try{window.localStorage.setItem("test","test");window.localStorage.removeItem("test");return true}catch(_error){e=_error;return false}};exports.compileDocumentSelector=compileDocumentSelector;exports.autoselectLocalDb=function(options,success,error){var IndexedDb,LocalStorageDb,MemoryDb,WebSQLDb,browser;IndexedDb=__webpack_require__(7);WebSQLDb=__webpack_require__(8);LocalStorageDb=__webpack_require__(9);MemoryDb=__webpack_require__(4);browser=bowser.browser;if(!isLocalStorageSupported()){return new MemoryDb(options,success)}if(window.cordova){console.log("Selecting WebSQLDb for Cordova");return new WebSQLDb(options,success,error)}if(browser.android||browser.ios||browser.chrome||browser.safari||browser.opera||browser.blackberry){console.log("Selecting WebSQLDb for browser");return new WebSQLDb(options,success,function(_this){return function(err){console.log("Failed to create WebSQLDb: "+(err?err.message:void 0));return new IndexedDb(options,success,function(err){console.log("Failed to create IndexedDb: "+(err?err.message:void 0));return new MemoryDb(options,success)})}}(this))}if(browser.firefox&&browser.version>=16){console.log("Selecting IndexedDb for browser");return new IndexedDb(options,success,function(_this){return function(err){console.log("Failed to create IndexedDb: "+(err?err.message:void 0));return new MemoryDb(options,success)}}(this))}console.log("Selecting LocalStorageDb for fallback");return new LocalStorageDb(options,success,error)};exports.migrateLocalDb=function(fromDb,toDb,success,error){var HybridDb,col,hybridDb,name,_ref;HybridDb=__webpack_require__(10);hybridDb=new HybridDb(fromDb,toDb);_ref=fromDb.collections;for(name in _ref){col=_ref[name];if(toDb[name]){hybridDb.addCollection(name)}}return hybridDb.upload(success,error)};exports.cloneLocalDb=function(fromDb,toDb,success,error){var col,name,_ref;_ref=fromDb.collections;for(name in _ref){col=_ref[name];if(!toDb[name]){toDb.addCollection(name)}}return async.each(_.values(fromDb.collections),function(_this){return function(fromCol,cb){var toCol;toCol=toDb[fromCol.name];return fromCol.find({}).fetch(function(items){return toCol.seed(items,function(){return fromCol.pendingUpserts(function(upserts){return toCol.upsert(_.pluck(upserts,"doc"),_.pluck(upserts,"base"),function(){return fromCol.pendingRemoves(function(removes){return async.eachSeries(removes,function(remove,cb2){return toCol.remove(remove,function(){return cb2()},cb2)},cb)},cb)},cb)},cb)},cb)},cb)}}(this),function(_this){return function(err){if(err){return error(err)}return success()}}(this))};exports.processFind=function(items,selector,options){var filtered;filtered=_.filter(items,compileDocumentSelector(selector));filtered=processNearOperator(selector,filtered);filtered=processGeoIntersectsOperator(selector,filtered);if(options&&options.sort){filtered.sort(compileSort(options.sort))}if(options&&options.skip){filtered=_.slice(filtered,options.skip)}if(options&&options.limit){filtered=_.take(filtered,options.limit)}if(options&&options.fields){filtered=exports.filterFields(filtered,options.fields)}return filtered};exports.filterFields=function(items,fields){if(fields==null){fields={}}if(_.keys(fields).length===0){return items}return _.map(items,function(item){var field,from,newItem,obj,path,pathElem,to,_i,_j,_k,_l,_len,_len1,_len2,_len3,_len4,_m,_ref,_ref1,_ref2,_ref3;newItem={};if(_.first(_.values(fields))===1){_ref=_.keys(fields).concat(["_id"]);for(_i=0,_len=_ref.length;_i<_len;_i++){field=_ref[_i];path=field.split(".");obj=item;for(_j=0,_len1=path.length;_j<_len1;_j++){pathElem=path[_j];if(obj){obj=obj[pathElem]}}if(obj==null){continue}from=item;to=newItem;_ref1=_.initial(path);for(_k=0,_len2=_ref1.length;_k<_len2;_k++){pathElem=_ref1[_k];to[pathElem]=to[pathElem]||{};to=to[pathElem];from=from[pathElem]}to[_.last(path)]=from[_.last(path)]}return newItem}else{item=_.cloneDeep(item);_ref2=_.keys(fields);for(_l=0,_len3=_ref2.length;_l<_len3;_l++){field=_ref2[_l];path=field.split(".");obj=item;_ref3=_.initial(path);for(_m=0,_len4=_ref3.length;_m<_len4;_m++){pathElem=_ref3[_m];if(obj){obj=obj[pathElem]}}if(obj==null){continue}delete obj[_.last(path)]}return item}})};exports.createUid=function(){return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(c){var r,v;r=Math.random()*16|0;v=c==="x"?r:r&3|8;return v.toString(16)})};processNearOperator=function(selector,list){var distances,geo,key,value;for(key in selector){value=selector[key];if(value!=null&&value["$near"]){geo=value["$near"]["$geometry"];if(geo.type!=="Point"){break}list=_.filter(list,function(doc){return doc[key]&&doc[key].type==="Point"});distances=_.map(list,function(doc){return{doc:doc,distance:getDistanceFromLatLngInM(geo.coordinates[1],geo.coordinates[0],doc[key].coordinates[1],doc[key].coordinates[0])}});distances=_.filter(distances,function(item){return item.distance>=0});distances=_.sortBy(distances,"distance");if(value["$near"]["$maxDistance"]){distances=_.filter(distances,function(item){return item.distance<=value["$near"]["$maxDistance"]})}list=_.pluck(distances,"doc")}}return list};pointInPolygon=function(point,polygon){if(!_.isEqual(_.first(polygon.coordinates[0]),_.last(polygon.coordinates[0]))){throw new Error("First must equal last")}if(point.coordinates[0]<Math.min.apply(this,_.map(polygon.coordinates[0],function(coord){return coord[0]}))){return false}if(point.coordinates[1]<Math.min.apply(this,_.map(polygon.coordinates[0],function(coord){return coord[1]}))){return false}if(point.coordinates[0]>Math.max.apply(this,_.map(polygon.coordinates[0],function(coord){return coord[0]}))){return false}if(point.coordinates[1]>Math.max.apply(this,_.map(polygon.coordinates[0],function(coord){return coord[1]}))){return false}return true};getDistanceFromLatLngInM=function(lat1,lng1,lat2,lng2){var R,a,c,d,dLat,dLng;R=6370986;dLat=deg2rad(lat2-lat1);dLng=deg2rad(lng2-lng1);a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(deg2rad(lat1))*Math.cos(deg2rad(lat2))*Math.sin(dLng/2)*Math.sin(dLng/2);c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));d=R*c;return d};deg2rad=function(deg){return deg*(Math.PI/180)};processGeoIntersectsOperator=function(selector,list){var geo,key,value;for(key in selector){value=selector[key];if(value!=null&&value["$geoIntersects"]){geo=value["$geoIntersects"]["$geometry"];if(geo.type!=="Polygon"){break}list=_.filter(list,function(doc){if(!doc[key]||doc[key].type!=="Point"){return false}return pointInPolygon(doc[key],geo)})}}return list};exports.regularizeUpsert=function(docs,bases,success,error){var item,items,_i,_len,_ref;if(_.isFunction(bases)){_ref=[void 0,bases,success],bases=_ref[0],success=_ref[1],error=_ref[2]}if(!_.isArray(docs)){docs=[docs];bases=[bases]}else{bases=bases||[]}items=_.map(docs,function(doc,i){return{doc:doc,base:i<bases.length?bases[i]:void 0}});for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];if(!item.doc._id){item.doc._id=exports.createUid()}if(item.base&&!item.base._id){throw new Error("Base needs _id")}if(item.base&&item.base._id!==item.doc._id){throw new Error("Base needs same _id")}}return[items,success,error]}},function(module,exports){module.exports=_},function(module,exports,__webpack_require__){LocalCollection={};EJSON=__webpack_require__(16);var _=__webpack_require__(1);var isArray=function(x){return _.isArray(x)&&!EJSON.isBinary(x)};var _anyIfArray=function(x,f){if(isArray(x))return _.any(x,f);return f(x)};var _anyIfArrayPlus=function(x,f){if(f(x))return true;return isArray(x)&&_.any(x,f)};var hasOperators=function(valueSelector){var theseAreOperators=undefined;for(var selKey in valueSelector){var thisIsOperator=selKey.substr(0,1)==="$";if(theseAreOperators===undefined){theseAreOperators=thisIsOperator}else if(theseAreOperators!==thisIsOperator){throw new Error("Inconsistent selector: "+valueSelector)}}return!!theseAreOperators};var compileValueSelector=function(valueSelector){if(valueSelector==null){return function(value){return _anyIfArray(value,function(x){return x==null})}}if(!_.isObject(valueSelector)){return function(value){return _anyIfArray(value,function(x){return x===valueSelector})}}if(valueSelector instanceof RegExp){return function(value){if(value===undefined)return false;return _anyIfArray(value,function(x){return valueSelector.test(x)})}}if(isArray(valueSelector)){return function(value){if(!isArray(value))return false;return _anyIfArrayPlus(value,function(x){return LocalCollection._f._equal(valueSelector,x)})}}if(hasOperators(valueSelector)){var operatorFunctions=[];_.each(valueSelector,function(operand,operator){if(!_.has(VALUE_OPERATORS,operator))throw new Error("Unrecognized operator: "+operator);operatorFunctions.push(VALUE_OPERATORS[operator](operand,valueSelector.$options))});return function(value){return _.all(operatorFunctions,function(f){return f(value)})}}return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._equal(valueSelector,x)})}};var LOGICAL_OPERATORS={$and:function(subSelector){if(!isArray(subSelector)||_.isEmpty(subSelector))throw Error("$and/$or/$nor must be nonempty array");var subSelectorFunctions=_.map(subSelector,compileDocumentSelector);return function(doc){return _.all(subSelectorFunctions,function(f){return f(doc)})}},$or:function(subSelector){if(!isArray(subSelector)||_.isEmpty(subSelector))throw Error("$and/$or/$nor must be nonempty array");var subSelectorFunctions=_.map(subSelector,compileDocumentSelector);return function(doc){return _.any(subSelectorFunctions,function(f){return f(doc)})}},$nor:function(subSelector){if(!isArray(subSelector)||_.isEmpty(subSelector))throw Error("$and/$or/$nor must be nonempty array");var subSelectorFunctions=_.map(subSelector,compileDocumentSelector);return function(doc){return _.all(subSelectorFunctions,function(f){return!f(doc)})}},$where:function(selectorValue){if(!(selectorValue instanceof Function)){selectorValue=Function("return "+selectorValue)}return function(doc){return selectorValue.call(doc)}}};var VALUE_OPERATORS={$in:function(operand){if(!isArray(operand))throw new Error("Argument to $in must be array");var index=null;if(_.all(operand,_.isString))index=_.indexBy(operand);return function(value){return _anyIfArrayPlus(value,function(x){if(_.isString(x)&&index!==null)return index[x]!=undefined;return _.any(operand,function(operandElt){return LocalCollection._f._equal(operandElt,x)})})}},$all:function(operand){if(!isArray(operand))throw new Error("Argument to $all must be array");return function(value){if(!isArray(value))return false;return _.all(operand,function(operandElt){return _.any(value,function(valueElt){return LocalCollection._f._equal(operandElt,valueElt)})})}},$lt:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)<0})}},$lte:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)<=0})}},$gt:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)>0})}},$gte:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)>=0})}},$ne:function(operand){return function(value){return!_anyIfArrayPlus(value,function(x){return LocalCollection._f._equal(x,operand)})}},$nin:function(operand){if(!isArray(operand))throw new Error("Argument to $nin must be array");var inFunction=VALUE_OPERATORS.$in(operand);return function(value){if(value===undefined)return true;return!inFunction(value)}},$exists:function(operand){return function(value){return operand===(value!==undefined)}},$mod:function(operand){var divisor=operand[0],remainder=operand[1];return function(value){return _anyIfArray(value,function(x){return x%divisor===remainder})}},$size:function(operand){return function(value){return isArray(value)&&operand===value.length}},$type:function(operand){return function(value){if(value===undefined)return false;return _anyIfArray(value,function(x){return LocalCollection._f._type(x)===operand})}},$regex:function(operand,options){if(options!==undefined){if(/[^gim]/.test(options))throw new Error("Only the i, m, and g regexp options are supported");var regexSource=operand instanceof RegExp?operand.source:operand;operand=new RegExp(regexSource,options)}else if(!(operand instanceof RegExp)){operand=new RegExp(operand)}return function(value){if(value===undefined)return false;return _anyIfArray(value,function(x){return operand.test(x)})}},$options:function(operand){return function(value){return true}},$elemMatch:function(operand){var matcher=compileDocumentSelector(operand);return function(value){if(!isArray(value))return false;return _.any(value,function(x){return matcher(x)})}},$not:function(operand){var matcher=compileValueSelector(operand);return function(value){return!matcher(value)}},$near:function(operand){return function(value){return true}},$geoIntersects:function(operand){return function(value){return true}}};LocalCollection._f={_type:function(v){if(typeof v==="number")return 1;if(typeof v==="string")return 2;if(typeof v==="boolean")return 8;if(isArray(v))return 4;if(v===null)return 10;if(v instanceof RegExp)return 11;if(typeof v==="function")return 13;if(v instanceof Date)return 9;if(EJSON.isBinary(v))return 5;if(v instanceof Meteor.Collection.ObjectID)return 7;return 3},_equal:function(a,b){return EJSON.equals(a,b,{keyOrderSensitive:true})},_typeorder:function(t){return[-1,1,2,3,4,5,-1,6,7,8,0,9,-1,100,2,100,1,8,1][t]},_cmp:function(a,b){if(a===undefined)return b===undefined?0:-1;if(b===undefined)return 1;var ta=LocalCollection._f._type(a);var tb=LocalCollection._f._type(b);var oa=LocalCollection._f._typeorder(ta);var ob=LocalCollection._f._typeorder(tb);if(oa!==ob)return oa<ob?-1:1;if(ta!==tb)throw Error("Missing type coercion logic in _cmp");if(ta===7){ta=tb=2;a=a.toHexString();b=b.toHexString()}if(ta===9){ta=tb=1;a=a.getTime();b=b.getTime()}if(ta===1)return a-b;if(tb===2)return a<b?-1:a===b?0:1;if(ta===3){var to_array=function(obj){var ret=[];for(var key in obj){ret.push(key);ret.push(obj[key])}return ret};return LocalCollection._f._cmp(to_array(a),to_array(b))}if(ta===4){for(var i=0;;i++){if(i===a.length)return i===b.length?0:-1;if(i===b.length)return 1;var s=LocalCollection._f._cmp(a[i],b[i]);if(s!==0)return s}}if(ta===5){if(a.length!==b.length)return a.length-b.length;for(i=0;i<a.length;i++){if(a[i]<b[i])return-1;if(a[i]>b[i])return 1}return 0}if(ta===8){if(a)return b?0:1;return b?-1:0}if(ta===10)return 0;if(ta===11)throw Error("Sorting not supported on regular expression");if(ta===13)throw Error("Sorting not supported on Javascript code");throw Error("Unknown type to sort")}};LocalCollection._matches=function(selector,doc){return LocalCollection._compileSelector(selector)(doc)};LocalCollection._makeLookupFunction=function(key){var dotLocation=key.indexOf(".");var first,lookupRest,nextIsNumeric;if(dotLocation===-1){first=key}else{first=key.substr(0,dotLocation);var rest=key.substr(dotLocation+1);lookupRest=LocalCollection._makeLookupFunction(rest);nextIsNumeric=/^\d+(\.|$)/.test(rest)}return function(doc){if(doc==null)return[undefined];var firstLevel=doc[first];if(!lookupRest)return[firstLevel];if(isArray(firstLevel)&&firstLevel.length===0)return[undefined];if(!isArray(firstLevel)||nextIsNumeric)firstLevel=[firstLevel];return Array.prototype.concat.apply([],_.map(firstLevel,lookupRest))}};var compileDocumentSelector=function(docSelector){var perKeySelectors=[];_.each(docSelector,function(subSelector,key){if(key.substr(0,1)==="$"){if(!_.has(LOGICAL_OPERATORS,key))throw new Error("Unrecognized logical operator: "+key);perKeySelectors.push(LOGICAL_OPERATORS[key](subSelector))}else{var lookUpByIndex=LocalCollection._makeLookupFunction(key);var valueSelectorFunc=compileValueSelector(subSelector);perKeySelectors.push(function(doc){var branchValues=lookUpByIndex(doc);return _.any(branchValues,valueSelectorFunc)})}});return function(doc){return _.all(perKeySelectors,function(f){return f(doc)})}};LocalCollection._compileSelector=function(selector){if(selector instanceof Function)return function(doc){return selector.call(doc)};if(LocalCollection._selectorIsId(selector)){return function(doc){return EJSON.equals(doc._id,selector)}}if(!selector||"_id"in selector&&!selector._id)return function(doc){return false};if(typeof selector==="boolean"||isArray(selector)||EJSON.isBinary(selector))throw new Error("Invalid selector: "+selector);return compileDocumentSelector(selector)};LocalCollection._compileSort=function(spec){var sortSpecParts=[];if(spec instanceof Array){for(var i=0;i<spec.length;i++){if(typeof spec[i]==="string"){sortSpecParts.push({lookup:LocalCollection._makeLookupFunction(spec[i]),ascending:true})}else{sortSpecParts.push({lookup:LocalCollection._makeLookupFunction(spec[i][0]),ascending:spec[i][1]!=="desc"})}}}else if(typeof spec==="object"){for(var key in spec){sortSpecParts.push({lookup:LocalCollection._makeLookupFunction(key),ascending:spec[key]>=0})}}else{throw Error("Bad sort specification: ",JSON.stringify(spec))}if(sortSpecParts.length===0)return function(){return 0};var reduceValue=function(branchValues,findMin){var reduced;var first=true;_.each(branchValues,function(branchValue){if(!isArray(branchValue))branchValue=[branchValue];if(isArray(branchValue)&&branchValue.length===0)branchValue=[undefined];_.each(branchValue,function(value){if(first){reduced=value;first=false}else{var cmp=LocalCollection._f._cmp(reduced,value);if(findMin&&cmp>0||!findMin&&cmp<0)reduced=value}})});return reduced};return function(a,b){for(var i=0;i<sortSpecParts.length;++i){var specPart=sortSpecParts[i];var aValue=reduceValue(specPart.lookup(a),specPart.ascending);var bValue=reduceValue(specPart.lookup(b),specPart.ascending);var compare=LocalCollection._f._cmp(aValue,bValue);if(compare!==0)return specPart.ascending?compare:-compare}return 0}};exports.compileDocumentSelector=compileDocumentSelector;exports.compileSort=LocalCollection._compileSort},function(module,exports,__webpack_require__){(function(global,setImmediate,process){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(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(true){!(__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return async}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}else{root.async=async}})()}).call(exports,__webpack_require__(5),__webpack_require__(13).setImmediate,__webpack_require__(6))},function(module,exports,__webpack_require__){var Collection,MemoryDb,async,compileSort,processFind,utils,_,__bind=function(fn,me){return function(){return fn.apply(me,arguments)}};_=__webpack_require__(1);async=__webpack_require__(3);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;module.exports=MemoryDb=function(){function MemoryDb(options,success){this.collections={};this.options=_.defaults(options,{safety:"clone"});if(success){success(this)}}MemoryDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.options);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};MemoryDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};MemoryDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return MemoryDb}();Collection=function(){function Collection(name,options){this._applySafety=__bind(this._applySafety,this);this.name=name;this.items={};this.upserts={};this.removes={};this.options=options||{}}Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(_this){return function(results){if(success!=null){return success(_this._applySafety(results.length>0?results[0]:null))}}}(this),error)};Collection.prototype._findFetch=function(selector,options,success,error){return setTimeout(function(_this){return function(){var results;results=processFind(_.values(_this.items),selector,options);if(success!=null){return success(_this._applySafety(results))}}}(this),0)};Collection.prototype._applySafety=function(items){if(!items){return items}if(_.isArray(items)){return _.map(items,this._applySafety)}if(this.options.safety==="clone"||!this.options.safety){return JSON.parse(JSON.stringify(items))}if(this.options.safety==="freeze"){Object.freeze(items);return items}throw new Error("Unsupported safety "+this.options.safety)};Collection.prototype.upsert=function(docs,bases,success,error){var item,items,_i,_len,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];items=JSON.parse(JSON.stringify(items));for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];if(item.base===void 0){if(this.upserts[item.doc._id]){item.base=this.upserts[item.doc._id].base}else{item.base=this.items[item.doc._id]||null}}this.items[item.doc._id]=item.doc;this.upserts[item.doc._id]=item}if(_.isArray(docs)){if(success){return success(this._applySafety(_.pluck(items,"doc")))}}else{if(success){return success(this._applySafety(_.pluck(items,"doc")[0]))}}};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}if(_.has(this.items,id)){this.removes[id]=this.items[id];delete this.items[id];delete this.upserts[id]}else{this.removes[id]={_id:id}}if(success!=null){return success()}};Collection.prototype.cache=function(docs,selector,options,success,error){var doc,docsMap,sort,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];this.cacheOne(doc)}docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return this.find(selector,options).fetch(function(_this){return function(results){var result,_j,_len1;for(_j=0,_len1=results.length;_j<_len1;_j++){result=results[_j];if(!docsMap[result._id]&&!_.has(_this.upserts,result._id)){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}delete _this.items[result._id]}}if(success!=null){return success()}}}(this),error)};Collection.prototype.pendingUpserts=function(success){return success(_.values(this.upserts))};Collection.prototype.pendingRemoves=function(success){return success(_.pluck(this.removes,"_id"))};Collection.prototype.resolveUpserts=function(upserts,success){var id,upsert,_i,_len;for(_i=0,_len=upserts.length;_i<_len;_i++){upsert=upserts[_i];id=upsert.doc._id;if(this.upserts[id]){if(_.isEqual(upsert.doc,this.upserts[id].doc)){delete this.upserts[id]}else{this.upserts[id].base=upsert.doc}}}if(success!=null){return success()}};Collection.prototype.resolveRemove=function(id,success){delete this.removes[id];if(success!=null){return success()}};Collection.prototype.seed=function(docs,success){var doc,_i,_len;if(!_.isArray(docs)){docs=[docs]}for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.items,doc._id)&&!_.has(this.removes,doc._id)){this.items[doc._id]=doc}}if(success!=null){return success()}};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success){var doc,existing,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.upserts,doc._id)&&!_.has(this.removes,doc._id)){existing=this.items[doc._id];if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){this.items[doc._id]=doc}}}if(success!=null){return success()}};Collection.prototype.uncache=function(selector,success,error){var compiledSelector,items;compiledSelector=utils.compileDocumentSelector(selector);items=_.filter(_.values(this.items),function(_this){return function(item){return _this.upserts[item._id]!=null||!compiledSelector(item)}}(this));this.items=_.object(_.pluck(items,"_id"),items);if(success!=null){return success()}};Collection.prototype.uncacheList=function(ids,success,error){var idIndex,items;idIndex=_.indexBy(ids);items=_.filter(_.values(this.items),function(_this){return function(item){return _this.upserts[item._id]!=null||!idIndex[item._id]}}(this));this.items=_.object(_.pluck(items,"_id"),items);if(success!=null){return success()}};return Collection}()},function(module,exports){var g;g=function(){return this}();try{g=g||Function("return this")()||(1,eval)("this")}catch(e){if(typeof window==="object")g=window}module.exports=g},function(module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[]};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")};process.umask=function(){return 0}},function(module,exports,__webpack_require__){var Collection,IDBStore,IndexedDb,async,compileSort,processFind,utils,_;_=__webpack_require__(1);async=__webpack_require__(3);IDBStore=__webpack_require__(17);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;module.exports=IndexedDb=function(){function IndexedDb(options,success,error){var ex;this.collections={};try{this.store=new IDBStore({dbVersion:1,storeName:"minimongo_"+options.namespace,keyPath:["col","doc._id"],autoIncrement:false,onStoreReady:function(_this){return function(){if(success){return success(_this)}}}(this),onError:error,indexes:[{name:"col",keyPath:"col",unique:false,multiEntry:false},{name:"col-state",keyPath:["col","state"],unique:false,multiEntry:false}]})}catch(_error){ex=_error;if(error){error(ex)}return}}IndexedDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.store);this[name]=collection;this.collections[name]=collection;if(success){return success()}};IndexedDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];return this.store.query(function(_this){return function(matches){var keys;keys=_.map(matches,function(m){return[m.col,m.doc._id]});if(keys.length>0){return _this.store.removeBatch(keys,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),{index:"col",keyRange:this.store.makeKeyRange({only:name}),onError:error})};IndexedDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return IndexedDb}();Collection=function(){function Collection(name,store){this.name=name;this.store=store}Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(results){if(success!=null){return success(results.length>0?results[0]:null)}},error)};Collection.prototype._findFetch=function(selector,options,success,error){return this.store.query(function(matches){matches=_.filter(matches,function(m){return m.state!=="removed"});if(success!=null){return success(processFind(_.pluck(matches,"doc"),selector,options))}},{index:"col",keyRange:this.store.makeKeyRange({only:this.name}),onError:error})};Collection.prototype.upsert=function(docs,bases,success,error){var items,keys,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];keys=_.map(items,function(_this){return function(item){return[_this.name,item.doc._id]}}(this));return this.store.getBatch(keys,function(_this){return function(records){var puts;puts=_.map(items,function(item,i){var base;if(item.base!==void 0){base=item.base}else if(records[i]&&records[i].doc&&records[i].state==="cached"){base=records[i].doc}else if(records[i]&&records[i].doc&&records[i].state==="upserted"){base=records[i].base}else{base=null}return{col:_this.name,state:"upserted",doc:item.doc,base:base}});return _this.store.putBatch(puts,function(){if(success){return success(docs)}},error)}}(this),error)};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}return this.store.get([this.name,id],function(_this){return function(record){if(record==null){record={col:_this.name,doc:{_id:id}}}record.state="removed";return _this.store.put(record,function(){if(success){return success(id)}},error)}}(this))};Collection.prototype.cache=function(docs,selector,options,success,error){var keys,puts,step2;step2=function(_this){return function(){var docsMap,sort;docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return _this.find(selector,options).fetch(function(results){var keys,removes;removes=[];keys=_.map(results,function(result){return[_this.name,result._id]});if(keys.length===0){if(success!=null){success()}return}return _this.store.getBatch(keys,function(records){var i,record,result,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];result=results[i];if(!docsMap[result._id]&&record&&record.state==="cached"){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}removes.push([_this.name,result._id])}}if(removes.length>0){return _this.store.removeBatch(removes,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}},error)},error)}}(this);if(docs.length===0){return step2()}keys=_.map(docs,function(_this){return function(doc){return[_this.name,doc._id]}}(this));puts=[];return this.store.getBatch(keys,function(_this){return function(records){var doc,i,record,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];doc=docs[i];if(record==null||record.state==="cached"){if(!record||!doc._rev||!record.doc._rev||doc._rev>record.doc._rev){puts.push({col:_this.name,state:"cached",doc:doc})}}}if(puts.length>0){return _this.store.putBatch(puts,step2,error)}else{return step2()}}}(this),error)};Collection.prototype.pendingUpserts=function(success,error){return this.store.query(function(matches){var upserts;upserts=_.map(matches,function(m){return{doc:m.doc,base:m.base||null}});if(success!=null){return success(upserts)}},{index:"col-state",keyRange:this.store.makeKeyRange({only:[this.name,"upserted"]}),onError:error})};Collection.prototype.pendingRemoves=function(success,error){return this.store.query(function(matches){if(success!=null){return success(_.pluck(_.pluck(matches,"doc"),"_id"))}},{index:"col-state",keyRange:this.store.makeKeyRange({only:[this.name,"removed"]}),onError:error})};Collection.prototype.resolveUpserts=function(upserts,success,error){var keys;keys=_.map(upserts,function(_this){return function(upsert){return[_this.name,upsert.doc._id]}}(this));return this.store.getBatch(keys,function(_this){return function(records){var i,puts,record,_i,_ref;puts=[];for(i=_i=0,_ref=upserts.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];if(record&&record.state==="upserted"){if(_.isEqual(record.doc,upserts[i].doc)){record.state="cached";puts.push(record)}else{record.base=upserts[i].doc;puts.push(record)}}}if(puts.length>0){return _this.store.putBatch(puts,function(){if(success){return success()}},error)}else{if(success){return success()}}}}(this),error)};Collection.prototype.resolveRemove=function(id,success,error){return this.store.get([this.name,id],function(_this){return function(record){if(!record){if(success!=null){success()}return}if(record.state==="removed"){return _this.store.remove([_this.name,id],function(){if(success!=null){return success()}},error)}}}(this))};Collection.prototype.seed=function(docs,success,error){var keys,puts;if(!_.isArray(docs)){docs=[docs]}keys=_.map(docs,function(_this){return function(doc){return[_this.name,doc._id]}}(this));puts=[];return this.store.getBatch(keys,function(_this){return function(records){var doc,i,record,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];doc=docs[i];if(record==null){puts.push({col:_this.name,state:"cached",doc:doc})}}if(puts.length>0){return _this.store.putBatch(puts,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),error)};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success,error){var keys,puts;keys=_.map(docs,function(_this){return function(doc){return[_this.name,doc._id]}}(this));puts=[];return this.store.getBatch(keys,function(_this){return function(records){var doc,i,record,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];doc=docs[i];if(record&&doc._rev&&record.doc._rev&&doc._rev<=record.doc._rev){continue}if(record==null){record={col:_this.name,state:"cached",doc:doc}}if(record.state==="cached"){record.doc=doc;puts.push(record)}}if(puts.length>0){return _this.store.putBatch(puts,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),error)};Collection.prototype.uncache=function(selector,success,error){var compiledSelector;compiledSelector=utils.compileDocumentSelector(selector);return this.store.query(function(_this){return function(matches){var keys;matches=_.filter(matches,function(m){return m.state==="cached"&&compiledSelector(m.doc)});keys=_.map(matches,function(m){return[_this.name,m.doc._id]});if(keys.length>0){return _this.store.removeBatch(keys,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),{index:"col",keyRange:this.store.makeKeyRange({only:this.name}),onError:error})};Collection.prototype.uncacheList=function(ids,success,error){var idIndex;idIndex=_.indexBy(ids);error=error||function(){};return this.store.query(function(_this){return function(matches){var keys;matches=_.filter(matches,function(m){return m.state==="cached"&&idIndex[m.doc._id]});keys=_.map(matches,function(m){return[_this.name,m.doc._id]});if(keys.length>0){return _this.store.removeBatch(keys,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),{index:"col",keyRange:this.store.makeKeyRange({only:this.name}),onError:error})};return Collection}()},function(module,exports,__webpack_require__){var Collection,WebSQLDb,async,compileSort,doNothing,processFind,utils,_;_=__webpack_require__(1);async=__webpack_require__(3);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;doNothing=function(){};module.exports=WebSQLDb=function(){function WebSQLDb(options,success,error){var checkV2,ex,migrateToV1,migrateToV2;this.collections={};try{this.db=window.openDatabase("minimongo_"+options.namespace,"","Minimongo:"+options.namespace,5*1024*1024);if(!this.db){return error(new Error("Failed to create database"))}}catch(_error){ex=_error;if(error){error(ex)}return}migrateToV1=function(tx){return tx.executeSql("CREATE TABLE docs (\n col TEXT NOT NULL,\n id TEXT NOT NULL,\n state TEXT NOT NULL,\n doc TEXT,\n PRIMARY KEY (col, id));",[],doNothing,function(tx,err){return error(err)})};migrateToV2=function(tx){return tx.executeSql("ALTER TABLE docs ADD COLUMN base TEXT;",[],doNothing,function(tx,err){return error(err)})};checkV2=function(_this){return function(){if(_this.db.version==="1.0"){return _this.db.changeVersion("1.0","2.0",migrateToV2,error,function(){if(success){return success(_this)}})}else if(_this.db.version!=="2.0"){return error("Unknown db version "+_this.db.version)}else{if(success){return success(_this)}}}}(this);if(!this.db.version){this.db.changeVersion("","1.0",migrateToV1,error,checkV2)}else{checkV2()}return this.db}WebSQLDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.db);this[name]=collection;this.collections[name]=collection;if(success){return success()}};WebSQLDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];return this.db.transaction(function(tx){return tx.executeSql("DELETE FROM docs WHERE col = ?",[name],success,function(tx,err){return error(err)})},error)};WebSQLDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return WebSQLDb}();Collection=function(){function Collection(name,db){this.name=name;this.db=db}Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(results){if(success!=null){return success(results.length>0?results[0]:null)}},error)};Collection.prototype._findFetch=function(selector,options,success,error){error=error||function(){};return this.db.readTransaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ?",[_this.name],function(tx,results){var docs,i,row,_i,_ref;docs=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);if(row.state!=="removed"){docs.push(JSON.parse(row.doc))}}if(success!=null){return success(processFind(docs,selector,options))}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.upsert=function(docs,bases,success,error){var items,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];error=error||function(){};return this.db.transaction(function(_this){return function(tx){var ids;ids=_.map(items,function(item){return item.doc._id});bases={};return async.eachSeries(ids,function(id,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,id],function(tx2,results){var row;tx=tx2;if(results.rows.length>0){row=results.rows.item(0);if(row.state==="upserted"){bases[row.id]=row.base?JSON.parse(row.base):null}else if(row.state==="cached"){bases[row.id]=JSON.parse(row.doc)}}return callback()},function(tx,err){return error(err)})},function(){var base,id,item,_i,_len,_results;_results=[];for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];id=item.doc._id;if(item.base!==void 0){base=item.base}else if(bases[id]){base=bases[id]}else{base=null}_results.push(tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc, base) VALUES (?, ?, ?, ?, ?)",[_this.name,item.doc._id,"upserted",JSON.stringify(item.doc),JSON.stringify(base)],doNothing,function(tx,err){return error(err)}))}return _results})}}(this),error,function(){if(success){return success(docs)}})};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}error=error||function(){};return this.db.transaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,id],function(tx,results){if(results.rows.length>0){return tx.executeSql('UPDATE docs SET state="removed" WHERE col = ? AND id = ?',[_this.name,id],function(){if(success){return success(id)}},function(tx,err){return error(err)})}else{return tx.executeSql("INSERT INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,id,"removed",JSON.stringify({_id:id})],function(){if(success){return success(id)}},function(tx,err){return error(err)})}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.cache=function(docs,selector,options,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(docs,function(doc,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,doc._id],function(tx,results){var existing;if(results.rows.length===0||results.rows.item(0).state==="cached"){existing=results.rows.length>0?JSON.parse(results.rows.item(0).doc):null;if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){return tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,doc._id,"cached",JSON.stringify(doc)],function(){return callback()},function(tx,err){return error(err)})}else{return callback()}}else{return callback()}},function(tx,err){return error(err)})},function(err){var docsMap,sort;if(err){if(error){error(err)}return}docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return _this.find(selector,options).fetch(function(results){return _this.db.transaction(function(tx){return async.eachSeries(results,function(result,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,result._id],function(tx,rows){if(!docsMap[result._id]&&rows.rows.length>0&&rows.rows.item(0).state==="cached"){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){return callback()}if(!options.sort){return callback()}}return tx.executeSql("DELETE FROM docs WHERE col = ? AND id = ?",[_this.name,result._id],function(){return callback()},function(tx,err){return error(err)})}else{return callback()}},function(tx,err){return error(err)})},function(err){if(err!=null){if(error!=null){error(err)}return}if(success!=null){return success()}})},error)},error)})}}(this),error)};Collection.prototype.pendingUpserts=function(success,error){error=error||function(){};return this.db.readTransaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND state = ?",[_this.name,"upserted"],function(tx,results){var docs,i,row,_i,_ref;docs=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);docs.push({doc:JSON.parse(row.doc),base:row.base?JSON.parse(row.base):null})}if(success!=null){return success(docs)}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.pendingRemoves=function(success,error){error=error||function(){};return this.db.readTransaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND state = ?",[_this.name,"removed"],function(tx,results){var docs,i,row,_i,_ref;docs=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);docs.push(JSON.parse(row.doc)._id)}if(success!=null){return success(docs)}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.resolveUpserts=function(upserts,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(upserts,function(upsert,cb){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,upsert.doc._id],function(tx,results){if(results.rows.length>0&&results.rows.item(0).state==="upserted"){if(_.isEqual(JSON.parse(results.rows.item(0).doc),upsert.doc)){tx.executeSql('UPDATE docs SET state="cached" WHERE col = ? AND id = ?',[_this.name,upsert.doc._id],doNothing,function(tx,err){return error(err)});return cb()}else{tx.executeSql("UPDATE docs SET base=? WHERE col = ? AND id = ?",[JSON.stringify(upsert.doc),_this.name,upsert.doc._id],doNothing,function(tx,err){return error(err)});return cb()}}else{return cb()}},function(tx,err){return error(err)})},function(err){if(err){return error(err)}if(success){return success()}})}}(this),error)};Collection.prototype.resolveRemove=function(id,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return tx.executeSql('DELETE FROM docs WHERE state="removed" AND col = ? AND id = ?',[_this.name,id],function(){if(success){return success(id)}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.seed=function(docs,success,error){if(!_.isArray(docs)){docs=[docs]}error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(docs,function(doc,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,doc._id],function(tx,results){if(results.rows.length===0){return tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,doc._id,"cached",JSON.stringify(doc)],function(){return callback()},function(tx,err){return error(err)})}else{return callback()}},function(tx,err){return error(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success()}}})}}(this),error)};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(docs,function(doc,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,doc._id],function(tx,results){var existing;if(results.rows.length===0||results.rows.item(0).state==="cached"){existing=results.rows.length>0?JSON.parse(results.rows.item(0).doc):null;if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){return tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,doc._id,"cached",JSON.stringify(doc)],function(){return callback()},function(tx,err){return callback(err)})}else{return callback()}}else{return callback()}},function(tx,err){return callback(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success(docs)}}})}}(this),error)};Collection.prototype.uncache=function(selector,success,error){var compiledSelector;compiledSelector=utils.compileDocumentSelector(selector);error=error||function(){};return this.db.transaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND state = ?",[_this.name,"cached"],function(tx,results){var doc,i,row,toRemove,_i,_ref;toRemove=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);doc=JSON.parse(row.doc);if(compiledSelector(doc)){toRemove.push(doc._id)}}return async.eachSeries(toRemove,function(id,callback){return tx.executeSql('DELETE FROM docs WHERE state="cached" AND col = ? AND id = ?',[_this.name,id],function(){return callback()},function(tx,err){return error(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success()}}})},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.uncacheList=function(ids,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(ids,function(id,callback){return tx.executeSql('DELETE FROM docs WHERE state="cached" AND col = ? AND id = ?',[_this.name,id],function(){return callback()},function(tx,err){return error(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success()}}})}}(this),error)};return Collection}()},function(module,exports,__webpack_require__){var Collection,LocalStorageDb,async,compileSort,processFind,utils,_;_=__webpack_require__(1);async=__webpack_require__(3);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;module.exports=LocalStorageDb=function(){function LocalStorageDb(options,success){this.collections={};if(options&&options.namespace&&window.localStorage){this.namespace=options.namespace}if(success){success(this)}}LocalStorageDb.prototype.addCollection=function(name,success,error){var collection,namespace;if(this.namespace){namespace=this.namespace+"."+name}collection=new Collection(name,namespace);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};LocalStorageDb.prototype.removeCollection=function(name,success,error){var i,key,keyToMatch,keys,_i,_j,_len,_ref;if(this.namespace&&window.localStorage){keys=[];for(i=_i=0,_ref=window.localStorage.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){keys.push(window.localStorage.key(i))}for(_j=0,_len=keys.length;_j<_len;_j++){key=keys[_j];keyToMatch=this.namespace+"."+name;if(key.substring(0,keyToMatch.length)===keyToMatch){window.localStorage.removeItem(key)}}}delete this[name];delete this.collections[name];if(success!=null){return success()}};LocalStorageDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return LocalStorageDb}();Collection=function(){function Collection(name,namespace){this.name=name;this.namespace=namespace;this.items={};this.upserts={};this.removes={};if(window.localStorage&&namespace!=null){this.loadStorage()}}Collection.prototype.loadStorage=function(){var base,i,item,key,removeItems,upsertKeys,_i,_j,_len,_ref;this.itemNamespace=this.namespace+"_";for(i=_i=0,_ref=window.localStorage.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){key=window.localStorage.key(i);if(key.substring(0,this.itemNamespace.length)===this.itemNamespace){item=JSON.parse(window.localStorage[key]);this.items[item._id]=item}}upsertKeys=window.localStorage[this.namespace+"upserts"]?JSON.parse(window.localStorage[this.namespace+"upserts"]):[];for(_j=0,_len=upsertKeys.length;_j<_len;_j++){key=upsertKeys[_j];this.upserts[key]={doc:this.items[key]};base=window.localStorage[this.namespace+"upsertbase_"+key]?JSON.parse(window.localStorage[this.namespace+"upsertbase_"+key]):null;this.upserts[key].base=base}removeItems=window.localStorage[this.namespace+"removes"]?JSON.parse(window.localStorage[this.namespace+"removes"]):[];return this.removes=_.object(_.pluck(removeItems,"_id"),removeItems)};Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(results){if(success!=null){return success(results.length>0?results[0]:null)}},error)};Collection.prototype._findFetch=function(selector,options,success,error){if(success!=null){return success(processFind(_.cloneDeep(_.values(this.items)),selector,options))}};Collection.prototype.upsert=function(docs,bases,success,error){var item,items,_i,_len,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];items=JSON.parse(JSON.stringify(items));for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];if(item.base===void 0){if(this.upserts[item.doc._id]){item.base=this.upserts[item.doc._id].base}else{item.base=this.items[item.doc._id]||null}}item=_.cloneDeep(item);this._putItem(item.doc);this._putUpsert(item)}if(success){return success(docs)}};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}if(_.has(this.items,id)){this._putRemove(this.items[id]);this._deleteItem(id);this._deleteUpsert(id)}else{this._putRemove({_id:id})}if(success!=null){return success()}};Collection.prototype._putItem=function(doc){this.items[doc._id]=doc;if(this.namespace){return window.localStorage[this.itemNamespace+doc._id]=JSON.stringify(doc)}};Collection.prototype._deleteItem=function(id){delete this.items[id];if(this.namespace){return window.localStorage.removeItem(this.itemNamespace+id)}};Collection.prototype._putUpsert=function(upsert){this.upserts[upsert.doc._id]=upsert;if(this.namespace){window.localStorage[this.namespace+"upserts"]=JSON.stringify(_.keys(this.upserts));return window.localStorage[this.namespace+"upsertbase_"+upsert.doc._id]=JSON.stringify(upsert.base)}};Collection.prototype._deleteUpsert=function(id){delete this.upserts[id];if(this.namespace){return window.localStorage[this.namespace+"upserts"]=JSON.stringify(_.keys(this.upserts))}};Collection.prototype._putRemove=function(doc){this.removes[doc._id]=doc;if(this.namespace){return window.localStorage[this.namespace+"removes"]=JSON.stringify(_.values(this.removes))}};Collection.prototype._deleteRemove=function(id){delete this.removes[id];if(this.namespace){return window.localStorage[this.namespace+"removes"]=JSON.stringify(_.values(this.removes))}};Collection.prototype.cache=function(docs,selector,options,success,error){var doc,docsMap,sort,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];this.cacheOne(doc)}docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return this.find(selector,options).fetch(function(_this){return function(results){var result,_j,_len1;for(_j=0,_len1=results.length;_j<_len1;_j++){result=results[_j];if(!docsMap[result._id]&&!_.has(_this.upserts,result._id)){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}_this._deleteItem(result._id)}}if(success!=null){return success()}}}(this),error)};Collection.prototype.pendingUpserts=function(success){return success(_.values(this.upserts))};Collection.prototype.pendingRemoves=function(success){return success(_.pluck(this.removes,"_id"))};Collection.prototype.resolveUpserts=function(upserts,success){var upsert,_i,_len;for(_i=0,_len=upserts.length;_i<_len;_i++){upsert=upserts[_i];if(this.upserts[upsert.doc._id]){if(_.isEqual(upsert.doc,this.upserts[upsert.doc._id].doc)){this._deleteUpsert(upsert.doc._id)}else{this.upserts[upsert.doc._id].base=upsert.doc;this._putUpsert(this.upserts[upsert.doc._id])}}}if(success!=null){return success()}};Collection.prototype.resolveRemove=function(id,success){this._deleteRemove(id);if(success!=null){return success()}};Collection.prototype.seed=function(docs,success){var doc,_i,_len;if(!_.isArray(docs)){docs=[docs]}for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.items,doc._id)&&!_.has(this.removes,doc._id)){this._putItem(doc)}}if(success!=null){return success()}};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success){var doc,existing,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.upserts,doc._id)&&!_.has(this.removes,doc._id)){existing=this.items[doc._id];if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){this._putItem(doc)}}}if(success!=null){return success()}};Collection.prototype.uncache=function(selector,success,error){var compiledSelector,item,_i,_len,_ref;compiledSelector=utils.compileDocumentSelector(selector);_ref=_.values(this.items);for(_i=0,_len=_ref.length;_i<_len;_i++){item=_ref[_i];if(this.upserts[item._id]==null&&compiledSelector(item)){this._deleteItem(item._id)}}if(success!=null){return success()}};Collection.prototype.uncacheList=function(ids,success,error){var id,_i,_len;for(_i=0,_len=ids.length;_i<_len;_i++){id=ids[_i];if(this.upserts[id]==null){this._deleteItem(id)}}if(success!=null){return success()}};return Collection}()},function(module,exports,__webpack_require__){var HybridCollection,HybridDb,processFind,utils,_;_=__webpack_require__(1);processFind=__webpack_require__(0).processFind;utils=__webpack_require__(0);module.exports=HybridDb=function(){function HybridDb(localDb,remoteDb){this.localDb=localDb;this.remoteDb=remoteDb;this.collections={}}HybridDb.prototype.addCollection=function(name,options,success,error){var collection,_ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}collection=new HybridCollection(name,this.localDb[name],this.remoteDb[name],options);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};HybridDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};HybridDb.prototype.upload=function(success,error){var cols,uploadCols;cols=_.values(this.collections);uploadCols=function(cols,success,error){var col;col=_.first(cols);if(col){return col.upload(function(){return uploadCols(_.rest(cols),success,error)},function(err){return error(err)})}else{return success()}};return uploadCols(cols,success,error)};HybridDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return HybridDb}();HybridCollection=function(){function HybridCollection(name,localCol,remoteCol,options){this.name=name;this.localCol=localCol;this.remoteCol=remoteCol;this.options=options||{};_.defaults(this.options,{cacheFind:true,cacheFindOne:true,interim:true,useLocalOnRemoteError:true,shortcut:false,timeout:0,sortUpserts:null})}HybridCollection.prototype.find=function(selector,options){if(options==null){options={}}return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};HybridCollection.prototype.findOne=function(selector,options,success,error){var step2,_ref;if(options==null){options={}}if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}_.defaults(options,this.options);step2=function(_this){return function(localDoc){var findOptions;findOptions=_.cloneDeep(options);findOptions.interim=false;findOptions.cacheFind=options.cacheFindOne;if(selector._id){findOptions.limit=1}else{delete findOptions.limit}return _this.find(selector,findOptions).fetch(function(data){if(data.length>0){if(!_.isEqual(localDoc,data[0])){return success(data[0])}}else{return success(null)}},error)}}(this);if(options.interim||options.shortcut){return this.localCol.findOne(selector,options,function(localDoc){if(localDoc){success(_.cloneDeep(localDoc));if(options.shortcut){return}}return step2(localDoc)},error)}else{return step2()}};HybridCollection.prototype._findFetch=function(selector,options,success,error){var localSuccess,step2;_.defaults(options,this.options);step2=function(_this){return function(localData){var remoteError,remoteOptions,remoteSuccess,timedOut,timer;remoteOptions=_.cloneDeep(options);if(options.cacheFind){delete remoteOptions.fields}timer=null;timedOut=false;remoteSuccess=function(remoteData){var cacheSuccess,data;if(timer){clearTimeout(timer)}if(timedOut){if(options.cacheFind){_this.localCol.cache(remoteData,selector,options,function(){},error)}return}if(options.cacheFind){cacheSuccess=function(){var localSuccess2;localSuccess2=function(localData2){if(!_.isEqual(localData,localData2)){return success(localData2)}};return _this.localCol.find(selector,options).fetch(localSuccess2,error)};return _this.localCol.cache(remoteData,selector,options,cacheSuccess,error)}else{data=remoteData;return _this.localCol.pendingRemoves(function(removes){var removesMap;if(removes.length>0){removesMap=_.object(_.map(removes,function(id){return[id,id]}));data=_.filter(remoteData,function(doc){return!_.has(removesMap,doc._id)})}return _this.localCol.pendingUpserts(function(upserts){var upsertsMap;if(upserts.length>0){upsertsMap=_.object(_.map(upserts,function(u){return u.doc._id}),_.map(upserts,function(u){return u.doc._id}));data=_.filter(data,function(doc){return!_.has(upsertsMap,doc._id)});data=data.concat(_.pluck(upserts,"doc"));data=processFind(data,selector,options)}if(!_.isEqual(localData,data)){return success(data)}},error)},error)}};remoteError=function(err){if(timer){clearTimeout(timer)}if(timedOut){return}if(!options.interim){if(options.useLocalOnRemoteError){return _this.localCol.find(selector,options).fetch(success,error)}else{if(error){return error(err)}}}else{}};if(options.timeout){timer=setTimeout(function(){timer=null;timedOut=true;if(!options.interim){if(options.useLocalOnRemoteError){return _this.localCol.find(selector,options).fetch(success,error)}else{if(error){return error(new Error("Remote timed out"))}}}else{}},options.timeout)}return _this.remoteCol.find(selector,remoteOptions).fetch(remoteSuccess,remoteError)}}(this);if(options.interim){localSuccess=function(localData){success(localData);return step2(localData)};return this.localCol.find(selector,options).fetch(localSuccess,error)}else{return step2()}};HybridCollection.prototype.upsert=function(docs,bases,success,error){return this.localCol.upsert(docs,bases,function(result){if(_.isFunction(bases)){success=bases}return typeof success==="function"?success(docs):void 0},error)};HybridCollection.prototype.remove=function(id,success,error){return this.localCol.remove(id,function(){if(success!=null){return success()}},error)};HybridCollection.prototype.upload=function(success,error){var uploadRemoves,uploadUpserts;uploadUpserts=function(_this){return function(upserts,success,error){var upsert;upsert=_.first(upserts);if(upsert){return _this.remoteCol.upsert(upsert.doc,upsert.base,function(remoteDoc){return _this.localCol.resolveUpserts([upsert],function(){if(remoteDoc){return _this.localCol.cacheOne(remoteDoc,function(){return uploadUpserts(_.rest(upserts),success,error)},error)}else{return _this.localCol.remove(upsert.doc._id,function(){return _this.localCol.resolveRemove(upsert.doc._id,function(){return uploadUpserts(_.rest(upserts),success,error)},error)},error)}},error)},function(err){if(err.status===410||err.status===403){return _this.localCol.remove(upsert.doc._id,function(){return _this.localCol.resolveRemove(upsert.doc._id,function(){if(err.status===410){return uploadUpserts(_.rest(upserts),success,error)}else{return error(err)}},error)},error)}else{return error(err)}})}else{return success()}}}(this);uploadRemoves=function(_this){return function(removes,success,error){var remove;remove=_.first(removes);if(remove){return _this.remoteCol.remove(remove,function(){return _this.localCol.resolveRemove(remove,function(){return uploadRemoves(_.rest(removes),success,error)},error)},function(err){if(err.status===410||err.status===403){return _this.localCol.resolveRemove(remove,function(){if(err.status===410){return uploadRemoves(_.rest(removes),success,error)}else{return error(err)}},error)}else{return error(err)}},error)}else{return success()}}}(this);return this.localCol.pendingUpserts(function(_this){return function(upserts){if(_this.options.sortUpserts){upserts.sort(_this.options.sortUpserts)}return uploadUpserts(upserts,function(){return _this.localCol.pendingRemoves(function(removes){return uploadRemoves(removes,success,error)},error)},error)}}(this),error)};return HybridCollection}()},function(module,exports,__webpack_require__){module.exports=__webpack_require__(12)},function(module,exports,__webpack_require__){exports.MemoryDb=__webpack_require__(4);exports.LocalStorageDb=__webpack_require__(9);exports.IndexedDb=__webpack_require__(7);exports.WebSQLDb=__webpack_require__(8);exports.RemoteDb=__webpack_require__(18);exports.HybridDb=__webpack_require__(10);exports.ReplicatingDb=__webpack_require__(21);exports.utils=__webpack_require__(0)},function(module,exports,__webpack_require__){var apply=Function.prototype.apply;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)};exports.clearTimeout=exports.clearInterval=function(timeout){if(timeout){timeout.close()}};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id)};exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout()},msecs)}};__webpack_require__(14);exports.setImmediate=setImmediate;exports.clearImmediate=clearImmediate},function(module,exports,__webpack_require__){(function(global,process){(function(global,undefined){"use strict";if(global.setImmediate){return}var nextHandle=1;var tasksByHandle={};var currentlyRunningATask=false;var doc=global.document;var registerImmediate;function setImmediate(callback){if(typeof callback!=="function"){callback=new Function(""+callback)}var args=new Array(arguments.length-1);for(var i=0;i<args.length;i++){args[i]=arguments[i+1]}var task={callback:callback,args:args};tasksByHandle[nextHandle]=task;registerImmediate(nextHandle);return nextHandle++}function clearImmediate(handle){delete tasksByHandle[handle]}function run(task){var callback=task.callback;var args=task.args;switch(args.length){case 0:callback();break;case 1:callback(args[0]);break;case 2:callback(args[0],args[1]);break;case 3:callback(args[0],args[1],args[2]);break;default:callback.apply(undefined,args);break}}function runIfPresent(handle){if(currentlyRunningATask){setTimeout(runIfPresent,0,handle)}else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=true;try{run(task)}finally{clearImmediate(handle);currentlyRunningATask=false}}}}function installNextTickImplementation(){registerImmediate=function(handle){process.nextTick(function(){runIfPresent(handle)})}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=true;var oldOnMessage=global.onmessage;global.onmessage=function(){postMessageIsAsynchronous=false};global.postMessage("","*");global.onmessage=oldOnMessage;return postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$";var onGlobalMessage=function(event){if(event.source===global&&typeof event.data==="string"&&event.data.indexOf(messagePrefix)===0){runIfPresent(+event.data.slice(messagePrefix.length))}};if(global.addEventListener){global.addEventListener("message",onGlobalMessage,false)}else{global.attachEvent("onmessage",onGlobalMessage)}registerImmediate=function(handle){global.postMessage(messagePrefix+handle,"*")}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)};registerImmediate=function(handle){channel.port2.postMessage(handle)}}function installReadyStateChangeImplementation(){var html=doc.documentElement;registerImmediate=function(handle){var script=doc.createElement("script");script.onreadystatechange=function(){runIfPresent(handle);script.onreadystatechange=null;html.removeChild(script);script=null};html.appendChild(script)}}function installSetTimeoutImplementation(){registerImmediate=function(handle){setTimeout(runIfPresent,0,handle)}}var attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global;if({}.toString.call(global.process)==="[object process]"){installNextTickImplementation()}else if(canUsePostMessage()){installPostMessageImplementation()}else if(global.MessageChannel){installMessageChannelImplementation()}else if(doc&&"onreadystatechange"in doc.createElement("script")){installReadyStateChangeImplementation()}else{installSetTimeoutImplementation()}attachTo.setImmediate=setImmediate;attachTo.clearImmediate=clearImmediate})(typeof self==="undefined"?typeof global==="undefined"?this:global:self)}).call(exports,__webpack_require__(5),__webpack_require__(6))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__;/*!
* Bowser - a browser detector
* https://github.com/ded/bowser
* MIT License | (c) Dustin Diaz 2014
*/
!function(name,definition){if(typeof module!="undefined"&&module.exports)module.exports["browser"]=definition();else if(true)!(__WEBPACK_AMD_DEFINE_FACTORY__=definition,__WEBPACK_AMD_DEFINE_RESULT__=typeof __WEBPACK_AMD_DEFINE_FACTORY__==="function"?__WEBPACK_AMD_DEFINE_FACTORY__.call(exports,__webpack_require__,exports,module):__WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__));else this[name]=definition()}("bowser",function(){var t=true;function detect(ua){function getFirstMatch(regex){var match=ua.match(regex);return match&&match.length>1&&match[1]||""}function getSecondMatch(regex){var match=ua.match(regex);return match&&match.length>1&&match[2]||""}var iosdevice=getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase(),likeAndroid=/like android/i.test(ua),android=!likeAndroid&&/android/i.test(ua),edgeVersion=getFirstMatch(/edge\/(\d+(\.\d+)?)/i),versionIdentifier=getFirstMatch(/version\/(\d+(\.\d+)?)/i),tablet=/tablet/i.test(ua),mobile=!tablet&&/[^-]mobi/i.test(ua),result;if(/opera|opr/i.test(ua)){result={name:"Opera",opera:t,version:versionIdentifier||getFirstMatch(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i)}}else if(/windows phone/i.test(ua)){result={name:"Windows Phone",windowsphone:t};if(edgeVersion){result.msedge=t;result.version=edgeVersion}else{result.msie=t;result.version=getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i)}}else if(/msie|trident/i.test(ua)){result={name:"Internet Explorer",msie:t,version:getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i)}}else if(/chrome.+? edge/i.test(ua)){result={name:"Microsoft Edge",msedge:t,version:edgeVersion}}else if(/chrome|crios|crmo/i.test(ua)){result={name:"Chrome",chrome:t,version:getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}}else if(iosdevice){result={name:iosdevice=="iphone"?"iPhone":iosdevice=="ipad"?"iPad":"iPod"};if(versionIdentifier){result.version=versionIdentifier}}else if(/sailfish/i.test(ua)){result={name:"Sailfish",sailfish:t,version:getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}}else if(/seamonkey\//i.test(ua)){result={name:"SeaMonkey",seamonkey:t,version:getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i)}}else if(/firefox|iceweasel/i.test(ua)){result={name:"Firefox",firefox:t,version:getFirstMatch(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i)};if(/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)){result.firefoxos=t}}else if(/silk/i.test(ua)){result={name:"Amazon Silk",silk:t,version:getFirstMatch(/silk\/(\d+(\.\d+)?)/i)}}else if(android){result={name:"Android",version:versionIdentifier}}else if(/phantom/i.test(ua)){result={name:"PhantomJS",phantom:t,version:getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i)}}else if(/blackberry|\bbb\d+/i.test(ua)||/rim\stablet/i.test(ua)){result={name:"BlackBerry",blackberry:t,version:versionIdentifier||getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}}else if(/(web|hpw)os/i.test(ua)){result={name:"WebOS",webos:t,version:versionIdentifier||getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)};/touchpad\//i.test(ua)&&(result.touchpad=t)}else if(/bada/i.test(ua)){result={name:"Bada",bada:t,version:getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i)}}else if(/tizen/i.test(ua)){result={name:"Tizen",tizen:t,version:getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||versionIdentifier}}else if(/safari/i.test(ua)){result={name:"Safari",safari:t,version:versionIdentifier}}else{result={name:getFirstMatch(/^(.*)\/(.*) /),version:getSecondMatch(/^(.*)\/(.*) /)}}if(!result.msedge&&/(apple)?webkit/i.test(ua)){result.name=result.name||"Webkit";result.webkit=t;if(!result.version&&versionIdentifier){result.version=versionIdentifier}}else if(!result.opera&&/gecko\//i.test(ua)){result.name=result.name||"Gecko";result.gecko=t;result.version=result.version||getFirstMatch(/gecko\/(\d+(\.\d+)?)/i)}if(!result.msedge&&(android||result.silk)){result.android=t}else if(iosdevice){result[iosdevice]=t;result.ios=t}var osVersion="";if(result.windowsphone){osVersion=getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i)}else if(iosdevice){osVersion=getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i);osVersion=osVersion.replace(/[_\s]/g,".")}else if(android){osVersion=getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i)}else if(result.webos){osVersion=getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i)}else if(result.blackberry){osVersion=getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i)}else if(result.bada){osVersion=getFirstMatch(/bada\/(\d+(\.\d+)*)/i)}else if(result.tizen){osVersion=getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i)}if(osVersion){result.osversion=osVersion}var osMajorVersion=osVersion.split(".")[0];if(tablet||iosdevice=="ipad"||android&&(osMajorVersion==3||osMajorVersion==4&&!mobile)||result.silk){result.tablet=t}else if(mobile||iosdevice=="iphone"||iosdevice=="ipod"||android||result.blackberry||result.webos||result.bada){result.mobile=t}if(result.msedge||result.msie&&result.version>=10||result.chrome&&result.version>=20||result.firefox&&result.version>=20||result.safari&&result.version>=6||result.opera&&result.version>=10||result.ios&&result.osversion&&result.osversion.split(".")[0]>=6||result.blackberry&&result.version>=10.1){result.a=t}else if(result.msie&&result.version<10||result.chrome&&result.version<20||result.firefox&&result.version<20||result.safari&&result.version<6||result.opera&&result.version<10||result.ios&&result.osversion&&result.osversion.split(".")[0]<6){result.c=t}else result.x=t;return result}var bowser=detect(typeof navigator!=="undefined"?navigator.userAgent:"");bowser.test=function(browserList){for(var i=0;i<browserList.length;++i){var browserItem=browserList[i];if(typeof browserItem==="string"){if(browserItem in bowser){return true}}}return false};bowser._detect=detect;return bowser})},function(module,exports,__webpack_require__){var _=__webpack_require__(1);EJSON={};var customTypes={};EJSON.addType=function(name,factory){if(_.has(customTypes,name))throw new Error("Type "+name+" already present");customTypes[name]=factory};var builtinConverters=[{matchJSONValue:function(obj){return _.has(obj,"$date")&&_.size(obj)===1},matchObject:function(obj){return obj instanceof Date},toJSONValue:function(obj){return{$date:obj.getTime()}},fromJSONValue:function(obj){return new Date(obj.$date)}},{matchJSONValue:function(obj){return _.has(obj,"$binary")&&_.size(obj)===1},matchObject:function(obj){return typeof Uint8Array!=="undefined"&&obj instanceof Uint8Array||obj&&_.has(obj,"$Uint8ArrayPolyfill")},toJSONValue:function(obj){return{$binary:EJSON._base64Encode(obj)}},fromJSONValue:function(obj){return EJSON._base64Decode(obj.$binary)}},{matchJSONValue:function(obj){return _.has(obj,"$escape")&&_.size(obj)===1},matchObject:function(obj){if(_.isEmpty(obj)||_.size(obj)>2){return false}return _.any(builtinConverters,function(converter){return converter.matchJSONValue(obj)})},toJSONValue:function(obj){var newObj={};_.each(obj,function(value,key){newObj[key]=EJSON.toJSONValue(value)});return{$escape:newObj}},fromJSONValue:function(obj){var newObj={};_.each(obj.$escape,function(value,key){newObj[key]=EJSON.fromJSONValue(value)});return newObj}},{matchJSONValue:function(obj){return _.has(obj,"$type")&&_.has(obj,"$value")&&_.size(obj)===2},matchObject:function(obj){return EJSON._isCustomType(obj)},toJSONValue:function(obj){return{$type:obj.typeName(),$value:obj.toJSONValue()}},fromJSONValue:function(obj){var typeName=obj.$type;var converter=customTypes[typeName];return converter(obj.$value)}}];EJSON._isCustomType=function(obj){return obj&&typeof obj.toJSONValue==="function"&&typeof obj.typeName==="function"&&_.has(customTypes,obj.typeName())};var adjustTypesToJSONValue=EJSON._adjustTypesToJSONValue=function(obj){if(obj===null)return null;var maybeChanged=toJSONValueHelper(obj);if(maybeChanged!==undefined)return maybeChanged;_.each(obj,function(value,key){if(typeof value!=="object"&&value!==undefined)return;var changed=toJSONValueHelper(value);if(changed){obj[key]=changed;return}adjustTypesToJSONValue(value)});return obj};var toJSONValueHelper=function(item){for(var i=0;i<builtinConverters.length;i++){var converter=builtinConverters[i];if(converter.matchObject(item)){return converter.toJSONValue(item)}}return undefined};EJSON.toJSONValue=function(item){var changed=toJSONValueHelper(item);if(changed!==undefined)return changed;if(typeof item==="object"){item=EJSON.clone(item);adjustTypesToJSONValue(item)}return item};var adjustTypesFromJSONValue=EJSON._adjustTypesFromJSONValue=function(obj){if(obj===null)return null;var maybeChanged=fromJSONValueHelper(obj);if(maybeChanged!==obj)return maybeChanged;_.each(obj,function(value,key){if(typeof value==="object"){var changed=fromJSONValueHelper(value);if(value!==changed){obj[key]=changed;return}adjustTypesFromJSONValue(value)}});return obj};var fromJSONValueHelper=function(value){if(typeof value==="object"&&value!==null){if(_.size(value)<=2&&_.all(value,function(v,k){return typeof k==="string"&&k.substr(0,1)==="$"})){for(var i=0;i<builtinConverters.length;i++){var converter=builtinConverters[i];if(converter.matchJSONValue(value)){return converter.fromJSONValue(value)}}}}return value};EJSON.fromJSONValue=function(item){var changed=fromJSONValueHelper(item);if(changed===item&&typeof item==="object"){item=EJSON.clone(item);adjustTypesFromJSONValue(item);return item}else{return changed}};EJSON.stringify=function(item){return JSON.stringify(EJSON.toJSONValue(item))};EJSON.parse=function(item){return EJSON.fromJSONValue(JSON.parse(item))};EJSON.isBinary=function(obj){return typeof Uint8Array!=="undefined"&&obj instanceof Uint8Array||obj&&obj.$Uint8ArrayPolyfill};EJSON.equals=function(a,b,options){var i;var keyOrderSensitive=!!(options&&options.keyOrderSensitive);if(a===b)return true;if(!a||!b)return false;if(!(typeof a==="object"&&typeof b==="object"))return false;if(a instanceof Date&&b instanceof Date)return a.valueOf()===b.valueOf();if(EJSON.isBinary(a)&&EJSON.isBinary(b)){if(a.length!==b.length)return false;for(i=0;i<a.length;i++){if(a[i]!==b[i])return false}return true}if(typeof a.equals==="function")return a.equals(b,options);if(a instanceof Array){if(!(b instanceof Array))return false;if(a.length!==b.length)return false;for(i=0;i<a.length;i++){if(!EJSON.equals(a[i],b[i],options))return false}return true}var ret;if(keyOrderSensitive){var bKeys=[];_.each(b,function(val,x){bKeys.push(x)});i=0;ret=_.all(a,function(val,x){if(i>=bKeys.length){return false}if(x!==bKeys[i]){return false}if(!EJSON.equals(val,b[bKeys[i]],options)){return false}i++;return true});return ret&&i===bKeys.length}else{i=0;ret=_.all(a,function(val,key){if(!_.has(b,key)){return false}if(!EJSON.equals(val,b[key],options)){return false}i++;return true});return ret&&_.size(b)===i}};EJSON.clone=function(v){var ret;if(typeof v!=="object")return v;if(v===null)return null;if(v instanceof Date)return new Date(v.getTime());if(EJSON.isBinary(v)){ret=EJSON.newBinary(v.length);for(var i=0;i<v.length;i++){ret[i]=v[i]}return ret}if(_.isArray(v)||_.isArguments(v)){ret=[];for(i=0;i<v.length;i++)ret[i]=EJSON.clone(v[i]);return ret}if(typeof v.clone==="function"){return v.clone()}ret={};_.each(v,function(value,key){ret[key]=EJSON.clone(value)});return ret};module.exports=EJSON},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__;/**
* @license IDBWrapper - A cross-browser wrapper for IndexedDB
* Version 1.7.1
* Copyright (c) 2011 - 2016 Jens Arps
* http://jensarps.de/
*
* Licensed under the MIT (X11) license
*/
(function(name,definition,global){"use strict";if(true){!(__WEBPACK_AMD_DEFINE_FACTORY__=definition,__WEBPACK_AMD_DEFINE_RESULT__=typeof __WEBPACK_AMD_DEFINE_FACTORY__==="function"?__WEBPACK_AMD_DEFINE_FACTORY__.call(exports,__webpack_require__,exports,module):__WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}else if(typeof module!=="undefined"&&module.exports){module.exports=definition()}else{global[name]=definition()}})("IDBStore",function(){"use strict";var defaultErrorHandler=function(error){throw error};var defaultSuccessHandler=function(){};var defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:true,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]};var IDBStore=function(kwArgs,onStoreReady){if(typeof onStoreReady=="undefined"&&typeof kwArgs=="function"){onStoreReady=kwArgs}if(Object.prototype.toString.call(kwArgs)!="[object Object]"){kwArgs={}}for(var key in defaults){this[key]=typeof kwArgs[key]!="undefined"?kwArgs[key]:defaults[key]}this.dbName=this.storePrefix+this.storeName;this.dbVersion=parseInt(this.dbVersion,10)||1;onStoreReady&&(this.onStoreReady=onStoreReady);var env=typeof window=="object"?window:self;var availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0];this.idb=env[this.implementation];this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange;this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"};this.openDB()};var proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion);var preventSuccessCallback=false;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent)){this.onError(new Error("The version number provided is lower than the existing one."))}else{var error;if(errorEvent.target.error){error=errorEvent.target.error}else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;if("errorCode"in errorEvent.target){errorMessage+=" with error code "+errorEvent.target.errorCode}error=new Error(errorMessage)}this.onError(error)}}.bind(this);openRequest.onsuccess=function(event){if(preventSuccessCallback){return}if(this.db){this.onStoreReady();return}this.db=event.target.result;if(typeof this.db.version=="string"){this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));return}if(!this.db.objectStoreNames.contains(this.storeName)){this.onError(new Error("Object store couldn't be created."));return}var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName){preventSuccessCallback=true;this.onError(new Error("Cannot create index: No index name given."));return}this.normalizeIndexData(indexData);if(this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);var complies=this.indexComplies(actualIndex,indexData);if(!complies){preventSuccessCallback=true;this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))}existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else{preventSuccessCallback=true;this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))}},this);if(existingIndexes.length){preventSuccessCallback=true;this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))}preventSuccessCallback||this.onStoreReady()}.bind(this);openRequest.onupgradeneeded=function(event){this.db=event.target.result;if(this.db.objectStoreNames.contains(this.storeName)){this.store=event.target.transaction.objectStore(this.storeName)}else{var optionalParameters={autoIncrement:this.autoIncrement};if(this.keyPath!==null){optionalParameters.keyPath=this.keyPath}this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName){preventSuccessCallback=true;this.onError(new Error("Cannot create index: No index name given."))}this.normalizeIndexData(indexData);if(this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);var complies=this.indexComplies(actualIndex,indexData);if(!complies){this.store.deleteIndex(indexName);this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})}existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else{this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})}},this);if(existingIndexes.length){existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess;deleteRequest.onerror=onError}else{onError(new Error("Browser does not support IndexedDB deleteDatabase!"))}},put:function(key,value,onSuccess,onError){if(this.keyPath!==null){onError=onSuccess;onSuccess=value;value=key}onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null,putRequest;var putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);putTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};putTransaction.onabort=onError;putTransaction.onerror=onError;if(this.keyPath!==null){this._addIdPropertyIfNeeded(value);putRequest=putTransaction.objectStore(this.storeName).put(value)}else{putRequest=putTransaction.objectStore(this.storeName).put(value,key)}putRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};putRequest.onerror=onError;return putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null;var getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};getTransaction.onabort=onError;getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};getRequest.onerror=onError;return getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null;var removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};removeTransaction.onabort=onError;removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName)["delete"](key);deleteRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};deleteRequest.onerror=onError;return removeTransaction},batch:function(dataArray,onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);if(Object.prototype.toString.call(dataArray)!="[object Array]"){onError(new Error("dataArray argument must be of type Array."))}else if(dataArray.length===0){return onSuccess(true)}var count=dataArray.length;var called=false;var hasSuccess=false;var batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(hasSuccess)};batchTransaction.onabort=onError;batchTransaction.onerror=onError;var onItemSuccess=function(){count--;if(count===0&&!called){called=true;hasSuccess=true}};dataArray.forEach(function(operation){var type=operation.type;var key=operation.key;var value=operation.value;var onItemError=function(err){batchTransaction.abort();if(!called){called=true;onError(err,type,key)}};if(type=="remove"){var deleteRequest=batchTransaction.objectStore(this.storeName)["delete"](key);deleteRequest.onsuccess=onItemSuccess;deleteRequest.onerror=onItemError}else if(type=="put"){var putRequest;if(this.keyPath!==null){this._addIdPropertyIfNeeded(value);putRequest=batchTransaction.objectStore(this.storeName).put(value)}else{putRequest=batchTransaction.objectStore(this.storeName).put(value,key)}putRequest.onsuccess=onItemSuccess;putRequest.onerror=onItemError}},this);return batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){if(typeof options=="function"){onSuccess=options;onError=onSuccess;options={}}onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);options||(options={});if(Object.prototype.toString.call(dataArray)!="[object Array]"){onError(new Error("dataArray argument must be of type Array."))}var keyField=options.keyField||this.keyPath;var count=dataArray.length;var called=false;var hasSuccess=false;var index=0;var batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){if(hasSuccess){onSuccess(dataArray)}else{onError(false)}};batchTransaction.onabort=onError;batchTransaction.onerror=onError;var onItemSuccess=function(event){var record=dataArray[index++];record[keyField]=event.target.result;count--;if(count===0&&!called){called=true;hasSuccess=true}};dataArray.forEach(function(record){var key=record.key;var onItemError=function(err){batchTransaction.abort();if(!called){called=true;onError(err)}};var putRequest;if(this.keyPath!==null){this._addIdPropertyIfNeeded(record);putRequest=batchTransaction.objectStore(this.storeName).put(record)}else{putRequest=batchTransaction.objectStore(this.storeName).put(record,key)}putRequest.onsuccess=onItemSuccess;putRequest.onerror=onItemError},this);return batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);arrayType||(arrayType="sparse");if(Object.prototype.toString.call(keyArray)!="[object Array]"){onError(new Error("keyArray argument must be of type Array."))}else if(keyArray.length===0){return onSuccess([])}var data=[];var count=keyArray.length;var called=false;var hasSuccess=false;var result=null;var batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};batchTransaction.onabort=onError;batchTransaction.onerror=onError;var onItemSuccess=function(event){if(event.target.result||arrayType=="dense"){data.push(event.target.result)}else if(arrayType=="sparse"){data.length++}count--;if(count===0){called=true;hasSuccess=true;result=data}};keyArray.forEach(function(key){var onItemError=function(err){called=true;result=err;onError(err);batchTransaction.abort()};var getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess;getRequest.onerror=onItemError},this);return batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);var store=getAllTransaction.objectStore(this.storeName);if(store.getAll){this._getAllNative(getAllTransaction,store,onSuccess,onError)}else{this._getAllCursor(getAllTransaction,store,onSuccess,onError)}return getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=false,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};getAllTransaction.onabort=onError;getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=false,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};getAllTransaction.onabort=onError;getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;if(cursor){all.push(cursor.value);cursor["continue"]()}else{hasSuccess=true;result=all}};cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null;var clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};clearTransaction.onabort=onError;clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();clearRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};clearRequest.onerror=onError;return clearTransaction},_addIdPropertyIfNeeded:function(dataObj){if(typeof dataObj[this.keyPath]=="undefined"){dataObj[this.keyPath]=this._insertIdCount+++Date.now()}},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name;indexData.unique=!!indexData.unique;indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){var complies=["keyPath","unique","multiEntry"].every(function(key){if(key=="multiEntry"&&actual[key]===undefined&&expected[key]===false){return true}if(key=="keyPath"&&Object.prototype.toString.call(expected[key])=="[object Array]"){var exp=expected.keyPath;var act=actual.keyPath;if(typeof act=="string"){return exp.toString()==act}if(!(typeof act.contains=="function"||typeof act.indexOf=="function")){return false}if(act.length!==exp.length){return false}for(var i=0,m=exp.length;i<m;i++){if(!(act.contains&&act.contains(exp[i])||act.indexOf(exp[i]!==-1))){return false}}return true}return expected[key]==actual[key]});return complies},iterate:function(onItem,options){options=mixin({index:null,order:"ASC",autoContinue:true,filterDuplicates:false,keyRange:null,writeAccess:false,onEnd:null,onError:defaultErrorHandler,limit:Infinity,offset:0,allowItemRejection:false},options||{});var directionType=options.order.toLowerCase()=="desc"?"PREV":"NEXT";if(options.filterDuplicates){directionType+="_NO_DUPLICATE"}var hasSuccess=false;var cursorTransaction=this.db.transaction([this.storeName],this.consts[options.writeAccess?"READ_WRITE":"READ_ONLY"]);var cursorTarget=cursorTransaction.objectStore(this.storeName);if(options.index){cursorTarget=cursorTarget.index(options.index)}var recordCount=0;cursorTransaction.oncomplete=function(){if(!hasSuccess){options.onError(null);return}if(options.onEnd){options.onEnd()}else{onItem(null)}};cursorTransaction.onabort=options.onError;cursorTransaction.onerror=options.onError;var cursorRequest=cursorTarget.openCursor(options.keyRange,this.consts[directionType]);cursorRequest.onerror=options.onError;cursorRequest.onsuccess=function(event){var cursor=event.target.result;if(cursor){if(options.offset){cursor.advance(options.offset);options.offset=0}else{var onItemReturn=onItem(cursor.value,cursor,cursorTransaction);if(!options.allowItemRejection||onItemReturn!==false){recordCount++}if(options.autoContinue){if(recordCount+options.offset<options.limit){cursor["continue"]()}else{hasSuccess=true}}}}else{hasSuccess=true}};return cursorTransaction},query:function(onSuccess,options){var result=[],processedItems=0;options=options||{};options.autoContinue=true;options.writeAccess=false;options.allowItemRejection=!!options.filter;options.onEnd=function(){onSuccess(result,processedItems)};return this.iterate(function(item){processedItems++;var accept=options.filter?options.filter(item):true;if(accept!==false){result.push(item)}return accept},options)},count:function(onSuccess,options){options=mixin({index:null,keyRange:null},options||{});var onError=options.onError||defaultErrorHandler;var hasSuccess=false,result=null;var cursorTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);cursorTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};cursorTransaction.onabort=onError;cursorTransaction.onerror=onError;var cursorTarget=cursorTransaction.objectStore(this.storeName);if(options.index){cursorTarget=cursorTarget.index(options.index)}var countRequest=cursorTarget.count(options.keyRange);countRequest.onsuccess=function(evt){hasSuccess=true;result=evt.target.result};countRequest.onError=onError;return cursorTransaction},makeKeyRange:function(options){var keyRange,hasLower=typeof options.lower!="undefined",hasUpper=typeof options.upper!="undefined",isOnly=typeof options.only!="undefined";switch(true){case isOnly:keyRange=this.keyRange.only(options.only);break;case hasLower&&hasUpper:keyRange=this.keyRange.bound(options.lower,options.upper,options.excludeLower,options.excludeUpper);break;case hasLower:keyRange=this.keyRange.lowerBound(options.lower,options.excludeLower);break;case hasUpper:keyRange=this.keyRange.upperBound(options.upper,options.excludeUpper);break;default:throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.')}return keyRange}};var empty={};function mixin(target,source){var name,s;for(name in source){s=source[name];if(s!==empty[name]&&s!==target[name]){target[name]=s}}return target}function hasVersionError(errorEvent){if("error"in errorEvent.target){return errorEvent.target.error.name=="VersionError"}else if("errorCode"in errorEvent.target){return errorEvent.target.errorCode==12}return false}IDBStore.prototype=proto;IDBStore.version=proto.version;return IDBStore},this)},function(module,exports,__webpack_require__){var $,Collection,RemoteDb,async,jQueryHttpClient,utils,_;_=__webpack_require__(1);$=__webpack_require__(19);async=__webpack_require__(3);utils=__webpack_require__(0);jQueryHttpClient=__webpack_require__(20);module.exports=RemoteDb=function(){function RemoteDb(url,client,httpClient){this.url=url;this.client=client;this.collections={};this.httpClient=httpClient||jQueryHttpClient}RemoteDb.prototype.addCollection=function(name,options,success,error){var collection,url,_ref;if(options==null){options={}}if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}url=options.url||this.url+name;collection=new Collection(name,url,this.client,this.httpClient);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};RemoteDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};RemoteDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return RemoteDb}();Collection=function(){function Collection(name,url,client,httpClient){this.name=name;this.url=url;this.client=client;this.httpClient=httpClient}Collection.prototype.find=function(selector,options){if(options==null){options={}}return{fetch:function(_this){return function(success,error){var params;params={};if(options.sort){params.sort=JSON.stringify(options.sort)}if(options.limit){params.limit=options.limit}if(options.skip){params.skip=options.skip}if(options.fields){params.fields=JSON.stringify(options.fields)}if(_this.client){params.client=_this.client}params.selector=JSON.stringify(selector||{});if(typeof navigator!=="undefined"&&navigator!==null&&navigator.userAgent.toLowerCase().indexOf("android 2.3")!==-1){params._=(new Date).getTime()}return _this.httpClient("GET",_this.url,params,null,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var params,_ref;if(options==null){options={}}if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}params={};if(options.sort){params.sort=JSON.stringify(options.sort)}params.limit=1;if(this.client){params.client=this.client}params.selector=JSON.stringify(selector||{});if(typeof navigator!=="undefined"&&navigator!==null&&navigator.userAgent.toLowerCase().indexOf("android 2.3")!==-1){params._=(new Date).getTime()}return this.httpClient("GET",this.url,params,null,function(results){if(results&&results.length>0){return success(results[0])}else{return success(null)}},error)};Collection.prototype.upsert=function(docs,bases,success,error){var items,results,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];if(!this.client){throw new Error("Client required to upsert")}results=[];return async.eachLimit(items,8,function(_this){return function(item,cb){var params;if(!item.doc._id){item.doc._id=utils.createUid()}params={client:_this.client};if(typeof navigator!=="undefined"&&navigator!==null&&navigator.userAgent.toLowerCase().indexOf("android 2.3")!==-1){params._=(new Date).getTime()}if(item.base){return _this.httpClient("PATCH",_this.url+"/"+item.doc._id,params,item,function(result){results.push(result);return cb()},function(err){return cb(err)})}else{return _this.httpClient("POST",_this.url,params,item.doc,function(result){results.push(result);return cb()},function(err){return cb(err)})}}}(this),function(err){if(err){if(error){error(err)}return}if(_.isArray(docs)){if(success){return success(results)}}else{if(success){return success(results[0])}}})};Collection.prototype.remove=function(id,success,error){var params;if(!this.client){throw new Error("Client required to remove")}params={client:this.client};return this.httpClient("DELETE",this.url+"/"+id,params,null,success,function(err){if(err.status===410){return success()}else{return error(err)}})};return Collection}()},function(module,exports){module.exports=$},function(module,exports){module.exports=function(method,url,params,data,success,error){var fullUrl,req;fullUrl=url+"?"+$.param(params);if(method==="GET"){req=$.ajax(fullUrl,{dataType:"json",timeout:18e4})}else if(method==="DELETE"){req=$.ajax(fullUrl,{type:"DELETE",timeout:6e4})}else if(method==="POST"||method==="PATCH"){req=$.ajax(fullUrl,{data:JSON.stringify(data),contentType:"application/json",timeout:6e4,type:method})}else{throw new Error("Unknown method "+method)}req.done(function(response,textStatus,jqXHR){return success(response||null)});return req.fail(function(jqXHR,textStatus,errorThrown){if(error){return error(jqXHR)}})}},function(module,exports,__webpack_require__){var Collection,ReplicatingDb,compileSort,utils,_;_=__webpack_require__(1);utils=__webpack_require__(0);compileSort=__webpack_require__(2).compileSort;module.exports=ReplicatingDb=function(){function ReplicatingDb(masterDb,replicaDb){this.collections={};this.masterDb=masterDb;this.replicaDb=replicaDb}ReplicatingDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.masterDb[name],this.replicaDb[name]);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};ReplicatingDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};ReplicatingDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return ReplicatingDb}();Collection=function(){function Collection(name,masterCol,replicaCol){this.name=name;this.masterCol=masterCol;this.replicaCol=replicaCol}Collection.prototype.find=function(selector,options){return this.masterCol.find(selector,options)};Collection.prototype.findOne=function(selector,options,success,error){return this.masterCol.findOne(selector,options,success,error)};Collection.prototype.upsert=function(docs,bases,success,error){var items,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];return this.masterCol.upsert(_.pluck(items,"doc"),_.pluck(items,"base"),function(_this){return function(){return _this.replicaCol.upsert(_.pluck(items,"doc"),_.pluck(items,"base"),function(results){return success(docs)},error)}}(this),error)};Collection.prototype.remove=function(id,success,error){return this.masterCol.remove(id,function(_this){return function(){return _this.replicaCol.remove(id,success,error)}}(this),error)};Collection.prototype.cache=function(docs,selector,options,success,error){var docsMap,sort;docsMap=_.indexBy(docs,"_id");if(options.sort){sort=compileSort(options.sort)}return this.masterCol.find(selector,options).fetch(function(_this){return function(results){var doc,performCaches,performUncaches,result,resultsMap,toCache,toUncache,_i,_j,_len,_len1;resultsMap=_.indexBy(results,"_id");toCache=[];for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];result=resultsMap[doc._id];if(!result){toCache.push(doc);continue}if(doc._rev&&result._rev&&doc._rev<=result._rev){continue}if(!_.isEqual(doc,result)){toCache.push(doc)}}toUncache=[];for(_j=0,_len1=results.length;_j<_len1;_j++){result=results[_j];if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}if(!docsMap[result._id]){toUncache.push(result._id)}}performCaches=function(next){if(toCache.length>0){return _this.masterCol.cacheList(toCache,function(){return _this.replicaCol.cacheList(toCache,function(){return next()},error)},error)}else{return next()}};performUncaches=function(next){if(toUncache.length>0){return _this.masterCol.uncacheList(toUncache,function(){return _this.replicaCol.uncacheList(toUncache,function(){return next()},error)},error)}else{return next()}};return performCaches(function(){return performUncaches(function(){if(success!=null){success()}})})}}(this),error)};Collection.prototype.pendingUpserts=function(success,error){return this.masterCol.pendingUpserts(success,error)};Collection.prototype.pendingRemoves=function(success,error){return this.masterCol.pendingRemoves(success,error)};Collection.prototype.resolveUpserts=function(upserts,success,error){return this.masterCol.resolveUpserts(upserts,function(_this){return function(){return _this.replicaCol.resolveUpserts(upserts,success,error)}}(this),error)};Collection.prototype.resolveRemove=function(id,success,error){return this.masterCol.resolveRemove(id,function(_this){return function(){return _this.replicaCol.resolveRemove(id,success,error)}}(this),error)};Collection.prototype.seed=function(docs,success,error){return this.masterCol.seed(docs,function(_this){return function(){return _this.replicaCol.seed(docs,success,error)}}(this),error)};Collection.prototype.cacheOne=function(doc,success,error){return this.masterCol.cacheOne(doc,function(_this){return function(){return _this.replicaCol.cacheOne(doc,success,error)}}(this),error)};Collection.prototype.cacheList=function(docs,success,error){return this.masterCol.cacheList(docs,function(_this){return function(){return _this.replicaCol.cacheList(docs,success,error)}}(this),error)};Collection.prototype.uncache=function(selector,success,error){return this.masterCol.uncache(selector,function(_this){return function(){return _this.replicaCol.uncache(selector,success,error)}}(this),error)};Collection.prototype.uncacheList=function(ids,success,error){return this.masterCol.uncacheList(ids,function(_this){return function(){return _this.replicaCol.uncacheList(ids,success,error)}}(this),error)};return Collection}()}]);