Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

lokijs

Package Overview
Dependencies
Maintainers
1
Versions
92
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lokijs - npm Package Compare versions

Comparing version 1.3.10 to 1.3.11

.editorconfig

2

build/loki-indexed-adapter.min.js

@@ -1,1 +0,1 @@

(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.LokiIndexedAdapter=factory()}})(this,function(){return function(){function IndexedAdapter(appname){this.app="loki";if(typeof appname!=="undefined"){this.app=appname}this.catalog=null;if(!this.checkAvailability()){console.error("indexedDB does not seem to be supported for your environment")}}IndexedAdapter.prototype.checkAvailability=function(){if(window&&window.indexedDB)return true;return false};IndexedAdapter.prototype.loadDatabase=function(dbname,callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.loadDatabase(dbname,callback)});return}this.catalog.getAppKey(appName,dbname,function(result){if(typeof callback==="function"){if(result.id===0){console.warn("loki indexeddb adapter could not find database");callback(null);return}callback(result.val)}else{console.log(result.val)}})};IndexedAdapter.prototype.loadKey=IndexedAdapter.prototype.loadDatabase;IndexedAdapter.prototype.saveDatabase=function(dbname,dbstring,callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;cat.setAppKey(appName,dbname,dbstring,callback)});return}this.catalog.setAppKey(appName,dbname,dbstring,callback)};IndexedAdapter.prototype.saveKey=IndexedAdapter.prototype.saveDatabase;IndexedAdapter.prototype.deleteDatabase=function(dbname){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.deleteDatabase(dbname)});return}this.catalog.getAppKey(appName,dbname,function(result){var id=result.id;if(id!==0){adapter.catalog.deleteAppKey(id)}})};IndexedAdapter.prototype.deleteKey=IndexedAdapter.prototype.deleteDatabase;IndexedAdapter.prototype.getDatabaseList=function(callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.getDatabaseList(callback)});return}this.catalog.getAppKeys(appName,function(results){var names=[];for(var idx=0;idx<results.length;idx++){names.push(results[idx].key)}if(typeof callback==="function"){callback(names)}else{names.forEach(function(obj){console.log(obj)})}})};IndexedAdapter.prototype.getKeyList=IndexedAdapter.prototype.getDatabaseList;IndexedAdapter.prototype.getCatalogSummary=function(callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.getCatalogSummary(callback)});return}this.catalog.getAllKeys(function(results){var entries=[];var obj,size,oapp,okey,oval;for(var idx=0;idx<results.length;idx++){obj=results[idx];oapp=obj.app||"";okey=obj.key||"";oval=obj.val||"";size=oapp.length*2+okey.length*2+oval.length+1;entries.push({app:obj.app,key:obj.key,size:size})}if(typeof callback==="function"){callback(entries)}else{entries.forEach(function(obj){console.log(obj)})}})};function LokiCatalog(callback){this.db=null;this.initializeLokiCatalog(callback)}LokiCatalog.prototype.initializeLokiCatalog=function(callback){var openRequest=indexedDB.open("LokiCatalog",1);var cat=this;openRequest.onupgradeneeded=function(e){var thisDB=e.target.result;if(thisDB.objectStoreNames.contains("LokiAKV")){thisDB.deleteObjectStore("LokiAKV")}if(!thisDB.objectStoreNames.contains("LokiAKV")){var objectStore=thisDB.createObjectStore("LokiAKV",{keyPath:"id",autoIncrement:true});objectStore.createIndex("app","app",{unique:false});objectStore.createIndex("key","key",{unique:false});objectStore.createIndex("appkey","appkey",{unique:true})}};openRequest.onsuccess=function(e){cat.db=e.target.result;if(typeof callback==="function")callback(cat)};openRequest.onerror=function(e){throw e}};LokiCatalog.prototype.getAppKey=function(app,key,callback){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var index=store.index("appkey");var appkey=app+","+key;var request=index.get(appkey);request.onsuccess=function(usercallback){return function(e){var lres=e.target.result;if(lres===null||typeof lres==="undefined"){lres={id:0,success:false}}if(typeof usercallback==="function"){usercallback(lres)}else{console.log(lres)}}}(callback);request.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({id:0,success:false})}else{throw e}}}(callback)};LokiCatalog.prototype.getAppKeyById=function(id,callback,data){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var request=store.get(id);request.onsuccess=function(data,usercallback){return function(e){if(typeof usercallback==="function"){usercallback(e.target.result,data)}else{console.log(e.target.result)}}}(data,callback)};LokiCatalog.prototype.setAppKey=function(app,key,val,callback){var transaction=this.db.transaction(["LokiAKV"],"readwrite");var store=transaction.objectStore("LokiAKV");var index=store.index("appkey");var appkey=app+","+key;var request=index.get(appkey);request.onsuccess=function(e){var res=e.target.result;if(res===null||res===undefined){res={app:app,key:key,appkey:app+","+key,val:val}}else{res.val=val}var requestPut=store.put(res);requestPut.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({success:false})}else{console.error("LokiCatalog.setAppKey (set) onerror");console.error(request.error)}}}(callback);requestPut.onsuccess=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({success:true})}}}(callback)};request.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({success:false})}else{console.error("LokiCatalog.setAppKey (get) onerror");console.error(request.error)}}}(callback)};LokiCatalog.prototype.deleteAppKey=function(id,callback){var transaction=this.db.transaction(["LokiAKV"],"readwrite");var store=transaction.objectStore("LokiAKV");var request=store.delete(id);request.onsuccess=function(usercallback){return function(evt){if(typeof usercallback==="function")usercallback({success:true})}}(callback);request.onerror=function(usercallback){return function(evt){if(typeof usercallback==="function"){usercallback(false)}else{console.error("LokiCatalog.deleteAppKey raised onerror");console.error(request.error)}}}(callback)};LokiCatalog.prototype.getAppKeys=function(app,callback){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var index=store.index("app");var singleKeyRange=IDBKeyRange.only(app);var cursor=index.openCursor(singleKeyRange);var localdata=[];cursor.onsuccess=function(data,callback){return function(e){var cursor=e.target.result;if(cursor){var currObject=cursor.value;data.push(currObject);cursor.continue()}else{if(typeof callback==="function"){callback(data)}else{console.log(data)}}}}(localdata,callback);cursor.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback(null)}else{console.error("LokiCatalog.getAppKeys raised onerror");console.error(e)}}}(callback)};LokiCatalog.prototype.getAllKeys=function(callback){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var cursor=store.openCursor();var localdata=[];cursor.onsuccess=function(data,callback){return function(e){var cursor=e.target.result;if(cursor){var currObject=cursor.value;data.push(currObject);cursor.continue()}else{if(typeof callback==="function"){callback(data)}else{console.log(data)}}}}(localdata,callback);cursor.onerror=function(usercallback){return function(e){if(typeof usercallback==="function")usercallback(null)}}(callback)};return IndexedAdapter}()});
(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.LokiIndexedAdapter=factory()}})(this,function(){return function(){function IndexedAdapter(appname){this.app="loki";if(typeof appname!=="undefined"){this.app=appname}this.catalog=null;if(!this.checkAvailability()){throw new Error("indexedDB does not seem to be supported for your environment")}}IndexedAdapter.prototype.checkAvailability=function(){if(window&&window.indexedDB)return true;return false};IndexedAdapter.prototype.loadDatabase=function(dbname,callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.loadDatabase(dbname,callback)});return}this.catalog.getAppKey(appName,dbname,function(result){if(typeof callback==="function"){if(result.id===0){callback(null);return}callback(result.val)}else{console.log(result.val)}})};IndexedAdapter.prototype.loadKey=IndexedAdapter.prototype.loadDatabase;IndexedAdapter.prototype.saveDatabase=function(dbname,dbstring,callback){var appName=this.app;var adapter=this;function saveCallback(result){if(result&&result.success===true){callback(null)}else{callback(new Error("Error saving database"))}}if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;cat.setAppKey(appName,dbname,dbstring,saveCallback)});return}this.catalog.setAppKey(appName,dbname,dbstring,saveCallback)};IndexedAdapter.prototype.saveKey=IndexedAdapter.prototype.saveDatabase;IndexedAdapter.prototype.deleteDatabase=function(dbname){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.deleteDatabase(dbname)});return}this.catalog.getAppKey(appName,dbname,function(result){var id=result.id;if(id!==0){adapter.catalog.deleteAppKey(id)}})};IndexedAdapter.prototype.deleteKey=IndexedAdapter.prototype.deleteDatabase;IndexedAdapter.prototype.getDatabaseList=function(callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.getDatabaseList(callback)});return}this.catalog.getAppKeys(appName,function(results){var names=[];for(var idx=0;idx<results.length;idx++){names.push(results[idx].key)}if(typeof callback==="function"){callback(names)}else{names.forEach(function(obj){console.log(obj)})}})};IndexedAdapter.prototype.getKeyList=IndexedAdapter.prototype.getDatabaseList;IndexedAdapter.prototype.getCatalogSummary=function(callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.getCatalogSummary(callback)});return}this.catalog.getAllKeys(function(results){var entries=[];var obj,size,oapp,okey,oval;for(var idx=0;idx<results.length;idx++){obj=results[idx];oapp=obj.app||"";okey=obj.key||"";oval=obj.val||"";size=oapp.length*2+okey.length*2+oval.length+1;entries.push({app:obj.app,key:obj.key,size:size})}if(typeof callback==="function"){callback(entries)}else{entries.forEach(function(obj){console.log(obj)})}})};function LokiCatalog(callback){this.db=null;this.initializeLokiCatalog(callback)}LokiCatalog.prototype.initializeLokiCatalog=function(callback){var openRequest=indexedDB.open("LokiCatalog",1);var cat=this;openRequest.onupgradeneeded=function(e){var thisDB=e.target.result;if(thisDB.objectStoreNames.contains("LokiAKV")){thisDB.deleteObjectStore("LokiAKV")}if(!thisDB.objectStoreNames.contains("LokiAKV")){var objectStore=thisDB.createObjectStore("LokiAKV",{keyPath:"id",autoIncrement:true});objectStore.createIndex("app","app",{unique:false});objectStore.createIndex("key","key",{unique:false});objectStore.createIndex("appkey","appkey",{unique:true})}};openRequest.onsuccess=function(e){cat.db=e.target.result;if(typeof callback==="function")callback(cat)};openRequest.onerror=function(e){throw e}};LokiCatalog.prototype.getAppKey=function(app,key,callback){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var index=store.index("appkey");var appkey=app+","+key;var request=index.get(appkey);request.onsuccess=function(usercallback){return function(e){var lres=e.target.result;if(lres===null||typeof lres==="undefined"){lres={id:0,success:false}}if(typeof usercallback==="function"){usercallback(lres)}else{console.log(lres)}}}(callback);request.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({id:0,success:false})}else{throw e}}}(callback)};LokiCatalog.prototype.getAppKeyById=function(id,callback,data){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var request=store.get(id);request.onsuccess=function(data,usercallback){return function(e){if(typeof usercallback==="function"){usercallback(e.target.result,data)}else{console.log(e.target.result)}}}(data,callback)};LokiCatalog.prototype.setAppKey=function(app,key,val,callback){var transaction=this.db.transaction(["LokiAKV"],"readwrite");var store=transaction.objectStore("LokiAKV");var index=store.index("appkey");var appkey=app+","+key;var request=index.get(appkey);request.onsuccess=function(e){var res=e.target.result;if(res===null||res===undefined){res={app:app,key:key,appkey:app+","+key,val:val}}else{res.val=val}var requestPut=store.put(res);requestPut.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({success:false})}else{console.error("LokiCatalog.setAppKey (set) onerror");console.error(request.error)}}}(callback);requestPut.onsuccess=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({success:true})}}}(callback)};request.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback({success:false})}else{console.error("LokiCatalog.setAppKey (get) onerror");console.error(request.error)}}}(callback)};LokiCatalog.prototype.deleteAppKey=function(id,callback){var transaction=this.db.transaction(["LokiAKV"],"readwrite");var store=transaction.objectStore("LokiAKV");var request=store.delete(id);request.onsuccess=function(usercallback){return function(evt){if(typeof usercallback==="function")usercallback({success:true})}}(callback);request.onerror=function(usercallback){return function(evt){if(typeof usercallback==="function"){usercallback(false)}else{console.error("LokiCatalog.deleteAppKey raised onerror");console.error(request.error)}}}(callback)};LokiCatalog.prototype.getAppKeys=function(app,callback){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var index=store.index("app");var singleKeyRange=IDBKeyRange.only(app);var cursor=index.openCursor(singleKeyRange);var localdata=[];cursor.onsuccess=function(data,callback){return function(e){var cursor=e.target.result;if(cursor){var currObject=cursor.value;data.push(currObject);cursor.continue()}else{if(typeof callback==="function"){callback(data)}else{console.log(data)}}}}(localdata,callback);cursor.onerror=function(usercallback){return function(e){if(typeof usercallback==="function"){usercallback(null)}else{console.error("LokiCatalog.getAppKeys raised onerror");console.error(e)}}}(callback)};LokiCatalog.prototype.getAllKeys=function(callback){var transaction=this.db.transaction(["LokiAKV"],"readonly");var store=transaction.objectStore("LokiAKV");var cursor=store.openCursor();var localdata=[];cursor.onsuccess=function(data,callback){return function(e){var cursor=e.target.result;if(cursor){var currObject=cursor.value;data.push(currObject);cursor.continue()}else{if(typeof callback==="function"){callback(data)}else{console.log(data)}}}}(localdata,callback);cursor.onerror=function(usercallback){return function(e){if(typeof usercallback==="function")usercallback(null)}}(callback)};return IndexedAdapter}()});

@@ -1,2 +0,2 @@

(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.loki=factory()}})(this,function(){return function(){"use strict";var Utils={copyProperties:function(src,dest){var prop;for(prop in src){dest[prop]=src[prop]}},resolveTransformObject:function(subObj,params,depth){var prop,pname;if(typeof depth!=="number"){depth=0}if(++depth>=10)return subObj;for(prop in subObj){if(typeof subObj[prop]==="string"&&subObj[prop].indexOf("[%lktxp]")===0){pname=subObj[prop].substring(8);if(params.hasOwnProperty(pname)){subObj[prop]=params[pname]}}else if(typeof subObj[prop]==="object"){subObj[prop]=Utils.resolveTransformObject(subObj[prop],params,depth)}}return subObj},resolveTransformParams:function(transform,params){var idx,prop,clonedStep,resolvedTransform=[];if(typeof params==="undefined")return transform;for(idx=0;idx<transform.length;idx++){clonedStep=JSON.parse(JSON.stringify(transform[idx]));resolvedTransform.push(Utils.resolveTransformObject(clonedStep,params))}return resolvedTransform}};function ltHelper(prop1,prop2,equal){if(prop1===prop2){if(equal){return true}else{return false}}if(prop1===undefined){return true}if(prop2===undefined){return false}if(prop1===null){return true}if(prop2===null){return false}return prop1<prop2}function gtHelper(prop1,prop2,equal){if(prop1===prop2){if(equal){return true}else{return false}}if(prop1===undefined){return false}if(prop2===undefined){return true}if(prop1===null){return false}if(prop2===null){return true}return prop1>prop2}function sortHelper(prop1,prop2,desc){if(prop1===prop2){return 0}if(desc){if(ltHelper(prop1,prop2)){return 1}else{return-1}}else{if(gtHelper(prop1,prop2)){return 1}else{return-1}}}function containsCheckFn(a,b){if(Array.isArray(a)){return function(curr){return a.indexOf(curr)!==-1}}else if(a&&typeof a==="string"){return function(curr){return a.indexOf(curr)!==-1}}else if(a&&typeof a==="object"){return function(curr){return a.hasOwnProperty(curr)}}}var LokiOps={$eq:function(a,b){return a===b},$gt:function(a,b){return gtHelper(a,b)},$gte:function(a,b){return gtHelper(a,b,true)},$lt:function(a,b){return ltHelper(a,b)},$lte:function(a,b){return ltHelper(a,b,true)},$ne:function(a,b){return a!==b},$regex:function(a,b){return b.test(a)},$in:function(a,b){return b.indexOf(a)>-1},$containsAny:function(a,b){var checkFn;if(!Array.isArray(b)){b=[b]}checkFn=containsCheckFn(a,b)||function(){return false};return b.reduce(function(prev,curr){if(prev){return prev}return checkFn(curr)},false)},$contains:function(a,b){var checkFn;if(!Array.isArray(b)){b=[b]}checkFn=containsCheckFn(a,b)||function(){return false};return b.reduce(function(prev,curr){if(!prev){return prev}return checkFn(curr)},true)}};var operators={$eq:LokiOps.$eq,$gt:LokiOps.$gt,$gte:LokiOps.$gte,$lt:LokiOps.$lt,$lte:LokiOps.$lte,$ne:LokiOps.$ne,$regex:LokiOps.$regex,$in:LokiOps.$in,$contains:LokiOps.$contains,$containsAny:LokiOps.$containsAny};var indexedOpsList=["$eq","$gt","$gte","$lt","$lte"];function clone(data,method){var cloneMethod=method||"parse-stringify",cloned;if(cloneMethod==="parse-stringify"){cloned=JSON.parse(JSON.stringify(data))}return cloned}function localStorageAvailable(){try{return"localStorage"in window&&window.localStorage!==null}catch(e){return false}}function LokiEventEmitter(){}LokiEventEmitter.prototype.events={};LokiEventEmitter.prototype.asyncListeners=false;LokiEventEmitter.prototype.on=function(eventName,listener){var event=this.events[eventName];if(!event){event=this.events[eventName]=[]}event.push(listener);return listener};LokiEventEmitter.prototype.emit=function(eventName,data){var self=this;if(eventName&&this.events[eventName]){this.events[eventName].forEach(function(listener){if(self.asyncListeners){setTimeout(function(){listener(data)},1)}else{listener(data)}})}else{throw new Error("No event "+eventName+" defined")}};LokiEventEmitter.prototype.removeListener=function(eventName,listener){if(this.events[eventName]){var listeners=this.events[eventName];listeners.splice(listeners.indexOf(listener),1)}};function Loki(filename,options){this.filename=filename||"loki.db";this.collections=[];this.databaseVersion=1.1;this.engineVersion=1.1;this.autosave=false;this.autosaveInterval=5e3;this.autosaveHandle=null;this.options={};this.persistenceMethod=null;this.persistenceAdapter=null;this.events={init:[],loaded:[],flushChanges:[],close:[],changes:[],warning:[]};var getENV=function(){if(typeof window==="undefined"){return"NODEJS"}if(typeof global!=="undefined"&&global.window){return"NODEJS"}if(typeof document!=="undefined"){if(document.URL.indexOf("http://")===-1&&document.URL.indexOf("https://")===-1){return"CORDOVA"}return"BROWSER"}return"CORDOVA"};if(options&&options.hasOwnProperty("env")){this.ENV=options.env}else{this.ENV=getENV()}if(this.ENV==="undefined"){this.ENV="NODEJS"}this.configureOptions(options,true);this.on("init",this.clearChanges)}Loki.prototype=new LokiEventEmitter;Loki.prototype.getIndexedAdapter=function(){var adapter;if(typeof require==="function"){adapter=require("./loki-indexed-adapter.js")}return adapter};Loki.prototype.configureOptions=function(options,initialConfig){var defaultPersistence={NODEJS:"fs",BROWSER:"localStorage",CORDOVA:"localStorage"},persistenceMethods={fs:LokiFsAdapter,localStorage:LokiLocalStorageAdapter};this.options={};this.persistenceMethod=null;this.persistenceAdapter=null;if(typeof options!=="undefined"){this.options=options;if(this.options.hasOwnProperty("persistenceMethod")){if(typeof persistenceMethods[options.persistenceMethod]=="function"){this.persistenceMethod=options.persistenceMethod;this.persistenceAdapter=new persistenceMethods[options.persistenceMethod]}}if(this.options.hasOwnProperty("adapter")){this.persistenceMethod="adapter";this.persistenceAdapter=options.adapter}if(options.hasOwnProperty("autoload")&&typeof initialConfig!=="undefined"&&initialConfig){var self=this;setTimeout(function(){self.loadDatabase(options,options.autoloadCallback)},1)}if(this.options.hasOwnProperty("autosaveInterval")){this.autosaveDisable();this.autosaveInterval=parseInt(this.options.autosaveInterval,10)}if(this.options.hasOwnProperty("autosave")&&this.options.autosave){this.autosaveDisable();this.autosave=true;if(this.options.hasOwnProperty("autosaveCallback")){this.autosaveEnable(options,options.autosaveCallback)}else{this.autosaveEnable()}}}if(this.persistenceAdapter===null){this.persistenceMethod=defaultPersistence[this.ENV];if(this.persistenceMethod){this.persistenceAdapter=new persistenceMethods[this.persistenceMethod]}}};Loki.prototype.anonym=function(docs,indexesArray){var collection=new Collection("anonym",indexesArray);collection.insert(docs);return collection};Loki.prototype.addCollection=function(name,options){var collection=new Collection(name,options);this.collections.push(collection);return collection};Loki.prototype.loadCollection=function(collection){if(!collection.name){throw new Error("Collection must have a name property to be loaded")}this.collections.push(collection)};Loki.prototype.getCollection=function(collectionName){var i,len=this.collections.length;for(i=0;i<len;i+=1){if(this.collections[i].name===collectionName){return this.collections[i]}}this.emit("warning","collection "+collectionName+" not found");return null};Loki.prototype.listCollections=function(){var i=this.collections.length,colls=[];while(i--){colls.push({name:this.collections[i].name,type:this.collections[i].objType,count:this.collections[i].data.length})}return colls};Loki.prototype.removeCollection=function(collectionName){var i,len=this.collections.length;for(i=0;i<len;i+=1){if(this.collections[i].name===collectionName){this.collections.splice(i,1);return}}};Loki.prototype.getName=function(){return this.name};Loki.prototype.serializeReplacer=function(key,value){switch(key){case"autosaveHandle":case"persistenceAdapter":case"constraints":return null;default:return value}};Loki.prototype.serialize=function(){return JSON.stringify(this,this.serializeReplacer)};Loki.prototype.toJson=Loki.prototype.serialize;Loki.prototype.loadJSON=function(serializedDb,options){if(serializedDb.length===0)serializedDb=JSON.stringify({});var obj=JSON.parse(serializedDb),i=0,len=obj.collections?obj.collections.length:0,coll,copyColl,clen,j;this.name=obj.name;this.databaseVersion=1;if(obj.hasOwnProperty("databaseVersion")){this.databaseVersion=obj.databaseVersion}this.collections=[];for(i;i<len;i+=1){coll=obj.collections[i];copyColl=this.addCollection(coll.name);clen=coll.data.length;j=0;if(options&&options.hasOwnProperty(coll.name)){var loader=options[coll.name].inflate?options[coll.name].inflate:Utils.copyProperties;for(j;j<clen;j++){var collObj=new options[coll.name].proto;loader(coll.data[j],collObj);copyColl.data[j]=collObj}}else{for(j;j<clen;j++){copyColl.data[j]=coll.data[j]}}copyColl.transactional=coll.transactional;copyColl.asyncListeners=coll.asyncListeners;copyColl.disableChangesApi=coll.disableChangesApi;copyColl.cloneObjects=coll.cloneObjects;copyColl.maxId=coll.data.length===0?0:coll.maxId;copyColl.idIndex=coll.idIndex;if(typeof coll.binaryIndices!=="undefined"){copyColl.binaryIndices=coll.binaryIndices}if(typeof coll.transforms!=="undefined"){copyColl.transforms=coll.transforms}copyColl.ensureId();copyColl.uniqueNames=[];if(coll.hasOwnProperty("uniqueNames")){copyColl.uniqueNames=coll.uniqueNames;for(j=0;j<copyColl.uniqueNames.length;j++){copyColl.ensureUniqueIndex(copyColl.uniqueNames[j])}}if(typeof coll.DynamicViews==="undefined")continue;for(var idx=0;idx<coll.DynamicViews.length;idx++){var colldv=coll.DynamicViews[idx];var dv=copyColl.addDynamicView(colldv.name,colldv.options);dv.resultdata=colldv.resultdata;dv.resultsdirty=colldv.resultsdirty;dv.filterPipeline=colldv.filterPipeline;dv.sortCriteria=colldv.sortCriteria;dv.sortFunction=null;dv.sortDirty=colldv.sortDirty;dv.resultset.filteredrows=colldv.resultset.filteredrows;dv.resultset.searchIsChained=colldv.resultset.searchIsChained;dv.resultset.filterInitialized=colldv.resultset.filterInitialized;dv.rematerialize({removeWhereFilters:true})}}};Loki.prototype.close=function(callback){if(this.autosave){this.autosaveDisable();if(this.autosaveDirty()){this.saveDatabase()}}if(callback){this.on("close",callback)}this.emit("close")};Loki.prototype.generateChangesNotification=function(arrayOfCollectionNames){function getCollName(coll){return coll.name}var changes=[],selectedCollections=arrayOfCollectionNames||this.collections.map(getCollName);this.collections.forEach(function(coll){if(selectedCollections.indexOf(getCollName(coll))!==-1){changes=changes.concat(coll.getChanges())}});return changes};Loki.prototype.serializeChanges=function(collectionNamesArray){return JSON.stringify(this.generateChangesNotification(collectionNamesArray))};Loki.prototype.clearChanges=function(){this.collections.forEach(function(coll){if(coll.flushChanges){coll.flushChanges()}})};function LokiFsAdapter(){this.fs=require("fs")}LokiFsAdapter.prototype.loadDatabase=function loadDatabase(dbname,callback){this.fs.readFile(dbname,{encoding:"utf8"},function readFileCallback(err,data){if(err){callback(new Error(err))}else{callback(data)}})};LokiFsAdapter.prototype.saveDatabase=function saveDatabase(dbname,dbstring,callback){this.fs.writeFile(dbname,dbstring,callback)};function LokiLocalStorageAdapter(){}LokiLocalStorageAdapter.prototype.loadDatabase=function loadDatabase(dbname,callback){if(localStorageAvailable()){callback(localStorage.getItem(dbname))}else{callback(new Error("localStorage is not available"))}};LokiLocalStorageAdapter.prototype.saveDatabase=function saveDatabase(dbname,dbstring,callback){if(localStorageAvailable()){localStorage.setItem(dbname,dbstring);callback(null)}else{callback(new Error("localStorage is not available"))}};Loki.prototype.loadDatabase=function(options,callback){var cFun=callback||function(err,data){if(err){throw err}return},self=this;if(this.persistenceAdapter!==null){this.persistenceAdapter.loadDatabase(this.filename,function loadDatabaseCallback(dbString){if(typeof dbString==="string"){self.loadJSON(dbString,options||{});cFun(null);self.emit("loaded","database "+self.filename+" loaded")}else{console.warn("lokijs loadDatabase : Database not found");if(typeof dbString==="object"){cFun(dbString)}else{cFun("Database not found")}}})}else{cFun(new Error("persistenceAdapter not configured"))}};Loki.prototype.saveDatabase=function(callback){var cFun=callback||function(err){if(err){throw err}return},self=this;if(this.persistenceAdapter!==null){this.persistenceAdapter.saveDatabase(this.filename,self.serialize(),function saveDatabasecallback(){self.autosaveClearFlags();cFun(null)})}else{cFun(new Error("persistenceAdapter not configured"))}};Loki.prototype.save=Loki.prototype.saveDatabase;Loki.prototype.autosaveDirty=function(){for(var idx=0;idx<this.collections.length;idx++){if(this.collections[idx].dirty){return true}}return false};Loki.prototype.autosaveClearFlags=function(){for(var idx=0;idx<this.collections.length;idx++){this.collections[idx].dirty=false}};Loki.prototype.autosaveEnable=function(options,callback){this.autosave=true;var delay=5e3,self=this;if(typeof this.autosaveInterval!=="undefined"&&this.autosaveInterval!==null){delay=this.autosaveInterval}this.autosaveHandle=setInterval(function autosaveHandleInterval(){if(self.autosaveDirty()){self.saveDatabase(callback)}},delay)};Loki.prototype.autosaveDisable=function(){if(typeof this.autosaveHandle!=="undefined"&&this.autosaveHandle!==null){clearInterval(this.autosaveHandle);this.autosaveHandle=null}};function Resultset(collection,queryObj,queryFunc,firstOnly){this.collection=collection;this.searchIsChained=!queryObj&&!queryFunc;this.filteredrows=[];this.filterInitialized=false;if(typeof queryObj!=="undefined"&&queryObj!==null){return this.find(queryObj,firstOnly)}if(typeof queryFunc!=="undefined"&&queryFunc!==null){return this.where(queryFunc)}return this}Resultset.prototype.toJSON=function(){var copy=this.copy();copy.collection=null;return copy};Resultset.prototype.limit=function(qty){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var rscopy=this.copy();rscopy.filteredrows=rscopy.filteredrows.slice(0,qty);return rscopy};Resultset.prototype.offset=function(pos){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var rscopy=this.copy();rscopy.filteredrows=rscopy.filteredrows.splice(pos,rscopy.filteredrows.length);return rscopy};Resultset.prototype.copy=function(){var result=new Resultset(this.collection,null,null);result.filteredrows=this.filteredrows.slice();result.filterInitialized=this.filterInitialized;return result};Resultset.prototype.branch=Resultset.prototype.copy;Resultset.prototype.transform=function(transform,parameters){var idx,step,rs=this;if(typeof parameters!=="undefined"){transform=Utils.resolveTransformParams(transform,parameters)}for(idx=0;idx<transform.length;idx++){step=transform[idx];switch(step.type){case"find":rs.find(step.value);break;case"where":rs.where(step.value);break;case"simplesort":rs.simplesort(step.property,step.desc);break;case"compoundsort":rs.compoundsort(step.value);break;case"sort":rs.sort(step.value);break;case"limit":rs=rs.limit(step.value);break;case"offset":rs=rs.offset(step.value);break;case"map":rs=rs.map(step.value);break;case"eqJoin":rs=rs.eqJoin(step.joinData,step.leftJoinKey,step.rightJoinKey,step.mapFun);break;case"mapReduce":rs=rs.mapReduce(step.mapFunction,step.reduceFunction);break;case"update":rs.update(step.value);break;case"remove":rs.remove();break;default:break}}return rs};Resultset.prototype.sort=function(comparefun){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var wrappedComparer=function(userComparer,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return userComparer(obj1,obj2)}}(comparefun,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.simplesort=function(propname,isdesc){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}if(typeof isdesc==="undefined"){isdesc=false}var wrappedComparer=function(prop,desc,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return sortHelper(obj1[prop],obj2[prop],desc)}}(propname,isdesc,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.compoundeval=function(properties,obj1,obj2){var propertyCount=properties.length;if(propertyCount===0){throw new Error("Invalid call to compoundeval, need at least one property")}var isdesc=false;var firstProp=properties[0];if(typeof firstProp!=="string"){if(Array.isArray(firstProp)){isdesc=firstProp[1];firstProp=firstProp[0]}}if(obj1[firstProp]===obj2[firstProp]){if(propertyCount===1){return 0}else{return this.compoundeval(properties.slice(1),obj1,obj2,isdesc)}}return sortHelper(obj1[firstProp],obj2[firstProp],isdesc)};Resultset.prototype.compoundsort=function(properties){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var wrappedComparer=function(props,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return rslt.compoundeval(props,obj1,obj2)}}(properties,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.calculateRange=function(op,prop,val){var rcd=this.collection.data;var index=this.collection.binaryIndices[prop].values;var min=0;var max=index.length-1;var mid=null;var lbound=0;var ubound=index.length-1;if(rcd.length===0){return[0,-1]}var minVal=rcd[index[min]][prop];var maxVal=rcd[index[max]][prop];switch(op){case"$eq":if(ltHelper(val,minVal)||gtHelper(val,maxVal)){return[0,-1]}break;case"$gt":if(gtHelper(val,maxVal,true)){return[0,-1]}break;case"$gte":if(gtHelper(val,maxVal)){return[0,-1]}break;case"$lt":if(ltHelper(val,minVal,true)){return[0,-1]}if(ltHelper(maxVal,val)){return[0,rcd.length-1]}break;case"$lte":if(ltHelper(val,minVal)){return[0,-1]}if(ltHelper(maxVal,val,true)){return[0,rcd.length-1]}break}while(min<max){mid=Math.floor((min+max)/2);if(ltHelper(rcd[index[mid]][prop],val)){min=mid+1}else{max=mid}}lbound=min;min=0;max=index.length-1;while(min<max){mid=Math.floor((min+max)/2);if(ltHelper(val,rcd[index[mid]][prop])){max=mid}else{min=mid+1}}ubound=max;var lval=rcd[index[lbound]][prop];var uval=rcd[index[ubound]][prop];switch(op){case"$eq":if(lval!==val){return[0,-1]}if(uval!==val){ubound--}return[lbound,ubound];case"$gt":if(ltHelper(uval,val,true)){return[0,-1]}return[ubound,rcd.length-1];case"$gte":if(ltHelper(lval,val)){return[0,-1]}return[lbound,rcd.length-1];case"$lt":if(lbound===0&&ltHelper(lval,val)){return[0,0]}return[0,lbound-1];case"$lte":if(uval!==val){ubound--}if(ubound===0&&ltHelper(uval,val)){return[0,0]}return[0,ubound];default:return[0,rcd.length-1]}};Resultset.prototype.findOr=function(expressionArray){var fri=0,ei=0,fr=null,docset=[],expResultset=null;if(this.filterInitialized){docset=[];for(ei=0;ei<expressionArray.length;ei++){expResultset=this.branch();expResultset.find(expressionArray[ei]);expResultset.data();fr=expResultset.filteredrows;for(fri=0;fri<fr.length;fri++){if(docset.indexOf(fr[fri])===-1){docset.push(fr[fri])}}}this.filteredrows=docset}else{for(ei=0;ei<expressionArray.length;ei++){expResultset=this.collection.chain();expResultset.find(expressionArray[ei]);expResultset.data();fr=expResultset.filteredrows;for(fri=0;fri<fr.length;fri++){if(this.filteredrows.indexOf(fr[fri])===-1){this.filteredrows.push(fr[fri])}}}}this.filterInitialized=true;return this};Resultset.prototype.findAnd=function(expressionArray){for(var i=0;i<expressionArray.length;i++){this.find(expressionArray[i])}return this};Resultset.prototype.dotSubScan=function(root,property,fun,value){var arrayRef=null;var pathIndex,subIndex;var paths=property.split(".");var path;for(pathIndex=0;pathIndex<paths.length;pathIndex++){path=paths[pathIndex];if(arrayRef){for(subIndex=0;subIndex<arrayRef.length;subIndex++){if(fun(arrayRef[subIndex][path],value)){return true}}}else{root=root[path];if(Array.isArray(root)){arrayRef=root}}}return fun(root,value)};Resultset.prototype.find=function(query,firstOnly){if(this.collection.data.length===0){if(this.searchIsChained){this.filteredrows=[];this.filterInitialized=true;return this}return[]}var queryObject=query||"getAll",property,value,operator,p,key,searchByIndex=false,result=[],index=null,fun,t,i,emptyQO=true;firstOnly=firstOnly||false;for(p in queryObject){emptyQO=false;break}if(emptyQO){queryObject="getAll"}if(queryObject==="getAll"){if(this.searchIsChained){this.filteredrows=Object.keys(this.collection.data);return this}else{return this.collection.data}}var usingDotNotation=false;for(p in queryObject){if(queryObject.hasOwnProperty(p)){property=p;if(p==="$and"){if(this.searchIsChained){this.findAnd(queryObject[p]);if(firstOnly&&this.filteredrows.length>1){this.filteredrows=this.filteredrows.slice(0,1)}return this}else{result=this.collection.chain().findAnd(queryObject[p]).data();if(firstOnly){if(result.length===0)return[];return result[0]}return result}}if(p==="$or"){if(this.searchIsChained){this.findOr(queryObject[p]);if(firstOnly&&this.filteredrows.length>1){this.filteredrows=this.filteredrows.slice(0,1)}return this}else{result=this.collection.chain().findOr(queryObject[p]).data();if(firstOnly){if(result.length===0)return[];return result[0]}return result}}if(p.indexOf(".")!=-1){usingDotNotation=true}if(queryObject[p]===null||typeof queryObject[p]!=="object"){operator="$eq";value=queryObject[p]}else if(typeof queryObject[p]==="object"){for(key in queryObject[p]){if(queryObject[p].hasOwnProperty(key)){operator=key;value=queryObject[p][key]}}}else{throw"Do not know what you want to do."}break}}if(operator==="$regex")value=new RegExp(value);if(this.collection.data===null){throw new TypeError}if((!this.searchIsChained||this.searchIsChained&&!this.filterInitialized)&&indexedOpsList.indexOf(operator)!==-1&&this.collection.binaryIndices.hasOwnProperty(property)){this.collection.ensureIndex(property);searchByIndex=true;index=this.collection.binaryIndices[property]}fun=operators[operator];if(!this.searchIsChained){if(!searchByIndex){t=this.collection.data;i=t.length;if(firstOnly){if(usingDotNotation){while(i--){if(this.dotSubScan(t[i],property,fun,value)){return t[i]}}}else{while(i--){if(fun(t[i][property],value)){return t[i]}}}return[]}else{if(usingDotNotation){while(i--){if(this.dotSubScan(t[i],property,fun,value)){result.push(t[i])}}}else{while(i--){if(fun(t[i][property],value)){result.push(t[i])}}}}}else{t=this.collection.data;var seg=this.calculateRange(operator,property,value,this);if(firstOnly){if(seg[1]!==-1){return t[index.values[seg[0]]]}return[]}for(i=seg[0];i<=seg[1];i++){result.push(t[index.values[i]])}this.filteredrows=result}return result}else{if(this.filterInitialized){if(!searchByIndex){t=this.collection.data;i=this.filteredrows.length;if(usingDotNotation){while(i--){if(this.dotSubScan(t[this.filteredrows[i]],property,fun,value)){result.push(this.filteredrows[i])}}}else{while(i--){if(fun(t[this.filteredrows[i]][property],value)){result.push(this.filteredrows[i])}}}}else{t=index;i=this.filteredrows.length;while(i--){if(fun(t[this.filteredrows[i]],value)){result.push(this.filteredrows[i])}}}this.filteredrows=result;return this}else{if(!searchByIndex){t=this.collection.data;i=t.length;if(usingDotNotation){while(i--){if(this.dotSubScan(t[i],property,fun,value)){result.push(i)}}}else{while(i--){if(fun(t[i][property],value)){result.push(i)}}}}else{t=this.collection.data;var segm=this.calculateRange(operator,property,value,this);for(var idx=segm[0];idx<=segm[1];idx++){result.push(index.values[idx])}this.filteredrows=result}this.filteredrows=result;this.filterInitialized=true;return this}}};Resultset.prototype.where=function(fun){var viewFunction,result=[];if("function"===typeof fun){viewFunction=fun}else{throw"Argument is not a stored view or a function"}try{if(!this.searchIsChained){var i=this.collection.data.length;while(i--){if(viewFunction(this.collection.data[i])===true){result.push(this.collection.data[i])}}return result}else{if(this.filterInitialized){var j=this.filteredrows.length;while(j--){if(viewFunction(this.collection.data[this.filteredrows[j]])===true){result.push(this.filteredrows[j])}}this.filteredrows=result;return this}else{var k=this.collection.data.length;while(k--){if(viewFunction(this.collection.data[k])===true){result.push(k)}}this.filteredrows=result;this.filterInitialized=true;return this}}}catch(err){throw err}};Resultset.prototype.data=function(){var result=[];if(this.searchIsChained&&!this.filterInitialized){if(this.filteredrows.length===0){return this.collection.data}else{this.filterInitialized=true}}var data=this.collection.data,fr=this.filteredrows;var i,len=this.filteredrows.length;for(i=0;i<len;i++){result.push(data[fr[i]])}return result};Resultset.prototype.update=function(updateFunction){if(typeof updateFunction!=="function"){throw"Argument is not a function"}if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var len=this.filteredrows.length,rcd=this.collection.data;for(var idx=0;idx<len;idx++){updateFunction(rcd[this.filteredrows[idx]]);this.collection.update(rcd[this.filteredrows[idx]])}return this};Resultset.prototype.remove=function(){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var len=this.filteredrows.length;for(var idx=0;idx<len;idx++){this.collection.remove(this.filteredrows[idx])}this.filteredrows=[];return this};Resultset.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data().map(mapFunction))}catch(err){throw err}};Resultset.prototype.eqJoin=function(joinData,leftJoinKey,rightJoinKey,mapFun){var leftData=[],leftDataLength,rightData=[],rightDataLength,key,result=[],obj,leftKeyisFunction=typeof leftJoinKey==="function",rightKeyisFunction=typeof rightJoinKey==="function",joinMap={};leftData=this.data();leftDataLength=leftData.length;if(joinData instanceof Resultset){rightData=joinData.data()}else if(Array.isArray(joinData)){rightData=joinData}else{throw new TypeError("joinData needs to be an array or result set")}rightDataLength=rightData.length;for(var i=0;i<rightDataLength;i++){key=rightKeyisFunction?rightJoinKey(rightData[i]):rightData[i][rightJoinKey];joinMap[key]=rightData[i]}if(!mapFun){mapFun=function(left,right){return{left:left,right:right}}}for(var j=0;j<leftDataLength;j++){key=leftKeyisFunction?leftJoinKey(leftData[j]):leftData[j][leftJoinKey];result.push(mapFun(leftData[j],joinMap[key]||{}))}this.collection=new Collection("joinData");this.collection.insert(result);this.filteredrows=[];this.filterInitialized=false;return this};Resultset.prototype.map=function(mapFun){var data=this.data().map(mapFun);this.collection=new Collection("mappedData");this.collection.insert(data);this.filteredrows=[];this.filterInitialized=false;return this};function DynamicView(collection,name,options){this.collection=collection;this.name=name;this.rebuildPending=false;this.options=options||{};if(!this.options.hasOwnProperty("persistent")){this.options.persistent=false}if(!this.options.hasOwnProperty("sortPriority")){this.options.sortPriority="passive"}this.resultset=new Resultset(collection);this.resultdata=[];this.resultsdirty=false;this.cachedresultset=null;this.filterPipeline=[];this.sortFunction=null;this.sortCriteria=null;this.sortDirty=false;this.events={rebuild:[]}}DynamicView.prototype=new LokiEventEmitter;DynamicView.prototype.rematerialize=function(options){var fpl,fpi,idx;options=options||{};this.resultdata=[];this.resultsdirty=true;this.resultset=new Resultset(this.collection);if(this.sortFunction||this.sortCriteria){this.sortDirty=true}if(options.hasOwnProperty("removeWhereFilters")){fpl=this.filterPipeline.length;fpi=fpl;while(fpi--){if(this.filterPipeline[fpi].type==="where"){if(fpi!==this.filterPipeline.length-1){this.filterPipeline[fpi]=this.filterPipeline[this.filterPipeline.length-1]}this.filterPipeline.length--}}}var ofp=this.filterPipeline;this.filterPipeline=[];fpl=ofp.length;for(idx=0;idx<fpl;idx++){this.applyFind(ofp[idx].val)}this.data();this.emit("rebuild",this);return this};DynamicView.prototype.branchResultset=function(transform,parameters){var rs=this.resultset.copy();if(typeof transform==="undefined"){return rs}if(typeof transform==="string"){if(this.collection.transforms.hasOwnProperty(transform)){transform=this.collection.transforms[transform]}}if(typeof transform==="object"&&Array.isArray(transform)){return rs.transform(transform,parameters)}return rs};DynamicView.prototype.toJSON=function(){var copy=new DynamicView(this.collection,this.name,this.options);copy.resultset=this.resultset;copy.resultdata=[];copy.resultsdirty=true;copy.filterPipeline=this.filterPipeline;copy.sortFunction=this.sortFunction;copy.sortCriteria=this.sortCriteria;copy.sortDirty=this.sortDirty;copy.collection=null;return copy};DynamicView.prototype.applySort=function(comparefun){this.sortFunction=comparefun;this.sortCriteria=null;this.queueSortPhase();return this};DynamicView.prototype.applySimpleSort=function(propname,isdesc){if(typeof isdesc==="undefined"){isdesc=false}this.sortCriteria=[[propname,isdesc]];this.sortFunction=null;this.queueSortPhase();return this};DynamicView.prototype.applySortCriteria=function(criteria){this.sortCriterial=criteria;this.sortFunction=null;this.queueSortPhase();return this};DynamicView.prototype.startTransaction=function(){this.cachedresultset=this.resultset.copy();return this};DynamicView.prototype.commit=function(){this.cachedresultset=null;return this};DynamicView.prototype.rollback=function(){this.resultset=this.cachedresultset;if(this.options.persistent){this.resultdata=this.resultset.data();this.emit("rebuild",this)}return this};DynamicView.prototype.applyFind=function(query){this.filterPipeline.push({type:"find",val:query});this.resultset.find(query);if(this.sortFunction||this.sortCriteria){this.sortDirty=true;this.queueSortPhase()}if(this.options.persistent){this.resultsdirty=true;this.queueSortPhase()}return this};DynamicView.prototype.applyWhere=function(fun){this.filterPipeline.push({type:"where",val:fun});this.resultset.where(fun);if(this.sortFunction||this.sortCriteria){this.sortDirty=true;this.queueSortPhase()}if(this.options.persistent){this.resultsdirty=true;this.queueSortPhase()}return this};DynamicView.prototype.data=function(){if(this.sortDirty||this.resultsdirty||!this.resultset.filterInitialized){this.performSortPhase()}if(!this.options.persistent){return this.resultset.data()}return this.resultdata};DynamicView.prototype.queueRebuildEvent=function(){var self=this;if(this.rebuildPending){return}this.rebuildPending=true;setTimeout(function(){self.rebuildPending=false;self.emit("rebuild",this)},1)};DynamicView.prototype.queueSortPhase=function(){var self=this;if(this.sortDirty){return}this.sortDirty=true;if(this.options.sortPriority==="active"){setTimeout(function(){self.performSortPhase()},1)}else{this.queueRebuildEvent()}};DynamicView.prototype.performSortPhase=function(){if(!this.sortDirty&&!this.resultsdirty&&this.resultset.filterInitialized){return}if(this.sortFunction){this.resultset.sort(this.sortFunction)}if(this.sortCriteria){this.resultset.compoundsort(this.sortCriteria)}if(!this.options.persistent){this.sortDirty=false;return}this.resultdata=this.resultset.data();this.resultsdirty=false;this.sortDirty=false;this.emit("rebuild",this)};DynamicView.prototype.evaluateDocument=function(objIndex){var ofr=this.resultset.filteredrows;var oldPos=ofr.indexOf(objIndex);
var oldlen=ofr.length;var evalResultset=new Resultset(this.collection);evalResultset.filteredrows=[objIndex];evalResultset.filterInitialized=true;for(var idx=0;idx<this.filterPipeline.length;idx++){switch(this.filterPipeline[idx].type){case"find":evalResultset.find(this.filterPipeline[idx].val);break;case"where":evalResultset.where(this.filterPipeline[idx].val);break}}var newPos=evalResultset.filteredrows.length===0?-1:0;if(oldPos==-1&&newPos==-1)return;if(oldPos===-1&&newPos!==-1){ofr.push(objIndex);if(this.options.persistent){this.resultdata.push(this.collection.data[objIndex])}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}else{this.queueRebuildEvent()}return}if(oldPos!==-1&&newPos===-1){if(oldPos<oldlen-1){ofr[oldPos]=ofr[oldlen-1];ofr.length=oldlen-1;if(this.options.persistent){this.resultdata[oldPos]=this.resultdata[oldlen-1];this.resultdata.length=oldlen-1}}else{ofr.length=oldlen-1;if(this.options.persistent){this.resultdata.length=oldlen-1}}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}else{this.queueRebuildEvent()}return}if(oldPos!==-1&&newPos!==-1){if(this.options.persistent){this.resultdata[oldPos]=this.collection.data[objIndex]}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}else{this.queueRebuildEvent()}return}};DynamicView.prototype.removeDocument=function(objIndex){var ofr=this.resultset.filteredrows;var oldPos=ofr.indexOf(objIndex);var oldlen=ofr.length;var idx;if(oldPos!==-1){if(oldPos<oldlen-1){ofr[oldPos]=ofr[oldlen-1];ofr.length=oldlen-1;if(this.options.persistent){this.resultdata[oldPos]=this.resultdata[oldlen-1];this.resultdata.length=oldlen-1}}else{ofr.length=oldlen-1;if(this.options.persistent){this.resultdata.length=oldlen-1}}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}}oldlen=ofr.length;for(idx=0;idx<oldlen;idx++){if(ofr[idx]>objIndex){ofr[idx]--}}};DynamicView.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data().map(mapFunction))}catch(err){throw err}};function Collection(name,options){this.name=name;this.data=[];this.idIndex=[];this.binaryIndices={};this.constraints={unique:{},exact:{}};this.uniqueNames=[];this.transforms={};this.objType=name;this.dirty=true;this.cachedIndex=null;this.cachedBinaryIndex=null;this.cachedData=null;var self=this;options=options||{};if(options.hasOwnProperty("unique")){if(!Array.isArray(options.unique)){options.unique=[options.unique]}options.unique.forEach(function(prop){self.uniqueNames.push(prop);self.constraints.unique[prop]=new UniqueIndex(prop)})}if(options.hasOwnProperty("exact")){options.exact.forEach(function(prop){self.constraints.exact[prop]=new ExactIndex(prop)})}this.transactional=options.hasOwnProperty("transactional")?options.transactional:false;this.cloneObjects=options.hasOwnProperty("clone")?options.clone:false;this.asyncListeners=options.hasOwnProperty("asyncListeners")?options.asyncListeners:false;this.disableChangesApi=options.hasOwnProperty("disableChangesApi")?options.disableChangesApi:true;this.maxId=0;this.DynamicViews=[];this.events={insert:[],update:[],"pre-insert":[],"pre-update":[],close:[],flushbuffer:[],error:[],"delete":[],warning:[]};this.changes=[];this.ensureId();var indices=[];if(options&&options.indices){if(Object.prototype.toString.call(options.indices)==="[object Array]"){indices=options.indices}else if(typeof options.indices==="string"){indices=[options.indices]}else{throw new TypeError("Indices needs to be a string or an array of strings")}}for(var idx=0;idx<indices.length;idx++){this.ensureIndex(indices[idx])}function createChange(name,op,obj){self.changes.push({name:name,operation:op,obj:JSON.parse(JSON.stringify(obj))})}function flushChanges(){self.changes=[]}this.getChanges=function(){return self.changes};this.flushChanges=flushChanges;function insertMeta(obj){if(!obj){return}if(!obj.meta){obj.meta={}}obj.meta.created=(new Date).getTime();obj.meta.revision=0}function updateMeta(obj){if(!obj){return}obj.meta.updated=(new Date).getTime();obj.meta.revision+=1}function createInsertChange(obj){createChange(self.name,"I",obj)}function createUpdateChange(obj){createChange(self.name,"U",obj)}function insertMetaWithChange(obj){insertMeta(obj);createInsertChange(obj)}function updateMetaWithChange(obj){updateMeta(obj);createUpdateChange(obj)}var insertHandler,updateHandler;function setHandlers(){insertHandler=self.disableChangesApi?insertMeta:insertMetaWithChange;updateHandler=self.disableChangesApi?updateMeta:updateMetaWithChange}setHandlers();this.setChangesApi=function(enabled){self.disableChangesApi=!enabled;setHandlers()};this.on("insert",function insertCallback(obj){insertHandler(obj)});this.on("update",function updateCallback(obj){updateHandler(obj)});this.on("delete",function deleteCallback(obj){if(!self.disableChangesApi){createChange(self.name,"R",obj)}});this.on("warning",console.warn);flushChanges()}Collection.prototype=new LokiEventEmitter;Collection.prototype.addTransform=function(name,transform){if(this.transforms.hasOwnProperty(name)){throw new Error("a transform by that name already exists")}this.transforms[name]=transform};Collection.prototype.setTransform=function(name,transform){this.transforms[name]=transform};Collection.prototype.removeTransform=function(name){delete transforms[name]};Collection.prototype.byExample=function(template){var k,obj,query;query=[];for(k in template){if(!template.hasOwnProperty(k))continue;query.push((obj={},obj[k]=template[k],obj))}return{$and:query}};Collection.prototype.findObject=function(template){return this.findOne(this.byExample(template))};Collection.prototype.findObjects=function(template){return this.find(this.byExample(template))};Collection.prototype.ensureIndex=function(property,force){if(typeof force==="undefined"){force=false}if(property===null||property===undefined){throw"Attempting to set index without an associated property"}if(this.binaryIndices.hasOwnProperty(property)&&!force){if(!this.binaryIndices[property].dirty)return}this.binaryIndices[property]={name:property,dirty:true,values:[]};var index,len=this.data.length,i=0;index=this.binaryIndices[property];for(i;i<len;i+=1){index.values.push(i)}var wrappedComparer=function(prop,coll){return function(a,b){var obj1=coll.data[a];var obj2=coll.data[b];if(obj1[prop]===obj2[prop])return 0;if(gtHelper(obj1[prop],obj2[prop]))return 1;if(ltHelper(obj1[prop],obj2[prop]))return-1}}(property,this);index.values.sort(wrappedComparer);index.dirty=false;this.dirty=true};Collection.prototype.ensureUniqueIndex=function(field){var index=this.constraints.unique[field];if(!index){if(this.uniqueNames.indexOf(field)==-1){this.uniqueNames.push(field)}this.constraints.unique[field]=index=new UniqueIndex(field)}var self=this;this.data.forEach(function(obj){index.set(obj)});return index};Collection.prototype.ensureAllIndexes=function(force){var objKeys=Object.keys(this.binaryIndices);var i=objKeys.length;while(i--){this.ensureIndex(objKeys[i],force)}};Collection.prototype.flagBinaryIndexesDirty=function(){var objKeys=Object.keys(this.binaryIndices);var i=objKeys.length;while(i--){this.binaryIndices[objKeys[i]].dirty=true}};Collection.prototype.count=function(){return this.data.length};Collection.prototype.ensureId=function(){var len=this.data.length,i=0;this.idIndex=[];for(i;i<len;i+=1){this.idIndex.push(this.data[i].$loki)}};Collection.prototype.ensureIdAsync=function(callback){this.async(function(){this.ensureId()},callback)};Collection.prototype.addDynamicView=function(name,options){var dv=new DynamicView(this,name,options);this.DynamicViews.push(dv);return dv};Collection.prototype.removeDynamicView=function(name){for(var idx=0;idx<this.DynamicViews.length;idx++){if(this.DynamicViews[idx].name===name){this.DynamicViews.splice(idx,1)}}};Collection.prototype.getDynamicView=function(name){for(var idx=0;idx<this.DynamicViews.length;idx++){if(this.DynamicViews[idx].name===name){return this.DynamicViews[idx]}}return null};Collection.prototype.findAndUpdate=function(filterFunction,updateFunction){var results=this.where(filterFunction),i=0,obj;try{for(i;i<results.length;i++){obj=updateFunction(results[i]);this.update(obj)}}catch(err){this.rollback();console.error(err.message)}};Collection.prototype.insert=function(doc){if(!doc){var error=new Error("Object cannot be null");this.emit("error",error);throw error}var self=this;var obj;var docs=Array.isArray(doc)?doc:[doc];var results=[];docs.forEach(function(d){if(typeof d!=="object"){throw new TypeError("Document needs to be an object")}obj=self.cloneObjects?JSON.parse(JSON.stringify(d)):d;if(typeof obj.meta==="undefined"){obj.meta={revision:0,created:0}}self.emit("pre-insert",obj);if(self.add(obj)){self.emit("insert",obj);results.push(obj)}else{return undefined}});return results.length===1?results[0]:results};Collection.prototype.clear=function(){this.data=[];this.idIndex=[];this.binaryIndices={};this.cachedIndex=null;this.cachedData=null;this.maxId=0;this.DynamicViews=[];this.dirty=true};Collection.prototype.update=function(doc){if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}if(Array.isArray(doc)){var k=0,len=doc.length;for(k;k<len;k+=1){this.update(doc[k])}return}if(!doc.hasOwnProperty("$loki")){throw"Trying to update unsynced document. Please save the document first by using insert() or addMany()"}try{this.startTransaction();var arr=this.get(doc.$loki,true),obj,position,self=this;if(!arr){throw new Error("Trying to update a document not in collection.")}this.emit("pre-update",doc);obj=arr[0];Object.keys(this.constraints.unique).forEach(function(key){self.constraints.unique[key].update(obj)});position=arr[1];this.data[position]=doc;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].evaluateDocument(position)}this.idIndex[position]=obj.$loki;this.commit();this.dirty=true;this.emit("update",doc);return doc}catch(err){this.rollback();console.error(err.message);this.emit("error",err);throw err}};Collection.prototype.add=function(obj){var dvlen=this.DynamicViews.length;if("object"!==typeof obj){throw"Object being added needs to be an object"}if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}if(typeof obj.$loki!=="undefined"){throw"Document is already in collection, please use update()"}try{this.startTransaction();this.maxId++;if(isNaN(this.maxId)){this.maxId=this.data[this.data.length-1].$loki+1}obj.$loki=this.maxId;obj.meta.version=0;var self=this;Object.keys(this.constraints.unique).forEach(function(key){self.constraints.unique[key].set(obj)});this.data.push(obj);for(var i=0;i<dvlen;i++){this.DynamicViews[i].evaluateDocument(this.data.length-1)}this.idIndex.push(obj.$loki);this.commit();this.dirty=true;return obj}catch(err){this.rollback();console.error(err.message)}};Collection.prototype.removeWhere=function(query){var list;if(typeof query==="function"){list=this.data.filter(query)}else{list=new Resultset(this,query)}var len=list.length;while(len--){this.remove(list[len])}var dv;for(dv in this.DynamicViews){this.DynamicViews[dv].rematerialize()}};Collection.prototype.removeDataOnly=function(){this.removeWhere(function(obj){return true})};Collection.prototype.remove=function(doc){if(typeof doc==="number"){doc=this.get(doc)}if("object"!==typeof doc){throw new Error("Parameter is not an object")}if(Array.isArray(doc)){var k=0,len=doc.length;for(k;k<len;k+=1){this.remove(doc[k])}return}if(!doc.hasOwnProperty("$loki")){throw new Error("Object is not a document stored in the collection")}if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}try{this.startTransaction();var arr=this.get(doc.$loki,true),position=arr[1];var self=this;Object.keys(this.constraints.unique).forEach(function(key){if(doc[key]!==null&&typeof doc[key]!=="undefined"){self.constraints.unique[key].remove(doc[key])}});for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].removeDocument(position)}this.data.splice(position,1);this.idIndex.splice(position,1);this.commit();this.dirty=true;this.emit("delete",arr[0]);delete doc.$loki;delete doc.meta;return doc}catch(err){this.rollback();console.error(err.message);this.emit("error",err);return null}};Collection.prototype.get=function(id,returnPosition){var retpos=returnPosition||false,data=this.idIndex,max=data.length-1,min=0,mid=Math.floor(min+(max-min)/2);id=typeof id==="number"?id:parseInt(id,10);if(isNaN(id)){throw"Passed id is not an integer"}while(data[min]<data[max]){mid=Math.floor((min+max)/2);if(data[mid]<id){min=mid+1}else{max=mid}}if(max===min&&data[min]===id){if(retpos){return[this.data[min],min]}return this.data[min]}return null};Collection.prototype.by=function(field,value){var self;if(!value){self=this;return function(value){return self.by(field,value)}}return this.constraints.unique[field].get(value)};Collection.prototype.findOne=function(query){var result=new Resultset(this,query,null,true);if(Array.isArray(result)&&result.length===0){return null}else{return result}};Collection.prototype.chain=function(transform,parameters){var rs=new Resultset(this,null,null);if(typeof transform==="undefined"){return rs}if(typeof transform==="string"){if(this.transforms.hasOwnProperty(transform)){transform=this.transforms[transform]}}if(typeof transform==="object"&&Array.isArray(transform)){return rs.transform(transform,parameters)}return null};Collection.prototype.find=function(query){if(typeof query==="undefined"){query="getAll"}return new Resultset(this,query,null)};Collection.prototype.findOneUnindexed=function(prop,value){var i=this.data.length,doc;while(i--){if(this.data[i][prop]===value){doc=this.data[i];return doc}}return null};Collection.prototype.startTransaction=function(){if(this.transactional){this.cachedData=clone(this.data,"parse-stringify");this.cachedIndex=this.idIndex;this.cachedBinaryIndex=this.binaryIndices;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].startTransaction()}}};Collection.prototype.commit=function(){if(this.transactional){this.cachedData=null;this.cachedIndex=null;this.cachedBinaryIndices=null;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].commit()}}};Collection.prototype.rollback=function(){if(this.transactional){if(this.cachedData!==null&&this.cachedIndex!==null){this.data=this.cachedData;this.idIndex=this.cachedIndex;this.binaryIndices=this.cachedBinaryIndex}for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].rollback()}}};Collection.prototype.async=function(fun,callback){setTimeout(function(){if(typeof fun==="function"){fun();callback()}else{throw"Argument passed for async execution is not a function"}},0)};Collection.prototype.where=function(fun){return new Resultset(this,null,fun)};Collection.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data.map(mapFunction))}catch(err){throw err}};Collection.prototype.eqJoin=function(joinData,leftJoinProp,rightJoinProp,mapFun){return new Resultset(this).eqJoin(joinData,leftJoinProp,rightJoinProp,mapFun)};Collection.prototype.stages={};Collection.prototype.getStage=function(name){if(!this.stages[name]){this.stages[name]={}}return this.stages[name]};Collection.prototype.commitLog=[];Collection.prototype.stage=function(stageName,obj){var copy=JSON.parse(JSON.stringify(obj));this.getStage(stageName)[obj.$loki]=copy;return copy};Collection.prototype.commitStage=function(stageName,message){var stage=this.getStage(stageName),prop,timestamp=(new Date).getTime();for(prop in stage){this.update(stage[prop]);this.commitLog.push({timestamp:timestamp,message:message,data:JSON.parse(JSON.stringify(stage[prop]))})}this.stages[stageName]={}};Collection.prototype.no_op=function(){return};Collection.prototype.extract=function(field){var i=0,len=this.data.length,isDotNotation=isDeepProperty(field),result=[];for(i;i<len;i+=1){result.push(deepProperty(this.data[i],field,isDotNotation))}return result};Collection.prototype.max=function(field){return Math.max.apply(null,this.extract(field))};Collection.prototype.min=function(field){return Math.min.apply(null,this.extract(field))};Collection.prototype.maxRecord=function(field){var i=0,len=this.data.length,deep=isDeepProperty(field),result={index:0,value:undefined},max;for(i;i<len;i+=1){if(max!==undefined){if(max<deepProperty(this.data[i],field,deep)){max=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}else{max=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}result.value=max;return result};Collection.prototype.minRecord=function(field){var i=0,len=this.data.length,deep=isDeepProperty(field),result={index:0,value:undefined},min;for(i;i<len;i+=1){if(min!==undefined){if(min>deepProperty(this.data[i],field,deep)){min=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}else{min=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}result.value=min;return result};Collection.prototype.extractNumerical=function(field){return this.extract(field).map(parseBase10).filter(Number).filter(function(n){return!isNaN(n)})};Collection.prototype.avg=function(field){return average(this.extractNumerical(field))};Collection.prototype.stdDev=function(field){return standardDeviation(this.extractNumerical(field))};Collection.prototype.mode=function(field){var dict={},data=this.extract(field);data.forEach(function(obj){if(dict[obj]){dict[obj]+=1}else{dict[obj]=1}});var max,prop,mode;for(prop in dict){if(max){if(max<dict[prop]){mode=prop}}else{mode=prop;max=dict[prop]}}return mode};Collection.prototype.median=function(field){var values=this.extractNumerical(field);values.sort(sub);var half=Math.floor(values.length/2);if(values.length%2){return values[half]}else{return(values[half-1]+values[half])/2}};function isDeepProperty(field){return field.indexOf(".")!==-1}function parseBase10(num){return parseFloat(num,10)}function isNotUndefined(obj){return obj!==undefined}function add(a,b){return a+b}function sub(a,b){return a-b}function median(values){values.sort(sub);var half=Math.floor(values.length/2);return values.length%2?values[half]:(values[half-1]+values[half])/2}function average(array){return array.reduce(add,0)/array.length}function standardDeviation(values){var avg=average(values);var squareDiffs=values.map(function(value){var diff=value-avg;var sqrDiff=diff*diff;return sqrDiff});var avgSquareDiff=average(squareDiffs);var stdDev=Math.sqrt(avgSquareDiff);return stdDev}function deepProperty(obj,property,isDeep){if(isDeep===false){return obj[property]}var pieces=property.split("."),root=obj;while(pieces.length>0){root=root[pieces.shift()]}return root}function binarySearch(array,item,fun){var lo=0,hi=array.length,compared,mid;while(lo<hi){mid=(lo+hi)/2|0;compared=fun.apply(null,[item,array[mid]]);if(compared===0){return{found:true,index:mid}}else if(compared<0){hi=mid}else{lo=mid+1}}return{found:false,index:hi}}function BSonSort(fun){return function(array,item){return binarySearch(array,item,fun)}}function KeyValueStore(){}KeyValueStore.prototype={keys:[],values:[],sort:function(a,b){return a<b?-1:a>b?1:0},setSort:function(fun){this.bs=new BSonSort(fun)},bs:function(){return new BSonSort(this.sort)},set:function(key,value){var pos=this.bs(this.keys,key);if(pos.found){this.values[pos.index]=value}else{this.keys.splice(pos.index,0,key);this.values.splice(pos.index,0,value)}},get:function(key){return this.values[binarySearch(this.keys,key,this.sort).index]}};function UniqueIndex(uniqueField){this.field=uniqueField;this.keyMap={};this.lokiMap={}}UniqueIndex.prototype.keyMap={};UniqueIndex.prototype.lokiMap={};UniqueIndex.prototype.set=function(obj){if(obj[this.field]!==null&&typeof obj[this.field]!=="undefined"){if(this.keyMap[obj[this.field]]){throw new Error("Duplicate key for property "+this.field+": "+obj[this.field])}else{this.keyMap[obj[this.field]]=obj;this.lokiMap[obj.$loki]=obj[this.field]}}};UniqueIndex.prototype.get=function(key){return this.keyMap[key]};UniqueIndex.prototype.byId=function(id){return this.keyMap[this.lokiMap[id]]};UniqueIndex.prototype.update=function(obj){if(this.lokiMap[obj.$loki]!==obj[this.field]){var old=this.lokiMap[obj.$loki];this.set(obj);this.keyMap[old]=undefined}else{this.keyMap[obj[this.field]]=obj}};UniqueIndex.prototype.remove=function(key){var obj=this.keyMap[key];if(obj!==null&&typeof obj!=="undefined"){this.keyMap[key]=undefined;this.lokiMap[obj.$loki]=undefined}else{throw new Error("Key is not in unique index: "+this.field)}};UniqueIndex.prototype.clear=function(){this.keyMap={};this.lokiMap={}};function ExactIndex(exactField){this.index={};this.field=exactField}ExactIndex.prototype={set:function add(key,val){if(this.index[key]){this.index[key].push(val)}else{this.index[key]=[val]}},remove:function remove(key,val){var idxSet=this.index[key];for(var i in idxSet){if(idxSet[i]==val){idxSet.splice(i,1)}}if(idxSet.length<1){this.index[key]=undefined}},get:function get(key){return this.index[key]},clear:function clear(key){this.index={}}};function SortedIndex(sortedField){this.field=sortedField}SortedIndex.prototype={keys:[],values:[],sort:function(a,b){return a<b?-1:a>b?1:0},bs:function(){return new BSonSort(this.sort)},setSort:function(fun){this.bs=new BSonSort(fun)},set:function(key,value){var pos=binarySearch(this.keys,key,this.sort);if(pos.found){this.values[pos.index].push(value)}else{this.keys.splice(pos.index,0,key);this.values.splice(pos.index,0,[value])}},get:function(key){var bsr=binarySearch(this.keys,key,this.sort);if(bsr.found){return this.values[bsr.index]}else{return[]}},getLt:function(key){var bsr=binarySearch(this.keys,key,this.sort);var pos=bsr.index;if(bsr.found)pos--;return this.getAll(key,0,pos)},getGt:function(key){var bsr=binarySearch(this.keys,key,this.sort);var pos=bsr.index;if(bsr.found)pos++;return this.getAll(key,pos,this.keys.length)},getAll:function(key,start,end){var results=[];for(var i=start;i<end;i++){results=results.concat(this.values[i])}return results},getPos:function(key){return binarySearch(this.keys,key,this.sort)},remove:function(key,value){var pos=binarySearch(this.keys,key,this.sort).index;var idxSet=this.values[pos];for(var i in idxSet){if(idxSet[i]==value)idxSet.splice(i,1)}if(idxSet.length<1){this.keys.splice(pos,1);this.values.splice(pos,1)}},clear:function(){this.keys=[];this.values=[]}};Loki.Collection=Collection;Loki.KeyValueStore=KeyValueStore;return Loki}()});
(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.loki=factory()}})(this,function(){return function(){"use strict";var Utils={copyProperties:function(src,dest){var prop;for(prop in src){dest[prop]=src[prop]}},resolveTransformObject:function(subObj,params,depth){var prop,pname;if(typeof depth!=="number"){depth=0}if(++depth>=10)return subObj;for(prop in subObj){if(typeof subObj[prop]==="string"&&subObj[prop].indexOf("[%lktxp]")===0){pname=subObj[prop].substring(8);if(params.hasOwnProperty(pname)){subObj[prop]=params[pname]}}else if(typeof subObj[prop]==="object"){subObj[prop]=Utils.resolveTransformObject(subObj[prop],params,depth)}}return subObj},resolveTransformParams:function(transform,params){var idx,prop,clonedStep,resolvedTransform=[];if(typeof params==="undefined")return transform;for(idx=0;idx<transform.length;idx++){clonedStep=JSON.parse(JSON.stringify(transform[idx]));resolvedTransform.push(Utils.resolveTransformObject(clonedStep,params))}return resolvedTransform}};function ltHelper(prop1,prop2,equal){if(prop1===undefined||prop1===null||prop1===false||prop2===true){return true}if(prop2===undefined||prop2===null||prop1===true||prop2===false){return false}if(prop1<prop2){return true}if(prop1>prop2){return false}if(equal){return true}else{return false}}function gtHelper(prop1,prop2,equal){if(prop1===undefined||prop1===null||prop1===false||prop2===true){return false}if(prop2===undefined||prop2===null||prop1===true||prop2===false){return true}if(prop1>prop2){return true}if(prop1<prop2){return false}if(equal){return true}else{return false}}function sortHelper(prop1,prop2,desc){if(ltHelper(prop1,prop2)){if(desc){return 1}else{return-1}}if(gtHelper(prop1,prop2)){if(desc){return-1}else{return 1}}return 0}function containsCheckFn(a,b){if(Array.isArray(a)){return function(curr){return a.indexOf(curr)!==-1}}else if(a&&typeof a==="string"){return function(curr){return a.indexOf(curr)!==-1}}else if(a&&typeof a==="object"){return function(curr){return a.hasOwnProperty(curr)}}}var LokiOps={$eq:function(a,b){return a===b},$dteq:function(a,b){if(ltHelper(a,b)){return false}if(gtHelper(a,b)){return false}return true},$gt:function(a,b){return gtHelper(a,b)},$gte:function(a,b){return gtHelper(a,b,true)},$lt:function(a,b){return ltHelper(a,b)},$lte:function(a,b){return ltHelper(a,b,true)},$ne:function(a,b){return a!==b},$regex:function(a,b){return b.test(a)},$in:function(a,b){return b.indexOf(a)>-1},$nin:function(a,b){return b.indexOf(a)==-1},$containsNone:function(a,b){return!LokiOps.$containsAny(a,b)},$containsAny:function(a,b){var checkFn;if(!Array.isArray(b)){b=[b]}checkFn=containsCheckFn(a,b)||function(){return false};return b.reduce(function(prev,curr){if(prev){return prev}return checkFn(curr)},false)},$contains:function(a,b){var checkFn;if(!Array.isArray(b)){b=[b]}checkFn=containsCheckFn(a,b)||function(){return false};return b.reduce(function(prev,curr){if(!prev){return prev}return checkFn(curr)},true)}};var operators={$eq:LokiOps.$eq,$dteq:LokiOps.$dteq,$gt:LokiOps.$gt,$gte:LokiOps.$gte,$lt:LokiOps.$lt,$lte:LokiOps.$lte,$ne:LokiOps.$ne,$regex:LokiOps.$regex,$in:LokiOps.$in,$nin:LokiOps.$nin,$contains:LokiOps.$contains,$containsAny:LokiOps.$containsAny,$containsNone:LokiOps.$containsNone};var indexedOpsList=["$eq","$dteq","$gt","$gte","$lt","$lte"];function clone(data,method){var cloneMethod=method||"parse-stringify",cloned;switch(cloneMethod){case"parse-stringify":cloned=JSON.parse(JSON.stringify(data));break;case"jquery-extend-deep":cloned=jQuery.extend(true,{},data);break;case"shallow":cloned=Object.create(data.prototype||null);Object.keys(data).map(function(i){cloned[i]=data[i]});break;default:break}return cloned}function cloneObjectArray(objarray,method){var i,result=[];if(method=="parse-stringify"){return clone(objarray,method)}i=objarray.length-1;for(;i<=0;i--){result.push(clone(objarray[i],method))}return result}function localStorageAvailable(){try{return"localStorage"in window&&window.localStorage!==null}catch(e){return false}}function LokiEventEmitter(){}LokiEventEmitter.prototype.events={};LokiEventEmitter.prototype.asyncListeners=false;LokiEventEmitter.prototype.on=function(eventName,listener){var event=this.events[eventName];if(!event){event=this.events[eventName]=[]}event.push(listener);return listener};LokiEventEmitter.prototype.emit=function(eventName,data){var self=this;if(eventName&&this.events[eventName]){this.events[eventName].forEach(function(listener){if(self.asyncListeners){setTimeout(function(){listener(data)},1)}else{listener(data)}})}else{throw new Error("No event "+eventName+" defined")}};LokiEventEmitter.prototype.removeListener=function(eventName,listener){if(this.events[eventName]){var listeners=this.events[eventName];listeners.splice(listeners.indexOf(listener),1)}};function Loki(filename,options){this.filename=filename||"loki.db";this.collections=[];this.databaseVersion=1.1;this.engineVersion=1.1;this.autosave=false;this.autosaveInterval=5e3;this.autosaveHandle=null;this.options={};this.persistenceMethod=null;this.persistenceAdapter=null;this.verbose=options&&options.hasOwnProperty("verbose")?options.verbose:false;this.events={init:[],loaded:[],flushChanges:[],close:[],changes:[],warning:[]};var getENV=function(){if(typeof window==="undefined"){return"NODEJS"}if(typeof global!=="undefined"&&global.window){return"NODEJS"}if(typeof document!=="undefined"){if(document.URL.indexOf("http://")===-1&&document.URL.indexOf("https://")===-1){return"CORDOVA"}return"BROWSER"}return"CORDOVA"};if(options&&options.hasOwnProperty("env")){this.ENV=options.env}else{this.ENV=getENV()}if(this.ENV==="undefined"){this.ENV="NODEJS"}this.configureOptions(options,true);this.on("init",this.clearChanges)}Loki.prototype=new LokiEventEmitter;Loki.prototype.getIndexedAdapter=function(){var adapter;if(typeof require==="function"){adapter=require("./loki-indexed-adapter.js")}return adapter};Loki.prototype.configureOptions=function(options,initialConfig){var defaultPersistence={NODEJS:"fs",BROWSER:"localStorage",CORDOVA:"localStorage"},persistenceMethods={fs:LokiFsAdapter,localStorage:LokiLocalStorageAdapter};this.options={};this.persistenceMethod=null;this.persistenceAdapter=null;if(typeof options!=="undefined"){this.options=options;if(this.options.hasOwnProperty("persistenceMethod")){if(typeof persistenceMethods[options.persistenceMethod]=="function"){this.persistenceMethod=options.persistenceMethod;this.persistenceAdapter=new persistenceMethods[options.persistenceMethod]}}if(this.options.hasOwnProperty("adapter")){this.persistenceMethod="adapter";this.persistenceAdapter=options.adapter;this.options.adapter=null}if(options.autoload&&initialConfig){var self=this;setTimeout(function(){self.loadDatabase(options,options.autoloadCallback)},1)}if(this.options.hasOwnProperty("autosaveInterval")){this.autosaveDisable();this.autosaveInterval=parseInt(this.options.autosaveInterval,10)}if(this.options.hasOwnProperty("autosave")&&this.options.autosave){this.autosaveDisable();this.autosave=true;if(this.options.hasOwnProperty("autosaveCallback")){this.autosaveEnable(options,options.autosaveCallback)}else{this.autosaveEnable()}}}if(this.persistenceAdapter===null){this.persistenceMethod=defaultPersistence[this.ENV];if(this.persistenceMethod){this.persistenceAdapter=new persistenceMethods[this.persistenceMethod]}}};Loki.prototype.anonym=function(docs,indexesArray){var collection=new Collection("anonym",indexesArray);collection.insert(docs);if(this.verbose)collection.console=console;return collection};Loki.prototype.addCollection=function(name,options){var collection=new Collection(name,options);this.collections.push(collection);if(this.verbose)collection.console=console;return collection};Loki.prototype.loadCollection=function(collection){if(!collection.name){throw new Error("Collection must have a name property to be loaded")}this.collections.push(collection)};Loki.prototype.getCollection=function(collectionName){var i,len=this.collections.length;for(i=0;i<len;i+=1){if(this.collections[i].name===collectionName){return this.collections[i]}}this.emit("warning","collection "+collectionName+" not found");return null};Loki.prototype.listCollections=function(){var i=this.collections.length,colls=[];while(i--){colls.push({name:this.collections[i].name,type:this.collections[i].objType,count:this.collections[i].data.length})}return colls};Loki.prototype.removeCollection=function(collectionName){var i,len=this.collections.length;for(i=0;i<len;i+=1){if(this.collections[i].name===collectionName){this.collections.splice(i,1);return}}};Loki.prototype.getName=function(){return this.name};Loki.prototype.serializeReplacer=function(key,value){switch(key){case"autosaveHandle":case"persistenceAdapter":case"constraints":return null;default:return value}};Loki.prototype.serialize=function(){return JSON.stringify(this,this.serializeReplacer)};Loki.prototype.toJson=Loki.prototype.serialize;Loki.prototype.loadJSON=function(serializedDb,options){if(serializedDb.length===0)serializedDb=JSON.stringify({});var obj=JSON.parse(serializedDb),i=0,len=obj.collections?obj.collections.length:0,coll,copyColl,clen,j;this.name=obj.name;this.databaseVersion=1;if(obj.hasOwnProperty("databaseVersion")){this.databaseVersion=obj.databaseVersion}this.collections=[];for(i;i<len;i+=1){coll=obj.collections[i];copyColl=this.addCollection(coll.name);copyColl.transactional=coll.transactional;copyColl.asyncListeners=coll.asyncListeners;copyColl.disableChangesApi=coll.disableChangesApi;copyColl.cloneObjects=coll.cloneObjects;copyColl.cloneMethod=coll.cloneMethod||"parse-stringify";copyColl.autoupdate=coll.autoupdate;clen=coll.data.length;j=0;if(options&&options.hasOwnProperty(coll.name)){var loader=options[coll.name].inflate?options[coll.name].inflate:Utils.copyProperties;for(j;j<clen;j++){var collObj=new options[coll.name].proto;loader(coll.data[j],collObj);copyColl.data[j]=collObj;copyColl.addAutoUpdateObserver(collObj)}}else{for(j;j<clen;j++){copyColl.data[j]=coll.data[j];copyColl.addAutoUpdateObserver(copyColl.data[j])}}copyColl.maxId=coll.data.length===0?0:coll.maxId;copyColl.idIndex=coll.idIndex;if(typeof coll.binaryIndices!=="undefined"){copyColl.binaryIndices=coll.binaryIndices}if(typeof coll.transforms!=="undefined"){copyColl.transforms=coll.transforms}copyColl.ensureId();copyColl.uniqueNames=[];if(coll.hasOwnProperty("uniqueNames")){copyColl.uniqueNames=coll.uniqueNames;for(j=0;j<copyColl.uniqueNames.length;j++){copyColl.ensureUniqueIndex(copyColl.uniqueNames[j])}}if(typeof coll.DynamicViews==="undefined")continue;for(var idx=0;idx<coll.DynamicViews.length;idx++){var colldv=coll.DynamicViews[idx];var dv=copyColl.addDynamicView(colldv.name,colldv.options);dv.resultdata=colldv.resultdata;dv.resultsdirty=colldv.resultsdirty;dv.filterPipeline=colldv.filterPipeline;dv.sortCriteria=colldv.sortCriteria;dv.sortFunction=null;dv.sortDirty=colldv.sortDirty;dv.resultset.filteredrows=colldv.resultset.filteredrows;dv.resultset.searchIsChained=colldv.resultset.searchIsChained;dv.resultset.filterInitialized=colldv.resultset.filterInitialized;dv.rematerialize({removeWhereFilters:true})}}};Loki.prototype.close=function(callback){if(this.autosave){this.autosaveDisable();if(this.autosaveDirty()){this.saveDatabase(callback);callback=undefined}}if(callback){this.on("close",callback)}this.emit("close")};Loki.prototype.generateChangesNotification=function(arrayOfCollectionNames){function getCollName(coll){return coll.name}var changes=[],selectedCollections=arrayOfCollectionNames||this.collections.map(getCollName);this.collections.forEach(function(coll){if(selectedCollections.indexOf(getCollName(coll))!==-1){changes=changes.concat(coll.getChanges())}});return changes};Loki.prototype.serializeChanges=function(collectionNamesArray){return JSON.stringify(this.generateChangesNotification(collectionNamesArray))};Loki.prototype.clearChanges=function(){this.collections.forEach(function(coll){if(coll.flushChanges){coll.flushChanges()}})};function LokiFsAdapter(){this.fs=require("fs")}LokiFsAdapter.prototype.loadDatabase=function loadDatabase(dbname,callback){this.fs.readFile(dbname,{encoding:"utf8"},function readFileCallback(err,data){if(err){callback(new Error(err))}else{callback(data)}})};LokiFsAdapter.prototype.saveDatabase=function saveDatabase(dbname,dbstring,callback){this.fs.writeFile(dbname,dbstring,callback)};function LokiLocalStorageAdapter(){}LokiLocalStorageAdapter.prototype.loadDatabase=function loadDatabase(dbname,callback){if(localStorageAvailable()){callback(localStorage.getItem(dbname))}else{callback(new Error("localStorage is not available"))}};LokiLocalStorageAdapter.prototype.saveDatabase=function saveDatabase(dbname,dbstring,callback){if(localStorageAvailable()){localStorage.setItem(dbname,dbstring);callback(null)}else{callback(new Error("localStorage is not available"))}};Loki.prototype.loadDatabase=function(options,callback){var cFun=callback||function(err,data){if(err){throw err}return},self=this;if(this.persistenceAdapter!==null){this.persistenceAdapter.loadDatabase(this.filename,function loadDatabaseCallback(dbString){if(typeof dbString==="string"){self.loadJSON(dbString,options||{});cFun(null);self.emit("loaded","database "+self.filename+" loaded")}else{if(typeof dbString==="object"){cFun(dbString)}else{cFun("Database not found")}}})}else{cFun(new Error("persistenceAdapter not configured"))}};Loki.prototype.saveDatabase=function(callback){var cFun=callback||function(err){if(err){throw err}return},self=this;if(this.persistenceAdapter!==null){if(this.persistenceAdapter.mode==="reference"&&typeof this.persistenceAdapter.exportDatabase==="function"){this.persistenceAdapter.exportDatabase(this.filename,this,function exportDatabaseCallback(err){self.autosaveClearFlags();cFun(err)})}else{this.persistenceAdapter.saveDatabase(this.filename,self.serialize(),function saveDatabasecallback(err){self.autosaveClearFlags();cFun(err)})}}else{cFun(new Error("persistenceAdapter not configured"))}};Loki.prototype.save=Loki.prototype.saveDatabase;Loki.prototype.autosaveDirty=function(){for(var idx=0;idx<this.collections.length;idx++){if(this.collections[idx].dirty){return true}}return false};Loki.prototype.autosaveClearFlags=function(){for(var idx=0;idx<this.collections.length;idx++){this.collections[idx].dirty=false}};Loki.prototype.autosaveEnable=function(options,callback){this.autosave=true;var delay=5e3,self=this;if(typeof this.autosaveInterval!=="undefined"&&this.autosaveInterval!==null){delay=this.autosaveInterval}this.autosaveHandle=setInterval(function autosaveHandleInterval(){if(self.autosaveDirty()){self.saveDatabase(callback)}},delay)};Loki.prototype.autosaveDisable=function(){if(typeof this.autosaveHandle!=="undefined"&&this.autosaveHandle!==null){clearInterval(this.autosaveHandle);this.autosaveHandle=null}};function Resultset(collection,queryObj,queryFunc,firstOnly){this.collection=collection;this.searchIsChained=!queryObj&&!queryFunc;this.filteredrows=[];this.filterInitialized=false;if(typeof queryObj!=="undefined"&&queryObj!==null){return this.find(queryObj,firstOnly)}if(typeof queryFunc!=="undefined"&&queryFunc!==null){return this.where(queryFunc)}return this}Resultset.prototype.toJSON=function(){var copy=this.copy();copy.collection=null;return copy};Resultset.prototype.limit=function(qty){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data).map(Number)}var rscopy=this.copy();rscopy.filteredrows=rscopy.filteredrows.slice(0,qty);return rscopy};Resultset.prototype.offset=function(pos){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data).map(Number)}var rscopy=this.copy();rscopy.filteredrows=rscopy.filteredrows.splice(pos,rscopy.filteredrows.length);return rscopy};Resultset.prototype.copy=function(){var result=new Resultset(this.collection,null,null);result.filteredrows=this.filteredrows.slice();result.filterInitialized=this.filterInitialized;return result};Resultset.prototype.branch=Resultset.prototype.copy;Resultset.prototype.transform=function(transform,parameters){var idx,step,rs=this;if(typeof transform==="string"){if(this.collection.transforms.hasOwnProperty(transform)){transform=this.collection.transforms[transform]}}if(typeof transform!=="object"||!Array.isArray(transform)){throw new Error("Invalid transform")}if(typeof parameters!=="undefined"){transform=Utils.resolveTransformParams(transform,parameters)}for(idx=0;idx<transform.length;idx++){step=transform[idx];switch(step.type){case"find":rs.find(step.value);break;case"where":rs.where(step.value);break;case"simplesort":rs.simplesort(step.property,step.desc);break;case"compoundsort":rs.compoundsort(step.value);break;case"sort":rs.sort(step.value);break;case"limit":rs=rs.limit(step.value);break;case"offset":rs=rs.offset(step.value);break;case"map":rs=rs.map(step.value);break;case"eqJoin":rs=rs.eqJoin(step.joinData,step.leftJoinKey,step.rightJoinKey,step.mapFun);break;case"mapReduce":rs=rs.mapReduce(step.mapFunction,step.reduceFunction);break;case"update":rs.update(step.value);break;case"remove":rs.remove();break;default:break}}return rs};Resultset.prototype.sort=function(comparefun){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data).map(Number)}var wrappedComparer=function(userComparer,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return userComparer(obj1,obj2)}}(comparefun,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.simplesort=function(propname,isdesc){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data).map(Number)}if(typeof isdesc==="undefined"){isdesc=false}var wrappedComparer=function(prop,desc,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return sortHelper(obj1[prop],obj2[prop],desc)}}(propname,isdesc,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.compoundeval=function(properties,obj1,obj2){var propertyCount=properties.length;if(propertyCount===0){throw new Error("Invalid call to compoundeval, need at least one property")}var isdesc=false;var firstProp=properties[0];if(typeof firstProp!=="string"){if(Array.isArray(firstProp)){isdesc=firstProp[1];firstProp=firstProp[0]}}if(obj1[firstProp]===obj2[firstProp]){if(propertyCount===1){return 0}else{return this.compoundeval(properties.slice(1),obj1,obj2,isdesc)}}return sortHelper(obj1[firstProp],obj2[firstProp],isdesc)};Resultset.prototype.compoundsort=function(properties){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data).map(Number)}var wrappedComparer=function(props,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return rslt.compoundeval(props,obj1,obj2)}}(properties,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.calculateRange=function(op,prop,val){var rcd=this.collection.data;var index=this.collection.binaryIndices[prop].values;var min=0;var max=index.length-1;var mid=null;var lbound=0;var ubound=index.length-1;if(rcd.length===0){return[0,-1]}var minVal=rcd[index[min]][prop];var maxVal=rcd[index[max]][prop];switch(op){case"$eq":if(ltHelper(val,minVal)||gtHelper(val,maxVal)){return[0,-1]}break;case"$dteq":if(ltHelper(val,minVal)||gtHelper(val,maxVal)){return[0,-1]}break;case"$gt":if(gtHelper(val,maxVal,true)){return[0,-1]}break;case"$gte":if(gtHelper(val,maxVal)){return[0,-1]}break;case"$lt":if(ltHelper(val,minVal,true)){return[0,-1]}if(ltHelper(maxVal,val)){return[0,rcd.length-1]}break;case"$lte":if(ltHelper(val,minVal)){return[0,-1]}if(ltHelper(maxVal,val,true)){return[0,rcd.length-1]}break}while(min<max){mid=Math.floor((min+max)/2);if(ltHelper(rcd[index[mid]][prop],val)){min=mid+1}else{max=mid}}lbound=min;min=0;max=index.length-1;while(min<max){mid=Math.floor((min+max)/2);if(ltHelper(val,rcd[index[mid]][prop])){max=mid}else{min=mid+1}}ubound=max;var lval=rcd[index[lbound]][prop];var uval=rcd[index[ubound]][prop];switch(op){case"$eq":if(lval!==val){return[0,-1]}if(uval!==val){ubound--}return[lbound,ubound];case"$dteq":if(lval>val||lval<val){return[0,-1]}if(uval>val||uval<val){ubound--}return[lbound,ubound];case"$gt":if(ltHelper(uval,val,true)){return[0,-1]}return[ubound,rcd.length-1];case"$gte":if(ltHelper(lval,val)){return[0,-1]}return[lbound,rcd.length-1];case"$lt":if(lbound===0&&ltHelper(lval,val)){return[0,0]}return[0,lbound-1];case"$lte":if(uval!==val){ubound--}if(ubound===0&&ltHelper(uval,val)){return[0,0]}return[0,ubound];default:return[0,rcd.length-1]}};Resultset.prototype.findOr=function(expressionArray){var fri=0,ei=0,fr=null,docset=[],expResultset=null;if(this.filterInitialized){docset=[];for(ei=0;ei<expressionArray.length;ei++){expResultset=this.branch();expResultset.find(expressionArray[ei]);expResultset.data();fr=expResultset.filteredrows;for(fri=0;fri<fr.length;fri++){if(docset.indexOf(fr[fri])===-1){docset.push(fr[fri])}}}this.filteredrows=docset}else{for(ei=0;ei<expressionArray.length;ei++){expResultset=this.collection.chain();expResultset.find(expressionArray[ei]);expResultset.data();fr=expResultset.filteredrows;for(fri=0;fri<fr.length;fri++){if(this.filteredrows.indexOf(fr[fri])===-1){this.filteredrows.push(fr[fri])}}}}this.filterInitialized=true;return this};Resultset.prototype.findAnd=function(expressionArray){for(var i=0;i<expressionArray.length;i++){this.find(expressionArray[i])}return this};Resultset.prototype.dotSubScan=function(root,property,fun,value){var arrayRef=null;var pathIndex,subIndex;var paths=property.split(".");var path;for(pathIndex=0;pathIndex<paths.length;pathIndex++){path=paths[pathIndex];if(arrayRef){for(subIndex=0;subIndex<arrayRef.length;subIndex++){if(fun(arrayRef[subIndex][path],value)){return true}}}else{if(typeof root==="undefined"||root===null||!root.hasOwnProperty(path)){return false}root=root[path];if(Array.isArray(root)){arrayRef=root}}}return fun(root,value)};Resultset.prototype.find=function(query,firstOnly){if(this.collection.data.length===0){if(this.searchIsChained){this.filteredrows=[];this.filterInitialized=true;return this}return[]}var queryObject=query||"getAll",property,value,operator,p,key,searchByIndex=false,result=[],index=null,fun,t,i,emptyQO=true;firstOnly=firstOnly||false;for(p in queryObject){emptyQO=false;break}if(emptyQO){queryObject="getAll"}if(queryObject==="getAll"){if(this.searchIsChained){this.filteredrows=Object.keys(this.collection.data).map(Number);this.filterInitialized=true;return this}else{return this.collection.data.slice()}}var usingDotNotation=false;for(p in queryObject){if(queryObject.hasOwnProperty(p)){property=p;if(p==="$and"){if(this.searchIsChained){this.findAnd(queryObject[p]);if(firstOnly&&this.filteredrows.length>1){this.filteredrows=this.filteredrows.slice(0,1)}return this}else{result=this.collection.chain().findAnd(queryObject[p]).data();if(firstOnly){if(result.length===0)return[];return result[0]}return result}}if(p==="$or"){if(this.searchIsChained){this.findOr(queryObject[p]);if(firstOnly&&this.filteredrows.length>1){this.filteredrows=this.filteredrows.slice(0,1)}return this}else{result=this.collection.chain().findOr(queryObject[p]).data();if(firstOnly){if(result.length===0)return[];return result[0]}return result}}if(p.indexOf(".")!=-1){usingDotNotation=true}if(queryObject[p]===null||(typeof queryObject[p]!=="object"||queryObject[p]instanceof Date)){operator="$eq";value=queryObject[p]}else if(typeof queryObject[p]==="object"){for(key in queryObject[p]){if(queryObject[p].hasOwnProperty(key)){operator=key;value=queryObject[p][key]}}}else{throw new Error("Do not know what you want to do.")}break}}if(operator==="$regex"){if(typeof value==="object"&&Array.isArray(value)){value=new RegExp(value[0],value[1])}else{value=new RegExp(value)}}if(this.collection.data===null){throw new TypeError}if((!this.searchIsChained||this.searchIsChained&&!this.filterInitialized)&&indexedOpsList.indexOf(operator)!==-1&&this.collection.binaryIndices.hasOwnProperty(property)){this.collection.ensureIndex(property);searchByIndex=true;index=this.collection.binaryIndices[property]}fun=operators[operator];if(!this.searchIsChained){if(!searchByIndex){t=this.collection.data;i=t.length;if(firstOnly){if(usingDotNotation){while(i--){if(this.dotSubScan(t[i],property,fun,value)){return t[i]}}}else{while(i--){if(fun(t[i][property],value)){return t[i]}}}return[]}else{if(usingDotNotation){while(i--){if(this.dotSubScan(t[i],property,fun,value)){result.push(t[i])}}}else{while(i--){if(fun(t[i][property],value)){result.push(t[i])}}}}}else{t=this.collection.data;var seg=this.calculateRange(operator,property,value,this);if(firstOnly){if(seg[1]!==-1){return t[index.values[seg[0]]]}return[]}for(i=seg[0];i<=seg[1];i++){result.push(t[index.values[i]])}this.filteredrows=result}return result}else{if(this.filterInitialized){if(!searchByIndex){t=this.collection.data;i=this.filteredrows.length;if(usingDotNotation){while(i--){if(this.dotSubScan(t[this.filteredrows[i]],property,fun,value)){result.push(this.filteredrows[i])}}}else{while(i--){if(fun(t[this.filteredrows[i]][property],value)){result.push(this.filteredrows[i])}}}}else{t=index;i=this.filteredrows.length;while(i--){if(fun(t[this.filteredrows[i]],value)){result.push(this.filteredrows[i])}}}this.filteredrows=result;return this}else{if(!searchByIndex){t=this.collection.data;i=t.length;if(usingDotNotation){while(i--){if(this.dotSubScan(t[i],property,fun,value)){result.push(i)}}}else{while(i--){if(fun(t[i][property],value)){result.push(i)}}}}else{t=this.collection.data;var segm=this.calculateRange(operator,property,value,this);for(var idx=segm[0];idx<=segm[1];idx++){result.push(index.values[idx])}this.filteredrows=result}this.filteredrows=result;this.filterInitialized=true;return this}}};Resultset.prototype.where=function(fun){var viewFunction,result=[];if("function"===typeof fun){viewFunction=fun}else{throw new TypeError("Argument is not a stored view or a function")}try{if(!this.searchIsChained){var i=this.collection.data.length;while(i--){if(viewFunction(this.collection.data[i])===true){result.push(this.collection.data[i])}}return result}else{if(this.filterInitialized){var j=this.filteredrows.length;while(j--){if(viewFunction(this.collection.data[this.filteredrows[j]])===true){result.push(this.filteredrows[j])}}this.filteredrows=result;return this}else{var k=this.collection.data.length;while(k--){if(viewFunction(this.collection.data[k])===true){result.push(k)}}this.filteredrows=result;this.filterInitialized=true;return this}}}catch(err){throw err}};Resultset.prototype.data=function(options){var result=[],cd,cl;options=options||{};if(this.searchIsChained&&!this.filterInitialized){if(this.filteredrows.length===0){if(this.collection.cloneObjects||options.forceClones){cd=this.collection.data;cl=cl.length;for(i=0;i<cl;i++){result.push(clone(cd[i],options.forceCloneMethod||this.collection.cloneMethod))}}else{return this.collection.data.slice()}}else{this.filterInitialized=true}}var data=this.collection.data,fr=this.filteredrows;var i,len=this.filteredrows.length;for(i=0;i<len;i++){if(this.collection.cloneObjects||options.forceClones){result.push(clone(data[fr[i]],options.forceCloneMethod||this.collection.cloneMethod))}else{result.push(data[fr[i]])}}return result};Resultset.prototype.update=function(updateFunction){if(typeof updateFunction!=="function"){throw new TypeError("Argument is not a function")}if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data).map(Number)}var len=this.filteredrows.length,rcd=this.collection.data;for(var idx=0;idx<len;idx++){updateFunction(rcd[this.filteredrows[idx]]);this.collection.update(rcd[this.filteredrows[idx]])}return this};Resultset.prototype.remove=function(){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data).map(Number)}this.collection.remove(this.data());this.filteredrows=[];return this};Resultset.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data().map(mapFunction))}catch(err){throw err}};Resultset.prototype.eqJoin=function(joinData,leftJoinKey,rightJoinKey,mapFun){var leftData=[],leftDataLength,rightData=[],rightDataLength,key,result=[],obj,leftKeyisFunction=typeof leftJoinKey==="function",rightKeyisFunction=typeof rightJoinKey==="function",joinMap={};leftData=this.data();leftDataLength=leftData.length;if(joinData instanceof Resultset){rightData=joinData.data()}else if(Array.isArray(joinData)){rightData=joinData}else{throw new TypeError("joinData needs to be an array or result set")}rightDataLength=rightData.length;for(var i=0;i<rightDataLength;i++){key=rightKeyisFunction?rightJoinKey(rightData[i]):rightData[i][rightJoinKey];joinMap[key]=rightData[i]}if(!mapFun){mapFun=function(left,right){return{left:left,right:right}}}for(var j=0;j<leftDataLength;j++){key=leftKeyisFunction?leftJoinKey(leftData[j]):leftData[j][leftJoinKey];result.push(mapFun(leftData[j],joinMap[key]||{}))}this.collection=new Collection("joinData");this.collection.insert(result);this.filteredrows=[];this.filterInitialized=false;return this};Resultset.prototype.map=function(mapFun){var data=this.data().map(mapFun);this.collection=new Collection("mappedData");this.collection.insert(data);this.filteredrows=[];this.filterInitialized=false;return this};function DynamicView(collection,name,options){this.collection=collection;this.name=name;this.rebuildPending=false;this.options=options||{};if(!this.options.hasOwnProperty("persistent")){this.options.persistent=false}if(!this.options.hasOwnProperty("sortPriority")){this.options.sortPriority="passive"}this.resultset=new Resultset(collection);this.resultdata=[];this.resultsdirty=false;this.cachedresultset=null;this.filterPipeline=[];this.sortFunction=null;this.sortCriteria=null;this.sortDirty=false;this.events={rebuild:[]}}DynamicView.prototype=new LokiEventEmitter;DynamicView.prototype.rematerialize=function(options){var fpl,fpi,idx;options=options||{};this.resultdata=[];this.resultsdirty=true;this.resultset=new Resultset(this.collection);if(this.sortFunction||this.sortCriteria){this.sortDirty=true}if(options.hasOwnProperty("removeWhereFilters")){fpl=this.filterPipeline.length;fpi=fpl;while(fpi--){if(this.filterPipeline[fpi].type==="where"){if(fpi!==this.filterPipeline.length-1){this.filterPipeline[fpi]=this.filterPipeline[this.filterPipeline.length-1]}this.filterPipeline.length--}}}var ofp=this.filterPipeline;this.filterPipeline=[];fpl=ofp.length;for(idx=0;idx<fpl;idx++){this.applyFind(ofp[idx].val)}this.data();this.emit("rebuild",this);return this};DynamicView.prototype.branchResultset=function(transform,parameters){var rs=this.resultset.branch();if(typeof transform==="undefined"){return rs}return rs.transform(transform,parameters)};DynamicView.prototype.toJSON=function(){var copy=new DynamicView(this.collection,this.name,this.options);copy.resultset=this.resultset;copy.resultdata=[];copy.resultsdirty=true;copy.filterPipeline=this.filterPipeline;copy.sortFunction=this.sortFunction;copy.sortCriteria=this.sortCriteria;copy.sortDirty=this.sortDirty;copy.collection=null;return copy};DynamicView.prototype.removeFilters=function(){this.rebuildPending=false;this.resultset=new Resultset(this.collection);this.resultdata=[];this.resultsdirty=false;this.cachedresultset=null;this.filterPipeline=[];this.sortFunction=null;this.sortCriteria=null;this.sortDirty=false};DynamicView.prototype.applySort=function(comparefun){this.sortFunction=comparefun;this.sortCriteria=null;this.queueSortPhase();return this;
};DynamicView.prototype.applySimpleSort=function(propname,isdesc){if(typeof isdesc==="undefined"){isdesc=false}this.sortCriteria=[[propname,isdesc]];this.sortFunction=null;this.queueSortPhase();return this};DynamicView.prototype.applySortCriteria=function(criteria){this.sortCriteria=criteria;this.sortFunction=null;this.queueSortPhase();return this};DynamicView.prototype.startTransaction=function(){this.cachedresultset=this.resultset.copy();return this};DynamicView.prototype.commit=function(){this.cachedresultset=null;return this};DynamicView.prototype.rollback=function(){this.resultset=this.cachedresultset;if(this.options.persistent){this.resultdata=this.resultset.data();this.emit("rebuild",this)}return this};DynamicView.prototype._indexOfFilterWithId=function(uid){if(typeof uid==="string"||typeof uid==="number"){for(var idx=0,len=this.filterPipeline.length;idx<len;idx+=1){if(uid===this.filterPipeline[idx].uid){return idx}}}return-1};DynamicView.prototype._addFilter=function(filter){this.resultset[filter.type](filter.val);this.filterPipeline.push(filter)};DynamicView.prototype.reapplyFilters=function(){var filters=this.filterPipeline;var sortFunction=this.sortFunction;var sortCriteria=this.sortCriteria;this.removeFilters();for(var idx=0,len=filters.length;idx<len;idx+=1){this._addFilter(filters[idx])}if(sortFunction!==null){this.applySort(sortFunction)}if(sortCriteria!==null){this.applySortCriteria(sortCriteria)}if(this.options.persistent){this.resultsdirty=true;this.queueSortPhase()}return this};DynamicView.prototype.applyFilter=function(filter){var idx=this._indexOfFilterWithId(filter.uid);if(idx>=0){this.filterPipeline[idx]=filter;this.reapplyFilters();return}this._addFilter(filter);if(this.sortFunction||this.sortCriteria){this.sortDirty=true;this.queueSortPhase()}if(this.options.persistent){this.resultsdirty=true;this.queueSortPhase()}return this};DynamicView.prototype.applyFind=function(query,uid){this.applyFilter({type:"find",val:query,uid:uid});return this};DynamicView.prototype.applyWhere=function(fun,uid){this.applyFilter({type:"where",val:fun,uid:uid});return this};DynamicView.prototype.removeFilter=function(uid){var idx=this._indexOfFilterWithId(uid);if(idx<0){throw new Error("Dynamic view does not contain a filter with ID: "+uid)}this.filterPipeline.splice(idx,1);this.reapplyFilters();return this};DynamicView.prototype.data=function(){if(this.filterPipeline.length===0){this.applyFind()}if(this.sortDirty||this.resultsdirty){this.performSortPhase()}if(!this.options.persistent){return this.resultset.data()}return this.resultdata};DynamicView.prototype.queueRebuildEvent=function(){var self=this;if(this.rebuildPending){return}this.rebuildPending=true;setTimeout(function(){self.rebuildPending=false;self.emit("rebuild",self)},1)};DynamicView.prototype.queueSortPhase=function(){var self=this;if(this.sortDirty){return}this.sortDirty=true;if(this.options.sortPriority==="active"){setTimeout(function(){self.performSortPhase()},1)}else{this.queueRebuildEvent()}};DynamicView.prototype.performSortPhase=function(){if(!this.sortDirty&&!this.resultsdirty){return}if(this.sortFunction){this.resultset.sort(this.sortFunction)}if(this.sortCriteria){this.resultset.compoundsort(this.sortCriteria)}if(!this.options.persistent){this.sortDirty=false;return}this.resultdata=this.resultset.data();this.resultsdirty=false;this.sortDirty=false;this.emit("rebuild",this)};DynamicView.prototype.evaluateDocument=function(objIndex){var ofr=this.resultset.filteredrows;var oldPos=ofr.indexOf(+objIndex);var oldlen=ofr.length;var evalResultset=new Resultset(this.collection);evalResultset.filteredrows=[objIndex];evalResultset.filterInitialized=true;for(var idx=0;idx<this.filterPipeline.length;idx++){switch(this.filterPipeline[idx].type){case"find":evalResultset.find(this.filterPipeline[idx].val);break;case"where":evalResultset.where(this.filterPipeline[idx].val);break}}var newPos=evalResultset.filteredrows.length===0?-1:0;if(oldPos==-1&&newPos==-1)return;if(oldPos===-1&&newPos!==-1){ofr.push(objIndex);if(this.options.persistent){this.resultdata.push(this.collection.data[objIndex])}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}else{this.queueRebuildEvent()}return}if(oldPos!==-1&&newPos===-1){if(oldPos<oldlen-1){ofr[oldPos]=ofr[oldlen-1];ofr.length=oldlen-1;if(this.options.persistent){this.resultdata[oldPos]=this.resultdata[oldlen-1];this.resultdata.length=oldlen-1}}else{ofr.length=oldlen-1;if(this.options.persistent){this.resultdata.length=oldlen-1}}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}else{this.queueRebuildEvent()}return}if(oldPos!==-1&&newPos!==-1){if(this.options.persistent){this.resultdata[oldPos]=this.collection.data[objIndex]}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}else{this.queueRebuildEvent()}return}};DynamicView.prototype.removeDocument=function(objIndex){var ofr=this.resultset.filteredrows;var oldPos=ofr.indexOf(+objIndex);var oldlen=ofr.length;var idx;if(oldPos!==-1){if(oldPos<oldlen-1){ofr[oldPos]=ofr[oldlen-1];ofr.length=oldlen-1;if(this.options.persistent){this.resultdata[oldPos]=this.resultdata[oldlen-1];this.resultdata.length=oldlen-1}}else{ofr.length=oldlen-1;if(this.options.persistent){this.resultdata.length=oldlen-1}}if(this.sortFunction||this.sortCriteria){this.queueSortPhase()}}oldlen=ofr.length;for(idx=0;idx<oldlen;idx++){if(ofr[idx]>objIndex){ofr[idx]--}}};DynamicView.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data().map(mapFunction))}catch(err){throw err}};function Collection(name,options){this.name=name;this.data=[];this.idIndex=[];this.binaryIndices={};this.constraints={unique:{},exact:{}};this.uniqueNames=[];this.transforms={};this.objType=name;this.dirty=true;this.cachedIndex=null;this.cachedBinaryIndex=null;this.cachedData=null;var self=this;options=options||{};if(options.hasOwnProperty("unique")){if(!Array.isArray(options.unique)){options.unique=[options.unique]}options.unique.forEach(function(prop){self.uniqueNames.push(prop);self.constraints.unique[prop]=new UniqueIndex(prop)})}if(options.hasOwnProperty("exact")){options.exact.forEach(function(prop){self.constraints.exact[prop]=new ExactIndex(prop)})}this.transactional=options.hasOwnProperty("transactional")?options.transactional:false;this.cloneObjects=options.hasOwnProperty("clone")?options.clone:false;this.cloneMethod=options.hasOwnProperty("clonemethod")?options.cloneMethod:"parse-stringify";this.asyncListeners=options.hasOwnProperty("asyncListeners")?options.asyncListeners:false;this.disableChangesApi=options.hasOwnProperty("disableChangesApi")?options.disableChangesApi:true;this.autoupdate=options.hasOwnProperty("autoupdate")?options.autoupdate:false;this.maxId=0;this.DynamicViews=[];this.events={insert:[],update:[],"pre-insert":[],"pre-update":[],close:[],flushbuffer:[],error:[],"delete":[],warning:[]};this.changes=[];this.ensureId();var indices=[];if(options&&options.indices){if(Object.prototype.toString.call(options.indices)==="[object Array]"){indices=options.indices}else if(typeof options.indices==="string"){indices=[options.indices]}else{throw new TypeError("Indices needs to be a string or an array of strings")}}for(var idx=0;idx<indices.length;idx++){this.ensureIndex(indices[idx])}function observerCallback(changes){var changedObjects=typeof Set==="function"?new Set:[];if(!changedObjects.add)changedObjects.add=function(object){if(this.indexOf(object)===-1)this.push(object);return this};changes.forEach(function(change){changedObjects.add(change.object)});changedObjects.forEach(function(object){if(!object.hasOwnProperty("$loki"))return self.removeAutoUpdateObserver(object);try{self.update(object)}catch(err){}})}this.observerCallback=observerCallback;function createChange(name,op,obj){self.changes.push({name:name,operation:op,obj:JSON.parse(JSON.stringify(obj))})}function flushChanges(){self.changes=[]}this.getChanges=function(){return self.changes};this.flushChanges=flushChanges;function insertMeta(obj){if(!obj){return}if(!obj.meta){obj.meta={}}obj.meta.created=(new Date).getTime();obj.meta.revision=0}function updateMeta(obj){if(!obj){return}obj.meta.updated=(new Date).getTime();obj.meta.revision+=1}function createInsertChange(obj){createChange(self.name,"I",obj)}function createUpdateChange(obj){createChange(self.name,"U",obj)}function insertMetaWithChange(obj){insertMeta(obj);createInsertChange(obj)}function updateMetaWithChange(obj){updateMeta(obj);createUpdateChange(obj)}var insertHandler,updateHandler;function setHandlers(){insertHandler=self.disableChangesApi?insertMeta:insertMetaWithChange;updateHandler=self.disableChangesApi?updateMeta:updateMetaWithChange}setHandlers();this.setChangesApi=function(enabled){self.disableChangesApi=!enabled;setHandlers()};this.on("insert",function insertCallback(obj){insertHandler(obj)});this.on("update",function updateCallback(obj){updateHandler(obj)});this.on("delete",function deleteCallback(obj){if(!self.disableChangesApi){createChange(self.name,"R",obj)}});this.on("warning",function(warning){self.console.warn(warning)});flushChanges()}Collection.prototype=new LokiEventEmitter;Collection.prototype.console={log:function(){},warn:function(){},error:function(){}};Collection.prototype.addAutoUpdateObserver=function(object){if(!this.autoupdate||typeof Object.observe!=="function")return;Object.observe(object,this.observerCallback,["add","update","delete","reconfigure","setPrototype"])};Collection.prototype.removeAutoUpdateObserver=function(object){if(!this.autoupdate||typeof Object.observe!=="function")return;Object.unobserve(object,this.observerCallback)};Collection.prototype.addTransform=function(name,transform){if(this.transforms.hasOwnProperty(name)){throw new Error("a transform by that name already exists")}this.transforms[name]=transform};Collection.prototype.setTransform=function(name,transform){this.transforms[name]=transform};Collection.prototype.removeTransform=function(name){delete this.transforms[name]};Collection.prototype.byExample=function(template){var k,obj,query;query=[];for(k in template){if(!template.hasOwnProperty(k))continue;query.push((obj={},obj[k]=template[k],obj))}return{$and:query}};Collection.prototype.findObject=function(template){return this.findOne(this.byExample(template))};Collection.prototype.findObjects=function(template){return this.find(this.byExample(template))};Collection.prototype.ensureIndex=function(property,force){if(typeof force==="undefined"){force=false}if(property===null||property===undefined){throw new Error("Attempting to set index without an associated property")}if(this.binaryIndices.hasOwnProperty(property)&&!force){if(!this.binaryIndices[property].dirty)return}this.binaryIndices[property]={name:property,dirty:true,values:[]};var index,len=this.data.length,i=0;index=this.binaryIndices[property];for(i;i<len;i+=1){index.values.push(i)}var wrappedComparer=function(prop,coll){return function(a,b){var obj1=coll.data[a];var obj2=coll.data[b];if(obj1[prop]===obj2[prop])return 0;if(gtHelper(obj1[prop],obj2[prop]))return 1;if(ltHelper(obj1[prop],obj2[prop]))return-1}}(property,this);index.values.sort(wrappedComparer);index.dirty=false;this.dirty=true};Collection.prototype.ensureUniqueIndex=function(field){var index=this.constraints.unique[field];if(!index){if(this.uniqueNames.indexOf(field)==-1){this.uniqueNames.push(field)}this.constraints.unique[field]=index=new UniqueIndex(field)}var self=this;this.data.forEach(function(obj){index.set(obj)});return index};Collection.prototype.ensureAllIndexes=function(force){var objKeys=Object.keys(this.binaryIndices);var i=objKeys.length;while(i--){this.ensureIndex(objKeys[i],force)}};Collection.prototype.flagBinaryIndexesDirty=function(){var objKeys=Object.keys(this.binaryIndices);var i=objKeys.length;while(i--){this.binaryIndices[objKeys[i]].dirty=true}};Collection.prototype.flagBinaryIndexDirty=function(index){if(this.binaryIndices[index])this.binaryIndices[index].dirty=true};Collection.prototype.count=function(query){if(!query){return this.data.length}return this.chain().find(query).filteredrows.length};Collection.prototype.ensureId=function(){var len=this.data.length,i=0;this.idIndex=[];for(i;i<len;i+=1){this.idIndex.push(this.data[i].$loki)}};Collection.prototype.ensureIdAsync=function(callback){this.async(function(){this.ensureId()},callback)};Collection.prototype.addDynamicView=function(name,options){var dv=new DynamicView(this,name,options);this.DynamicViews.push(dv);return dv};Collection.prototype.removeDynamicView=function(name){for(var idx=0;idx<this.DynamicViews.length;idx++){if(this.DynamicViews[idx].name===name){this.DynamicViews.splice(idx,1)}}};Collection.prototype.getDynamicView=function(name){for(var idx=0;idx<this.DynamicViews.length;idx++){if(this.DynamicViews[idx].name===name){return this.DynamicViews[idx]}}return null};Collection.prototype.findAndUpdate=function(filterFunction,updateFunction){var results=this.where(filterFunction),i=0,obj;try{for(i;i<results.length;i++){obj=updateFunction(results[i]);this.update(obj)}}catch(err){this.rollback();this.console.error(err.message)}};Collection.prototype.insert=function(doc){if(!doc){var error=new Error("Object cannot be null");this.emit("error",error);throw error}var self=this;var obj;var docs=Array.isArray(doc)?doc:[doc];var results=[];docs.forEach(function(d){if(typeof d!=="object"){throw new TypeError("Document needs to be an object")}obj=self.cloneObjects?clone(d,self.cloneMethod):d;if(typeof obj.meta==="undefined"){obj.meta={revision:0,created:0}}self.emit("pre-insert",obj);if(self.add(obj)){self.addAutoUpdateObserver(obj);self.emit("insert",obj);results.push(obj)}else{return undefined}});return results.length===1?results[0]:results};Collection.prototype.clear=function(){this.data=[];this.idIndex=[];this.binaryIndices={};this.cachedIndex=null;this.cachedData=null;this.maxId=0;this.DynamicViews=[];this.dirty=true};Collection.prototype.update=function(doc){if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}if(Array.isArray(doc)){var k=0,len=doc.length;for(k;k<len;k+=1){this.update(doc[k])}return}if(!doc.hasOwnProperty("$loki")){throw new Error("Trying to update unsynced document. Please save the document first by using insert() or addMany()")}try{this.startTransaction();var arr=this.get(doc.$loki,true),obj,position,self=this;if(!arr){throw new Error("Trying to update a document not in collection.")}this.emit("pre-update",doc);obj=arr[0];Object.keys(this.constraints.unique).forEach(function(key){self.constraints.unique[key].update(obj)});position=arr[1];this.data[position]=doc;if(obj!==doc){this.addAutoUpdateObserver(doc)}for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].evaluateDocument(position)}this.idIndex[position]=obj.$loki;this.commit();this.dirty=true;this.emit("update",doc);return doc}catch(err){this.rollback();this.console.error(err.message);this.emit("error",err);throw err}};Collection.prototype.add=function(obj){var dvlen=this.DynamicViews.length;if("object"!==typeof obj){throw new TypeError("Object being added needs to be an object")}if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}if(typeof obj.$loki!=="undefined"){throw new Error("Document is already in collection, please use update()")}try{this.startTransaction();this.maxId++;if(isNaN(this.maxId)){this.maxId=this.data[this.data.length-1].$loki+1}obj.$loki=this.maxId;obj.meta.version=0;var self=this;Object.keys(this.constraints.unique).forEach(function(key){self.constraints.unique[key].set(obj)});this.data.push(obj);for(var i=0;i<dvlen;i++){this.DynamicViews[i].evaluateDocument(this.data.length-1)}this.idIndex.push(obj.$loki);this.commit();this.dirty=true;if(this.cloneObjects){return obj}else{return clone(obj,this.cloneMethod)}}catch(err){this.rollback();this.console.error(err.message)}};Collection.prototype.removeWhere=function(query){var list;if(typeof query==="function"){list=this.data.filter(query)}else{list=new Resultset(this,query)}this.remove(list)};Collection.prototype.removeDataOnly=function(){this.remove(this.data.slice())};Collection.prototype.remove=function(doc){if(typeof doc==="number"){doc=this.get(doc)}if("object"!==typeof doc){throw new Error("Parameter is not an object")}if(Array.isArray(doc)){var k=0,len=doc.length;for(k;k<len;k+=1){this.remove(doc[k])}return}if(!doc.hasOwnProperty("$loki")){throw new Error("Object is not a document stored in the collection")}if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}try{this.startTransaction();var arr=this.get(doc.$loki,true),position=arr[1];var self=this;Object.keys(this.constraints.unique).forEach(function(key){if(doc[key]!==null&&typeof doc[key]!=="undefined"){self.constraints.unique[key].remove(doc[key])}});for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].removeDocument(position)}this.data.splice(position,1);this.removeAutoUpdateObserver(doc);this.idIndex.splice(position,1);this.commit();this.dirty=true;this.emit("delete",arr[0]);delete doc.$loki;delete doc.meta;return doc}catch(err){this.rollback();this.console.error(err.message);this.emit("error",err);return null}};Collection.prototype.get=function(id,returnPosition){var retpos=returnPosition||false,data=this.idIndex,max=data.length-1,min=0,mid=Math.floor(min+(max-min)/2);id=typeof id==="number"?id:parseInt(id,10);if(isNaN(id)){throw new TypeError("Passed id is not an integer")}while(data[min]<data[max]){mid=Math.floor((min+max)/2);if(data[mid]<id){min=mid+1}else{max=mid}}if(max===min&&data[min]===id){if(retpos){return[this.data[min],min]}return this.data[min]}return null};Collection.prototype.by=function(field,value){var self;if(!value){self=this;return function(value){return self.by(field,value)}}if(!this.cloneObjects){return this.constraints.unique[field].get(value)}else{return clone(this.constraints.unique[field].get(value),this.cloneMethod)}};Collection.prototype.findOne=function(query){var result=new Resultset(this,query,null,true);if(Array.isArray(result)&&result.length===0){return null}else{if(!this.cloneObjects){return result}else{return clone(result,this.cloneMethod)}}};Collection.prototype.chain=function(transform,parameters){var rs=new Resultset(this,null,null);if(typeof transform==="undefined"){return rs}return rs.transform(transform,parameters)};Collection.prototype.find=function(query){if(typeof query==="undefined"){query="getAll"}if(!this.cloneObjects){return new Resultset(this,query,null)}else{var results=new Resultset(this,query,null);return cloneObjectArray(results,this.cloneMethod)}};Collection.prototype.findOneUnindexed=function(prop,value){var i=this.data.length,doc;while(i--){if(this.data[i][prop]===value){doc=this.data[i];return doc}}return null};Collection.prototype.startTransaction=function(){if(this.transactional){this.cachedData=clone(this.data,this.cloneMethod);this.cachedIndex=this.idIndex;this.cachedBinaryIndex=this.binaryIndices;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].startTransaction()}}};Collection.prototype.commit=function(){if(this.transactional){this.cachedData=null;this.cachedIndex=null;this.cachedBinaryIndices=null;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].commit()}}};Collection.prototype.rollback=function(){if(this.transactional){if(this.cachedData!==null&&this.cachedIndex!==null){this.data=this.cachedData;this.idIndex=this.cachedIndex;this.binaryIndices=this.cachedBinaryIndex}for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].rollback()}}};Collection.prototype.async=function(fun,callback){setTimeout(function(){if(typeof fun==="function"){fun();callback()}else{throw new TypeError("Argument passed for async execution is not a function")}},0)};Collection.prototype.where=function(fun){if(!this.cloneObjects){return new Resultset(this,null,fun)}else{var results=new Resultset(this,null,fun);return cloneObjectArray(results,this.cloneMethod)}};Collection.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data.map(mapFunction))}catch(err){throw err}};Collection.prototype.eqJoin=function(joinData,leftJoinProp,rightJoinProp,mapFun){return new Resultset(this).eqJoin(joinData,leftJoinProp,rightJoinProp,mapFun)};Collection.prototype.stages={};Collection.prototype.getStage=function(name){if(!this.stages[name]){this.stages[name]={}}return this.stages[name]};Collection.prototype.commitLog=[];Collection.prototype.stage=function(stageName,obj){var copy=JSON.parse(JSON.stringify(obj));this.getStage(stageName)[obj.$loki]=copy;return copy};Collection.prototype.commitStage=function(stageName,message){var stage=this.getStage(stageName),prop,timestamp=(new Date).getTime();for(prop in stage){this.update(stage[prop]);this.commitLog.push({timestamp:timestamp,message:message,data:JSON.parse(JSON.stringify(stage[prop]))})}this.stages[stageName]={}};Collection.prototype.no_op=function(){return};Collection.prototype.extract=function(field){var i=0,len=this.data.length,isDotNotation=isDeepProperty(field),result=[];for(i;i<len;i+=1){result.push(deepProperty(this.data[i],field,isDotNotation))}return result};Collection.prototype.max=function(field){return Math.max.apply(null,this.extract(field))};Collection.prototype.min=function(field){return Math.min.apply(null,this.extract(field))};Collection.prototype.maxRecord=function(field){var i=0,len=this.data.length,deep=isDeepProperty(field),result={index:0,value:undefined},max;for(i;i<len;i+=1){if(max!==undefined){if(max<deepProperty(this.data[i],field,deep)){max=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}else{max=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}result.value=max;return result};Collection.prototype.minRecord=function(field){var i=0,len=this.data.length,deep=isDeepProperty(field),result={index:0,value:undefined},min;for(i;i<len;i+=1){if(min!==undefined){if(min>deepProperty(this.data[i],field,deep)){min=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}else{min=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}result.value=min;return result};Collection.prototype.extractNumerical=function(field){return this.extract(field).map(parseBase10).filter(Number).filter(function(n){return!isNaN(n)})};Collection.prototype.avg=function(field){return average(this.extractNumerical(field))};Collection.prototype.stdDev=function(field){return standardDeviation(this.extractNumerical(field))};Collection.prototype.mode=function(field){var dict={},data=this.extract(field);data.forEach(function(obj){if(dict[obj]){dict[obj]+=1}else{dict[obj]=1}});var max,prop,mode;for(prop in dict){if(max){if(max<dict[prop]){mode=prop}}else{mode=prop;max=dict[prop]}}return mode};Collection.prototype.median=function(field){var values=this.extractNumerical(field);values.sort(sub);var half=Math.floor(values.length/2);if(values.length%2){return values[half]}else{return(values[half-1]+values[half])/2}};function isDeepProperty(field){return field.indexOf(".")!==-1}function parseBase10(num){return parseFloat(num,10)}function isNotUndefined(obj){return obj!==undefined}function add(a,b){return a+b}function sub(a,b){return a-b}function median(values){values.sort(sub);var half=Math.floor(values.length/2);return values.length%2?values[half]:(values[half-1]+values[half])/2}function average(array){return array.reduce(add,0)/array.length}function standardDeviation(values){var avg=average(values);var squareDiffs=values.map(function(value){var diff=value-avg;var sqrDiff=diff*diff;return sqrDiff});var avgSquareDiff=average(squareDiffs);var stdDev=Math.sqrt(avgSquareDiff);return stdDev}function deepProperty(obj,property,isDeep){if(isDeep===false){return obj[property]}var pieces=property.split("."),root=obj;while(pieces.length>0){root=root[pieces.shift()]}return root}function binarySearch(array,item,fun){var lo=0,hi=array.length,compared,mid;while(lo<hi){mid=(lo+hi)/2|0;compared=fun.apply(null,[item,array[mid]]);if(compared===0){return{found:true,index:mid}}else if(compared<0){hi=mid}else{lo=mid+1}}return{found:false,index:hi}}function BSonSort(fun){return function(array,item){return binarySearch(array,item,fun)}}function KeyValueStore(){}KeyValueStore.prototype={keys:[],values:[],sort:function(a,b){return a<b?-1:a>b?1:0},setSort:function(fun){this.bs=new BSonSort(fun)},bs:function(){return new BSonSort(this.sort)},set:function(key,value){var pos=this.bs(this.keys,key);if(pos.found){this.values[pos.index]=value}else{this.keys.splice(pos.index,0,key);this.values.splice(pos.index,0,value)}},get:function(key){return this.values[binarySearch(this.keys,key,this.sort).index]}};function UniqueIndex(uniqueField){this.field=uniqueField;this.keyMap={};this.lokiMap={}}UniqueIndex.prototype.keyMap={};UniqueIndex.prototype.lokiMap={};UniqueIndex.prototype.set=function(obj){if(obj[this.field]!==null&&typeof obj[this.field]!=="undefined"){if(this.keyMap[obj[this.field]]){throw new Error("Duplicate key for property "+this.field+": "+obj[this.field])}else{this.keyMap[obj[this.field]]=obj;this.lokiMap[obj.$loki]=obj[this.field]}}};UniqueIndex.prototype.get=function(key){return this.keyMap[key]};UniqueIndex.prototype.byId=function(id){return this.keyMap[this.lokiMap[id]]};UniqueIndex.prototype.update=function(obj){if(this.lokiMap[obj.$loki]!==obj[this.field]){var old=this.lokiMap[obj.$loki];this.set(obj);this.keyMap[old]=undefined}else{this.keyMap[obj[this.field]]=obj}};UniqueIndex.prototype.remove=function(key){var obj=this.keyMap[key];if(obj!==null&&typeof obj!=="undefined"){this.keyMap[key]=undefined;this.lokiMap[obj.$loki]=undefined}else{throw new Error("Key is not in unique index: "+this.field)}};UniqueIndex.prototype.clear=function(){this.keyMap={};this.lokiMap={}};function ExactIndex(exactField){this.index={};this.field=exactField}ExactIndex.prototype={set:function add(key,val){if(this.index[key]){this.index[key].push(val)}else{this.index[key]=[val]}},remove:function remove(key,val){var idxSet=this.index[key];for(var i in idxSet){if(idxSet[i]==val){idxSet.splice(i,1)}}if(idxSet.length<1){this.index[key]=undefined}},get:function get(key){return this.index[key]},clear:function clear(key){this.index={}}};function SortedIndex(sortedField){this.field=sortedField}SortedIndex.prototype={keys:[],values:[],sort:function(a,b){return a<b?-1:a>b?1:0},bs:function(){return new BSonSort(this.sort)},setSort:function(fun){this.bs=new BSonSort(fun)},set:function(key,value){var pos=binarySearch(this.keys,key,this.sort);if(pos.found){this.values[pos.index].push(value)}else{this.keys.splice(pos.index,0,key);this.values.splice(pos.index,0,[value])}},get:function(key){var bsr=binarySearch(this.keys,key,this.sort);if(bsr.found){return this.values[bsr.index]}else{return[]}},getLt:function(key){var bsr=binarySearch(this.keys,key,this.sort);var pos=bsr.index;if(bsr.found)pos--;return this.getAll(key,0,pos)},getGt:function(key){var bsr=binarySearch(this.keys,key,this.sort);var pos=bsr.index;if(bsr.found)pos++;return this.getAll(key,pos,this.keys.length)},getAll:function(key,start,end){var results=[];for(var i=start;i<end;i++){results=results.concat(this.values[i])}return results},getPos:function(key){return binarySearch(this.keys,key,this.sort)},remove:function(key,value){var pos=binarySearch(this.keys,key,this.sort).index;var idxSet=this.values[pos];for(var i in idxSet){if(idxSet[i]==value)idxSet.splice(i,1)}if(idxSet.length<1){this.keys.splice(pos,1);this.values.splice(pos,1)}},clear:function(){this.keys=[];this.values=[]}};Loki.Collection=Collection;Loki.KeyValueStore=KeyValueStore;return Loki}()});
{
"name": "lokijs",
"version": "1.3.10",
"version": "1.3.11",
"description": "Fast document oriented javascript in-memory database",

@@ -5,0 +5,0 @@ "homepage": "http://lokijs.org",

@@ -46,4 +46,6 @@ # LokiJS

Made by [@techfort](http://twitter.com/tech_fort), with the precious help of Dave Easterday. [Leave a tip](https://gratipay.com/techfort/) or give us a star if you find LokiJS useful!
Made by [@techfort](http://twitter.com/tech_fort), with the precious help of Dave Easterday.
_[Leave a tip](https://gratipay.com/techfort/) or give us a star if you find LokiJS useful!_
## Installation

@@ -50,0 +52,0 @@

@@ -44,2 +44,29 @@ if (typeof (window) === 'undefined') {

it('works', function () {
var tdb = new loki('regextests');
var tcu = tdb.addCollection('user');
tcu.insert({
name: 'abcd',
age: 25,
lang: 'English'
});
tcu.insert({
name: 'AbCd',
age: 39,
lang: 'Italian'
});
tcu.insert({
name: 'acdb',
age: 30,
lang: 'Swedish'
});
tcu.insert({
name: 'aBcD',
age: 30,
lang: 'Swedish'
});
// findOne()

@@ -59,3 +86,3 @@ var j = users.findOne({

// $regex test
// $regex test with raw regex
expect(users.find({

@@ -67,2 +94,16 @@ 'name': {

// case insensitive regex with array of ["pattern", "options"]
expect(tcu.find({
'name': {
'$regex': ["abcd", "i"]
}
}).length).toEqual(3);
// regex with single encoded string pattern (no options)
expect(tcu.find({
'name': {
'$regex': "cd"
}
}).length).toEqual(2);
// $contains

@@ -195,3 +236,18 @@ expect(users.find({

// make sure it can handle case where top level property doesn't exist
dnc.insert({
first: 'mmm',
last: 'nnn'
});
// make sure it can handle case where subscan property doesn't exist
dnc.insert({
first: 'ooo',
last: 'ppp',
addr: {
state: 'YY'
}
});
dnc.insert({
first: 'jjj',

@@ -700,4 +756,51 @@ last: 'kkk',

})
})
});
describe('chained removes', function() {
it('works', function() {
var rsc = db.addCollection('rsc');
rsc.insert({
'testid': 1,
'testString': 'hhh',
'testFloat': 5.2
});
rsc.insert({
'testid': 1,
'testString': 'bbb',
'testFloat': 6.2
});
rsc.insert({
'testid': 2,
'testString': 'ccc',
'testFloat': 6.2
});
rsc.insert({
'testid': 5,
'testString': 'zzz',
'testFloat': 7.2
});
var docCount = rsc.find().length;
// verify initial doc count
expect(docCount).toEqual(4);
// remove middle documents
rsc.chain().find({testFloat: 6.2}).remove();
// verify new doc count
expect(rsc.find().length).toEqual(2);
expect(rsc.chain().data().length).toEqual(2);
// now fetch and retain all remaining documents
var results = rsc.chain().simplesort('testString').data();
// make sure its the documents we expect
expect(results[0].testString).toEqual('hhh');
expect(results[1].testString).toEqual('zzz');
})
});
/* Dynamic View Tests */

@@ -704,0 +807,0 @@ describe('stepEvaluateDocument', function () {

@@ -26,17 +26,9 @@ /**

function JquerySyncAdapterError() {}
JquerySyncAdapterError.prototype = new Error();
if (!options) {
throw new JquerySyncAdapterError('No options configured in JquerySyncAdapter');
function JquerySyncAdapterError(message) {
this.name = "JquerySyncAdapterError";
this.message = (message || "");
}
if (!options.ajaxLib) {
throw new JquerySyncAdapterError('No ajax library specified in JquerySyncAdapter');
}
JquerySyncAdapterError.prototype = Error.prototype;
if (!options.saveUrl || !options.loadUrl) {
throw new JquerySyncAdapterError('Please specify load and save url in JquerySyncAdapter');
}
/**

@@ -52,2 +44,17 @@ * this adapter assumes an object options is passed,

this.options = options;
if (!options) {
throw new JquerySyncAdapterError('No options configured in JquerySyncAdapter');
}
if (!options.ajaxLib) {
throw new JquerySyncAdapterError('No ajaxLib property specified in options');
}
if (!options.save || !options.load) {
throw new JquerySyncAdapterError('Please specify load and save properties in options');
}
if (!options.save.url || !options.load.url) {
throw new JquerySyncAdapterError('load and save objects must have url property');
}
}

@@ -86,3 +93,3 @@

});
}());
}));

@@ -8,23 +8,615 @@ /*

(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['angular', 'lokijs'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory();
} else {
// Browser globals
root.lokiAngular = factory(
root.angular,
// Use thirdParty.loki if available to cover all legacy cases
root.thirdParty && root.thirdParty.loki ?
root.thirdParty.loki : root.loki
);
}
} (this, function (angular, lokijs) {
var module = angular.module('lokijs', [])
.factory('Loki', function Loki() {
return loki;
});
return module;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['angular', 'lokijs'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory();
} else {
// Browser globals
root.lokiAngular = factory(
root.angular,
// Use thirdParty.loki if available to cover all legacy cases
root.thirdParty && root.thirdParty.loki ?
root.thirdParty.loki : root.loki
);
}
}(this, function (angular, lokijs) {
var module = angular.module('lokijs', [])
.factory('Loki', Loki)
.service('Lokiwork', Lokiwork);
function Loki() {
return loki;
}
Lokiwork.$inject = ['Loki', '$q', '$injector', '$window'];
function Lokiwork(Loki, $q, $injector, $window) {
var vm = this;
vm.checkStates = checkStates;
var statesChecked = false;
var db;
var userDbPreference = '';
var userPrefJsonFile = 0;
var numOfJsonDatabases = 0;
var dbitems = [];
var lokidbs = [];
vm.dbExists = dbExists;
vm.closeDb = closeDb;
vm.closeAllDbs = closeAllDbs;
vm.getCollection = getCollection;
vm.addCollection = addCollection;
vm.removeCollection = removeCollection;
vm.getDoc = getDoc;
vm.updateDoc = updateDoc;
vm.updateCurrentDoc = updateCurrentDoc;
vm.setCurrentDoc = setCurrentDoc;
vm.getCurrentDoc = getCurrentDoc;
vm.deleteDocument = deleteDocument;
vm.deleteCurrentDoc = deleteCurrentDoc;
vm.deleteDatabase = deleteDatbase;
vm.addDocument = addDocument;
vm.insertItemInDoc = insertItemInDoc;
var currentDoc = {};
var currentColl = {};
numOfJsonDatabases = getNumberOfJsonDatabases();
function getCurrentDoc() {
return currentDoc;
}
function deleteDatbase(data) {
localStorage.removeItem(data);
}
function deleteDocument(dbName, collName, doc) { //doc should be in {name:value} format
return $q(function (resolve, reject) {
userDbPreference = dbName;
_getem('delete_doc', dbName, collName, doc)
.then(function (data) {
currentDoc = {};
resolve(data);
}, function(data){
reject(data);
});
});
}
function insertItemInDoc(item) {
return $q(function (resolve, reject) {
_getem('insert_item_in_doc', currentDoc.dbName, currentDoc.collName, currentDoc.doc, "", item)
.then(function (data) {
resolve(data);
}, function (data) {
reject(data);
});
});
}
function deleteCurrentDoc() {
return $q(function (resolve, reject) {
_getem('delete_current_doc')
.then(function (data) {
resolve(data);
}, function (data) {
reject(data);
});
});
}
function addDocument(dbName, collName, newDoc) {
return $q(function (resolve, reject) {
userDbPreference = dbName;
_getem('create_doc', dbName, collName, "", "", newDoc)
.then(function (data) {
currentDoc.dbName = dbName;
currentDoc.collName = collName;
currentDoc.doc = data;
currentDoc.lokiNum = data[0].$loki;
resolve(data[0]);
}, function(data){
reject(data);
});
});
}
function setCurrentDoc(dbName, collName, docName) {
return $q(function (resolve, reject) {
userDbPreference = dbName;
_getem('set_doc', dbName, collName, docName)
.then(function (data) {
currentDoc.dbName = dbName;
currentDoc.collName = collName;
currentDoc.doc = data;
currentDoc.lokiNum = data[0].$loki;
resolve(data[0]);
}, function(data){
reject(data);
});
});
}
function updateCurrentDoc(thekey, thevalue) {
return $q(function (resolve, reject) {
if (currentDoc) {
_getem('update_current_doc', currentDoc.dbName, currentDoc.collName, currentDoc.doc, thekey, thevalue)
.then(function (data) {
resolve(data[0]);
}, function(data){
reject(data);
});
} else {
reject("you have to set a current doc first, use: setCurrentDoc(dbName, collName, docName)");
}
});
}
function updateDoc(dbName, collName, docName, thekey, thevalue) {
return $q(function (resolve, reject) {
userDbPreference = dbName;
if (currentDoc) {
_getem('update_doc', dbName, collName, docName, thekey, thevalue)
.then(function (data) {
resolve(data[0]);
}, function(data){
reject(data);
});
} else {
reject("bad, check parameters)");
}
});
}
function getDoc(dbName, collName, docName) {
return $q(function (resolve, reject) {
userDbPreference = dbName;
_getem('get_doc', dbName, collName, docName)
.then(function (data) {
currentDoc.dbName = dbName;
currentDoc.collName = collName;
currentDoc.doc = data;
currentDoc.lokiNum = data[0].$loki;
resolve(data[0]);
}, function(data){
reject(data);
});
});
}
function getCollection(dbName, collName) {
return $q(function (resolve, reject) {
userDbPreference = dbName;
_getem('get_collection', dbName, collName)
.then(function (data) {
currentColl.dbName = dbName;
currentColl.collName = collName;
resolve(data);
}, function(data){
reject(data);
});
});
}
function removeCollection(dbName, collName) {
return $q(function (resolve, reject) {
userDbPreference = dbName;
_getem('remove_collection', dbName, collName)
.then(function (data) {
currentColl = {};
resolve(data);
}, function(data){
reject(data);
});
});
}
function addCollection(collData) {
return $q(function (resolve, reject) {
var dbobj = breakdown_components(collData);
userDbPreference = collData[dbobj.db];
_getem('add_collection', userDbPreference, '', '', '', collData)
.then(function (data) {
currentColl.dbName = userDbPreference;
resolve(data);
}, function(data){
reject(data);
});
});
}
function _getem(operation, dbName, collName, docName, thekey, thevalue) {
return $q(function (resolve, reject) {
if (db) {
if (db.filename === dbName) {
getdata();
} else {
loadDb(dbName)
.then(function () {
getdata();
});
}
} else {
if (statesChecked) {
loadDb(dbName)
.then(function () {
getdata();
});
} else {
checkStates().then(function () {
getdata();
}, function(data){
reject(data);
});
}
}
function getdata() {
var found;
if (operation === 'update_doc' || operation === 'insert_item_in_doc') {
db.loadDatabase(dbName);
var coll = db.getCollection(collName);
//docName is not simply a docname, this is an object like: {name: 'user settings'}
for(var i in docName) {
currentDoc.key = i;
currentDoc.value = docName[i];
}
for (var x = 0; x < coll.data.length; x++){
if (coll.data[x][currentDoc.key] === currentDoc.value){
currentDoc.lokiNum = coll.data[x].$loki;
}
}
found = coll.get(parseInt(currentDoc.lokiNum, 10));
if (operation === 'update_doc') {
found[thekey] = thevalue;
coll.update(found);
} else {
found.insert(thevalue);
}
db.save();
resolve(true);
}
else if(operation === 'update_current_doc'){
db.loadDatabase(dbName);
var coll0 = db.getCollection(collName);
found = coll0.get(parseInt(currentDoc.lokiNum, 10));
found[thekey] = thevalue;
coll0.update(found);
db.save();
resolve(true);
}
else if (operation === 'delete_current_doc' || operation === 'delete_doc') {
db.loadDatabase(dbName);
var coll6 = db.getCollection(collName);
if(operation === 'delete_doc'){
for(var j in docName) {
currentDoc.key = j;
currentDoc.value = docName[j];
}
for (var y = 0; y < coll6.data.length; y++){
if (coll6.data[y][currentDoc.key] === currentDoc.value){
currentDoc.lokiNum = coll6.data[y].$loki;
}
}
}
coll6.remove(currentDoc.lokiNum);
db.save();
resolve(true);
}
else if (operation === 'get_doc' || operation === 'set_doc') {
db.loadDatabase(dbName);
var coll1 = db.getCollection(collName);
found = coll1.find(docName);
resolve(angular.fromJson(found));
} else if (operation === 'get_collection') {
db.loadDatabase(dbName);
var coll2 = db.getCollection(collName);
resolve(angular.fromJson(coll2));
} else if (operation === 'remove_collection') {
db.loadDatabase(dbName);
db.removeCollection(collName);
//coll = db.getCollection(collName);
db.save(function () {
resolve('collection deleted');
});
} else if (operation === 'add_collection') {
db.loadDatabase(dbName);
var dbobj = breakdown_components(thevalue);
for (var w=0; w< dbobj.coll_array.length; w++){
var items = db.addCollection(thevalue[dbobj.coll_array[w].coll]);
items.insert(thevalue[dbobj.coll_array[w].docs]);
}
db.save(function () {
resolve('collection(s) added');
});
} else if (operation === 'create_doc') {
db.loadDatabase(dbName);
var coll3 = db.getCollection(collName);
coll3.insert(thevalue);
db.save(function () {
var found = coll3.find({
name: thevalue.name
});
resolve(angular.fromJson(found));
});
}
// _getem('delete_doc', dbName, collName, "", "", doc)
else if (operation === 'delete_current_doc') {
var coll5 = db.getCollection(currentDoc.collName);
if (!coll5) {
reject('You forgot to specify a current doc first');
} else {
coll5.remove(parseInt(currentDoc.lokiNum, 10));
db.save();
resolve(true);
}
}
}
});
}
function dbExists(databaseName) {
var value = window.localStorage.getItem(databaseName);
if (value) {
return true;
} else {
return false;
}
}
function closeAllDbs() {
return $q(function (resolve, reject) {
var current = 0;
for (var x = 0; x < lokidbs.length; x++) {
current++;
lokidbs[x].close();
if (x === (lokidbs.length - 1)) {
resolve();
}
}
});
}
function closeDb(databaseName) {
return $q(function (resolve, reject) {
for (var x = 0; x < lokidbs.length; x++) {
if (lokidbs.filename === databaseName) {
lokidbs[x].close();
resolve();
break;
}
}
});
}
function checkStates() {
return $q(function (resolve, reject) {
if (dbitems.length === 0) {
initialiseAll().then(function () {
console.log('had to initialize all dbs');
statesChecked = true;
resolve();
}, function (data) {
reject(data);
});
} else {
console.log('db list already initialized');
resolve();
}
});
}
function firstFewItemsOfDbList() {
return $q(function (resolve, reject) {
for (var x = 0; x >= 0; x++) {
if ($injector.has('json' + (x + 1))) {
var item = {};
var setting = $injector.get('json' + (x + 1));
var dbobj = breakdown_components(setting);
if (setting[dbobj.db] === userDbPreference) { //userDbPreference is the name
userPrefJsonFile = x + 1; //userPrefJsonFile is the index
if (x === (numOfJsonDatabases - 1)) {
resolve();
}
} else {
item.filename = dbobj.db;
item.json = x + 1;
dbitems.push(item);
if (x === (numOfJsonDatabases - 1)) {
resolve();
}
}
}
else {
resolve();
break;
}
}
});
}
function initialiseDbList() {
return $q(function (resolve, reject) {
firstFewItemsOfDbList()
.then(function () {
if (userPrefJsonFile === 0){
reject('Oops!, you didn\'t specify any starting document');
}
var currentdb = $injector.get('json' + userPrefJsonFile);
var item = {};
var dbobj = breakdown_components(currentdb);
item.filename = dbobj.db;
item.json = userPrefJsonFile;
dbitems.push(item);
resolve();
});
});
}
function getNumberOfJsonDatabases() {
if (numOfJsonDatabases >= 1) {
return numOfJsonDatabases;
} else {
for (var x = 0; x >= 0; x++) {
if ($injector.has('json' + (x + 1))) {
numOfJsonDatabases++;
}
else {
break;
}
}
return numOfJsonDatabases;
}
}
var still_running = false;
var current_iteration = 1;
function initialiseAll() {
return $q(function (resolve, reject) {
initialiseDbList()
.then(function () {
function iterate_me() {
if ($injector.has('json' + dbitems[current_iteration - 1].json)) {
var setting = $injector.get('json' + dbitems[current_iteration - 1].json);
console.log('number = ' + current_iteration);
var set = angular.fromJson(setting);
still_running = true;
initiateDb(set)
.then(function () {
//lokidbs.push(angular.copy(db));
if (!doesDBAlreadyExistInArray(db.filename)) {
lokidbs.push(angular.copy(db));
}
still_running = false;
if (current_iteration === (dbitems.length)) {
resolve();
} else {
current_iteration++;
iterate_me();
return;
}
});
}
}
iterate_me();
}, function(data){
reject(data);
});
});
}
function doesDBAlreadyExistInArray(dbname) {
var answer = false;
for (var x = 0; x < lokidbs.length; x++) {
if (lokidbs[x].filename === dbname) {
answer = true;
}
}
return answer;
}
function getIndexOfDbItem(dbname) {
var answer = -1;
for (var x = 0; x < numOfJsonDatabases; x++) {
if (dbitems[x].filename === dbname) {
answer = x;
}
}
return answer;
}
function loadDb(databaseName) {
return $q(function (resolve, reject) {
for (var x = 0; x < lokidbs.length; x++) {
if (lokidbs[x].filename === databaseName) {
db = lokidbs[x];
resolve();
}
}
});
}
function initiateDb(database) {
return $q(function (resolve, reject) {
var dbobj = breakdown_components(database);
var db_does_exist = false;
if (dbExists(database[dbobj.db])) {
db_does_exist = true;
}
db = new loki(database[dbobj.db], {
autoload: true,
autoloadCallback: loadHandler, //loadHandler, //for some reason this has to be called like this
autosave: true,
autosaveInterval: 10000
});
function loadHandler() {
if (db_does_exist) {
resolve();
} else {
var dbobj = breakdown_components(database);
for(var x = 0; x < dbobj.coll_array.length; x++){
var items = db.addCollection(database[dbobj.coll_array[x].coll]);
items.insert(database[dbobj.coll_array[x].docs]);
}
db.save();
resolve();
}
}
});
}
function breakdown_components(db_obj){
var iterate = 1;
var db_id = '';
var coll_id = "";
var doc_id = "";
var collections = [];
for(var i in db_obj){
if (iterate > 1){
if(isEven(iterate)){
coll_id = i;
}
else{
doc_id = i;
var tempobj = {coll: coll_id, docs: doc_id};
collections.push(tempobj);
}
}
else {
db_id = i;
}
iterate ++;
}
var dataobj = {db: db_id, coll_array: collections};
return dataobj;
}
function isEven(n) {
return n % 2 === 0;
}
function isOdd(n) {
return Boolean(n % 2);
}
}
return module;
}));
/*
Loki IndexedDb Adapter (need to include this script to use it)
Indexeddb is highly async, but this adapter has been made 'console-friendly' as well.

@@ -9,3 +9,3 @@ Anywhere a callback is omitted, it should return results (if applicable) to console.

for separate apps within a domain.
Examples :

@@ -34,6 +34,6 @@

});
// DELETE DATABASE
idbAdapter.deleteDatabase('test'); // delete 'finance'/'test' value from catalog
// CONSOLE USAGE : if using from console for management/diagnostic, here are a few examples :

@@ -70,4 +70,4 @@ adapter.getDatabaseList(); // with no callback passed, this method will log results to console

this.app = 'loki';
if (typeof (appname) !== 'undefined')
if (typeof (appname) !== 'undefined')
{

@@ -79,5 +79,5 @@ this.app = appname;

this.catalog = null;
if (!this.checkAvailability()) {
console.error('indexedDB does not seem to be supported for your environment');
throw new Error('indexedDB does not seem to be supported for your environment');
}

@@ -108,3 +108,3 @@ }

var adapter = this;
// lazy open/create db reference so dont -need- callback in constructor

@@ -114,9 +114,9 @@ if (this.catalog === null || this.catalog.db === null) {

adapter.catalog = cat;
adapter.loadDatabase(dbname, callback);
});
return;
}
// lookup up db string in AKV db

@@ -126,3 +126,2 @@ this.catalog.getAppKey(appName, dbname, function(result) {

if (result.id === 0) {
console.warn("loki indexeddb adapter could not find database");
callback(null);

@@ -154,3 +153,12 @@ return;

var adapter = this;
function saveCallback(result) {
if (result && result.success === true) {
callback(null);
}
else {
callback(new Error("Error saving database"));
}
}
// lazy open/create db reference so dont -need- callback in constructor

@@ -160,12 +168,12 @@ if (this.catalog === null || this.catalog.db === null) {

adapter.catalog = cat;
// now that catalog has been initialized, set (add/update) the AKV entry
cat.setAppKey(appName, dbname, dbstring, callback);
cat.setAppKey(appName, dbname, dbstring, saveCallback);
});
return;
}
// set (add/update) entry to AKV database
this.catalog.setAppKey(appName, dbname, dbstring, callback);
this.catalog.setAppKey(appName, dbname, dbstring, saveCallback);
};

@@ -185,3 +193,3 @@

var adapter = this;
// lazy open/create db reference so dont -need- callback in constructor

@@ -191,13 +199,13 @@ if (this.catalog === null || this.catalog.db === null) {

adapter.catalog = cat;
adapter.deleteDatabase(dbname);
});
return;
}
// catalog was already initialized, so just lookup object and delete by id
this.catalog.getAppKey(appName, dbname, function(result) {
var id = result.id;
if (id !== 0) {

@@ -221,3 +229,3 @@ adapter.catalog.deleteAppKey(id);

var adapter = this;
// lazy open/create db reference so dont -need- callback in constructor

@@ -227,9 +235,9 @@ if (this.catalog === null || this.catalog.db === null) {

adapter.catalog = cat;
adapter.getDatabaseList(callback);
});
return;
}
// catalog already initialized

@@ -239,7 +247,7 @@ // get all keys for current appName, and transpose results so just string array

var names = [];
for(var idx = 0; idx < results.length; idx++) {
names.push(results[idx].key);
}
if (typeof (callback) === 'function') {

@@ -268,3 +276,3 @@ callback(names);

var adapter = this;
// lazy open/create db reference

@@ -274,9 +282,9 @@ if (this.catalog === null || this.catalog.db === null) {

adapter.catalog = cat;
adapter.getCatalogSummary(callback);
});
return;
}
// catalog already initialized

@@ -291,3 +299,3 @@ // get all keys for current appName, and transpose results so just string array

oval;
for(var idx = 0; idx < results.length; idx++) {

@@ -298,9 +306,9 @@ obj = results[idx];

oval = obj.val || '';
// app and key are composited into an appkey column so we will mult by 2
size = oapp.length * 2 + okey.length * 2 + oval.length + 1;
entries.push({ "app": obj.app, "key": obj.key, "size": size });
}
if (typeof (callback) === 'function') {

@@ -322,3 +330,3 @@ callback(entries);

*/
function LokiCatalog(callback)
function LokiCatalog(callback)
{

@@ -332,3 +340,3 @@ this.db = null;

var cat = this;
// If database doesn't exist yet or its version is lower than our version specified above (2nd param in line above)

@@ -347,3 +355,3 @@ openRequest.onupgradeneeded = function(e) {

// user (me) required to duplicate the app and key into comma delimited appkey field off object
// This will allow retrieving single record with that composite key as well as
// This will allow retrieving single record with that composite key as well as
// still supporting opening cursors on app or key alone

@@ -377,5 +385,5 @@ objectStore.createIndex('appkey', 'appkey', {unique:true});

if (lres === null || typeof(lres) === 'undefined') {
lres = {
id: 0,
success: false
lres = {
id: 0,
success: false
};

@@ -392,3 +400,3 @@ }

})(callback);
request.onerror = (function(usercallback) {

@@ -412,3 +420,3 @@ return function(e) {

request.onsuccess = (function(data, usercallback){
return function(e) {
return function(e) {
if (typeof(usercallback) === 'function') {

@@ -421,3 +429,3 @@ usercallback(e.target.result, data);

};
})(data, callback);
})(data, callback);
};

@@ -448,3 +456,3 @@

}
var requestPut = store.put(res);

@@ -487,3 +495,3 @@

LokiCatalog.prototype.deleteAppKey = function (id, callback) {
LokiCatalog.prototype.deleteAppKey = function (id, callback) {
var transaction = this.db.transaction(['LokiAKV'], 'readwrite');

@@ -523,3 +531,3 @@ var store = transaction.objectStore('LokiAKV');

// cursor internally, pushing results into this.data[] and return
// cursor internally, pushing results into this.data[] and return
// this.data[] when done (similar to service)

@@ -560,3 +568,3 @@ var localdata = [];

})(callback);
};

@@ -563,0 +571,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc