diff --git a/addons/Dexie.Observable/dist/README.md b/addons/Dexie.Observable/dist/README.md deleted file mode 100644 index f54e59357..000000000 --- a/addons/Dexie.Observable/dist/README.md +++ /dev/null @@ -1,37 +0,0 @@ -## Can't find dexie-observable.js? -Transpiled code (dist version) IS ONLY checked in to -the [releases](https://github.com/dfahlander/Dexie.js/tree/releases/addons/Dexie.Observable/dist) -branch. - -## Download -[unpkg.com/dexie-observable/dist/dexie-observable.js](https://unpkg.com/dexie-observable/dist/dexie-observable.js) - -[unpkg.com/dexie-observable/dist/dexie-observable.min.js](https://unpkg.com/dexie-observable/dist/dexie-observable.min.js) - -[unpkg.com/dexie-observable/dist/dexie-observable.js.map](https://unpkg.com/dexie-observable/dist/dexie-observable.js.map) - -[unpkg.com/dexie-observable/dist/dexie-observable.min.js.map](https://unpkg.com/dexie-observable/dist/dexie-observable.min.js.map) - -## npm -``` -npm install dexie-observable --save -``` -## bower -Since Dexie v1.3.4, addons are included in the dexie bower package. -``` -$ bower install dexie --save -$ ls bower_components/dexie/addons/Dexie.Observable/dist -dexie-observable.js dexie-observable.js.map dexie-observable.min.js dexie-observable.min.js.map - -``` -## Or build them yourself... -Fork Dexie.js, then: -``` -git clone https://github.com/YOUR-USERNAME/Dexie.js.git -cd Dexie.js -npm install -cd addons/Dexie.Observable -npm run build # or npm run watch - -``` -If you're on windows, you need to use an elevated command prompt of some reason to get `npm install` to work. diff --git a/addons/Dexie.Observable/dist/dexie-observable.js b/addons/Dexie.Observable/dist/dexie-observable.js new file mode 100644 index 000000000..281d33781 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js @@ -0,0 +1,840 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('dexie')) : + typeof define === 'function' && define.amd ? define(['dexie'], factory) : + (global.Dexie = global.Dexie || {}, global.Dexie.Observable = factory(global.Dexie)); +}(this, (function (Dexie) { 'use strict'; + +Dexie = 'default' in Dexie ? Dexie['default'] : Dexie; + +/// + +/** + * Dexie.Observable.js + * =================== + * Dexie addon for observing database changes not just on local db instance but also on other instances and windows. + * + * version: 0.1.9 Alpha, Thu Oct 13 2016 + * + * Disclaimber: This addon is in alpha status meaning that + * its API and behavior may change. + * + */ +var global = self; + +/** class DatabaseChange + * + * Object contained by the _changes table. + */ +var DatabaseChange = Dexie.defineClass({ + rev: Number, // Auto-incremented primary key + source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation. + table: String, // Table name + key: Object, // Primary key. Any type. + type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE + obj: Object, // CREATE: obj contains the object created. + mods: Object, // UPDATE: mods contains the modifications made to the object. + oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied. +}); + +// Import some usable helper functions +var override = Dexie.override; +var Promise = Dexie.Promise; +var browserIsShuttingDown = false; + +function Observable(db) { + /// + /// Extension to Dexie providing Syncronization capabilities to Dexie. + /// + /// + + var NODE_TIMEOUT = 20000, + // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects. + HIBERNATE_GRACE_PERIOD = 20000, + // 20 seconds + // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. + // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process) + LOCAL_POLL = 2000, + // 1 second. In real-world there will be this value + the time it takes to poll(). + CREATE = 1, + UPDATE = 2, + DELETE = 3; + + var localStorage = Observable.localStorageImpl; + + /** class SyncNode + * + * Object contained in the _syncNodes table. + */ + var SyncNode = Dexie.defineClass({ + //id: Number, + myRevision: Number, + type: String, // "local" or "remote" + lastHeartBeat: Number, + deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted. + url: String, // Only applicable for "remote" nodes. Only used in Dexie.Syncable. + isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB. + + // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == "remote"): + syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. + syncContext: null, + syncOptions: Object, + connected: false, // FIXTHIS: Remove! Replace with status. + status: Number, + appliedRemoteRevision: null, + remoteBaseRevisions: [{ local: Number, remote: null }], + dbUploadState: { + tablesToUpload: [String], + currentTable: String, + currentKey: null, + localBaseRevision: Number + } + }); + + var mySyncNode = null; + + // Allow other addons to access the local sync node. May be needed by Dexie.Syncable. + Object.defineProperty(db, "_localSyncNode", { + get: function () { + return mySyncNode; + } + }); + + var pollHandle = null; + + if (Dexie.fake) { + // This code will never run. + // It's here just to enable auto-complete in visual studio - helps a lot when writing code. + db.version(1).stores({ + _syncNodes: "++id,myRevision,lastHeartBeat", + _changes: "++rev", + _intercomm: "++id,destinationNode", + _uncommittedChanges: "++id,node" + }); + db._syncNodes.mapToClass(SyncNode); + db._changes.mapToClass(DatabaseChange); + mySyncNode = new SyncNode({ + myRevision: 0, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null + }); + } + + // + // Override parsing the stores to add "_changes" and "_syncNodes" tables. + // + db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, function (origFunc) { + return function (stores, dbSchema) { + // Create the _changes and _syncNodes tables + stores["_changes"] = "++rev"; + stores["_syncNodes"] = "++id,myRevision,lastHeartBeat,url,isMaster,type,status"; + stores["_intercomm"] = "++id,destinationNode"; + stores["_uncommittedChanges"] = "++id,node"; // For remote syncing when server returns a partial result. + // Call default implementation. Will populate the dbSchema structures. + origFunc.call(this, stores, dbSchema); + // Allow UUID primary keys using $$ prefix on primary key or indexes + Object.keys(dbSchema).forEach(function (tableName) { + var schema = dbSchema[tableName]; + if (schema.primKey.name.indexOf('$$') === 0) { + schema.primKey.uuid = true; + schema.primKey.name = schema.primKey.name.substr(2); + schema.primKey.keyPath = schema.primKey.keyPath.substr(2); + } + }); + // Now mark all observable tables + Object.keys(dbSchema).forEach(function (tableName) { + // Marked observable tables with "observable" in their TableSchema. + if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) { + dbSchema[tableName].observable = true; + } + }); + }; + }); + + // + // Make sure to subscribe to "creating", "updating" and "deleting" hooks for all observable tables that were created in the stores() method. + // + db._tableFactory = override(db._tableFactory, function (origCreateTable) { + return function createTable(mode, tableSchema, transactionPromiseFactory) { + var table = origCreateTable.apply(this, arguments); + if (table.schema.observable && transactionPromiseFactory === db._transPromiseFactory) { + // Only crudMonitor when creating + crudMonitor(table); + } + if (table.name === "_syncNodes" && transactionPromiseFactory === db._transPromiseFactory) { + table.mapToClass(SyncNode); + } + return table; + }; + }); + + // changes event on db: + db.on.addEventType({ + changes: 'asap', + cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master. + message: 'asap' + }); + + // + // Overide transaction creation to always include the "_changes" store when any observable store is involved. + // + db._createTransaction = override(db._createTransaction, function (origFunc) { + return function (mode, storenames, dbschema, parent) { + if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases. + var addChanges = false; + if (mode === 'readwrite' && storenames.some(function (storeName) { + return dbschema[storeName] && dbschema[storeName].observable; + })) { + // At least one included store is a observable store. Make sure to also include the _changes store. + addChanges = true; + storenames = storenames.slice(0); // Clone + if (storenames.indexOf("_changes") === -1) storenames.push("_changes"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla) + } + // Call original db._createTransaction() + var trans = origFunc.call(this, mode, storenames, dbschema, parent); + // If this transaction is bound to any observable table, make sure to add changes when transaction completes. + if (addChanges) { + trans._lastWrittenRevision = 0; + trans.on('complete', function () { + if (trans._lastWrittenRevision) { + // Changes were written in this transaction. + if (!parent) { + // This is root-level transaction, i.e. a physical commit has happened. + // Delay-trigger a wakeup call: + if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle); + wakeupObservers.timeoutHandle = setTimeout(function () { + delete wakeupObservers.timeoutHandle; + wakeupObservers(trans._lastWrittenRevision); + }, 25); + } else { + // This is just a virtual commit of a sub transaction. + // Wait with waking up observers until root transaction has committed. + // Make sure to mark root transaction so that it will wakeup observers upon commit. + var rootTransaction = function findRootTransaction(trans) { + return trans.parent ? findRootTransaction(trans.parent) : trans; + }(parent); + rootTransaction._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rootTransaction.lastWrittenRevision || 0); + } + } + }); + // Derive "source" property from parent transaction by default + if (trans.parent && trans.parent.source) trans.source = trans.parent.source; + } + return trans; + }; + }); + + // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works. + // You might think that it will always be undefined before this call, but in case another Dexie instance in the same + // window with the same database name has been created already, this static property will already be set correctly. + Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0; + + function wakeupObservers(lastWrittenRevision) { + // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too. + if (Observable.latestRevision[db.name] < lastWrittenRevision) { + // Set the static property lastRevision[db.name] to the revision of the last written change. + Observable.latestRevision[db.name] = lastWrittenRevision; + // Wakeup ourselves, and any other db instances on this window: + Dexie.ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision); + }); + // Observable.on.latestRevisionIncremented will only wakeup db's in current window. + // We need a storage event to wakeup other windwos. + // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for + // the purpose to wakeup db instances in other windows. + localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id. + } + } + + db.close = override(db.close, function (origClose) { + return function () { + if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases. + // Teardown our framework. + if (wakeupObservers.timeoutHandle) { + clearTimeout(wakeupObservers.timeoutHandle); + delete wakeupObservers.timeoutHandle; + } + Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented); + Observable.on('suicideNurseCall').unsubscribe(onSuicide); + Observable.on('intercomm').unsubscribe(onIntercomm); + Observable.on('beforeunload').unsubscribe(onBeforeUnload); + // Inform other db instances in same window that we are dying: + if (mySyncNode && mySyncNode.id) { + Observable.on.suicideNurseCall.fire(db.name, mySyncNode.id); + // Inform other windows as well: + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.id.toString() + '/' + db.name, "dead"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything. + mySyncNode.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode); // This async operation may be cancelled since the browser is closing down now. + mySyncNode = null; + } + + if (pollHandle) clearTimeout(pollHandle); + pollHandle = null; + return origClose.apply(this, arguments); + }; + }); + + // Override Dexie.delete() in order to delete Observable.latestRevision[db.name]. + db.delete = override(db.delete, function (origDelete) { + return function () { + return origDelete.apply(this, arguments).then(function (result) { + // Reset Observable.latestRevision[db.name] + Observable.latestRevision[db.name] = 0; + return result; + }); + }; + }); + + // + // The Creating/Updating/Deleting hook will make sure any change is stored to the changes table + // + function crudMonitor(table) { + /// + var tableName = table.name; + + table.hook('creating').subscribe(function (primKey, obj, trans) { + /// + var rv = undefined; + if (primKey === undefined && table.schema.primKey.uuid) { + primKey = rv = Observable.createUUID(); + if (table.schema.primKey.keyPath) { + Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey); + } + } + + var change = { + source: trans.source || null, // If a "source" is marked on the transaction, store it. Useful for observers that want to ignore their own changes. + table: tableName, + key: primKey === undefined ? null : primKey, + type: CREATE, + obj: obj + }; + + var promise = db._changes.add(change).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }); + + // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so. + this.onsuccess = function (resultKey) { + if (primKey != resultKey) promise._then(function () { + change.key = resultKey; + db._changes.put(change); + }); + }; + this.onerror = function (err) { + // If the main operation fails, make sure to regret the change + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + + return rv; + }); + + table.hook('updating').subscribe(function (mods, primKey, oldObj, trans) { + /// + // mods may contain property paths with undefined as value if the property + // is being deleted. Since we cannot persist undefined we need to act + // like those changes is setting the value to null instead. + var modsWithoutUndefined = {}; + // As of current Dexie version (1.0.3) hook may be called even if it wouldnt really change. + // Therefore we may do that kind of optimization here - to not add change entries if + // there's nothing to change. + var anythingChanged = false; + var newObj = Dexie.deepClone(oldObj); + for (var propPath in mods) { + var mod = mods[propPath]; + if (typeof mod === 'undefined') { + Dexie.delByKeyPath(newObj, propPath); + modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined. + anythingChanged = true; + } else { + var currentValue = Dexie.getByKeyPath(oldObj, propPath); + if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) { + Dexie.setByKeyPath(newObj, propPath, mod); + modsWithoutUndefined[propPath] = mod; + anythingChanged = true; + } + } + } + if (anythingChanged) { + var change = { + source: trans.source || null, // If a "source" is marked on the transaction, store it. Useful for observers that want to ignore their own changes. + table: tableName, + key: primKey, + type: UPDATE, + mods: modsWithoutUndefined, + oldObj: oldObj, + obj: newObj + }; + var promise = db._changes.add(change); // Just so we get the correct revision order of the update... + this.onsuccess = function () { + promise._then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + }); + }; + this.onerror = function (err) { + // If the main operation fails, make sure to regret the change. + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + } + }); + + table.hook('deleting').subscribe(function (primKey, obj, trans) { + /// + var promise = db._changes.add({ + source: trans.source || null, // If a "source" is marked on the transaction, store it. Useful for observers that want to ignore their own changes. + table: tableName, + key: primKey, + type: DELETE, + oldObj: obj + }).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }); + this.onerror = function () { + // If the main operation fails, make sure to regret the change. + // Using _then because if promise is already fullfilled, the standard then() would + // do setTimeout() and we would loose the transaction. + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + }); + } + + // When db opens, make sure to start monitor any changes before other db operations will start. + db.on("ready", function startObserving() { + if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases. + return db.table("_changes").orderBy("rev").last(function (lastChange) { + // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db. + // Therefore we know that the retrieved value will be This query will + var latestRevision = lastChange ? lastChange.rev : 0; + mySyncNode = new SyncNode({ + myRevision: latestRevision, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null, + isMaster: 0 + }); + if (Observable.latestRevision[db.name] < latestRevision) { + // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased: + // There are other db instances in same window that hasnt yet been informed about a new revision + Observable.latestRevision[db.name] = latestRevision; + Dexie.ignoreTransaction(function () { + Observable.on.latestRevisionIncremented.fire(latestRevision); + }); + } + // Add new sync node or if this is a reopening of the database after a close() call, update it. + return db.transaction('rw', '_syncNodes', function () { + db._syncNodes.where('isMaster').equals(1).count(function (anyMasterNode) { + if (!anyMasterNode) { + // There's no master node. Let's take that role then. + mySyncNode.isMaster = 1; + } + // Add our node to DB and start subscribing to events + db._syncNodes.add(mySyncNode).then(function () { + Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available. + Observable.on('beforeunload', onBeforeUnload); + Observable.on('suicideNurseCall', onSuicide); + Observable.on('intercomm', onIntercomm); + // Start polling for changes and do cleanups: + pollHandle = setTimeout(poll, LOCAL_POLL); + }); + }); + }).then(function () { + cleanup(); + }); + //cleanup(); + //}); + }); + }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()). + + var handledRevision = 0; + + function onLatestRevisionIncremented(dbname, latestRevision) { + if (dbname === db.name) { + if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window) + handledRevision = latestRevision; + Dexie.vip(function () { + readChanges(latestRevision).catch('DatabaseClosedError', function (e) { + // Handle database closed error gracefully while reading changes. + // Don't trigger unhandledrejection + // Even though we intercept the close() method, it might be called when in the middle of + // reading changes and then that flow will cancel with DatabaseClosedError. + }); + }); + } + } + + function readChanges(latestRevision, recursion, wasPartial) { + // Whenever changes are read, fire db.on("changes") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is + // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario + // should be handled in case database is totally empty we should fail if sync is not available) + if (!recursion && readChanges.ongoingOperation) { + // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event. + // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges(). + // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished. + return readChanges.ongoingOperation; + } + + var partial = false; + var ourSyncNode = mySyncNode; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened. + if (!ourSyncNode) { + return Promise.reject("Database closed"); + } + var LIMIT = 1000; + var promise = db._changes.where("rev").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) { + if (changes.length > 0) { + var lastChange = changes[changes.length - 1]; + partial = changes.length === LIMIT; + db.on('changes').fire(changes, partial); + ourSyncNode.myRevision = lastChange.rev; + } else if (wasPartial) { + // No more changes, BUT since we have triggered on('changes') with partial = true, + // we HAVE TO trigger changes again with empty list and partial = false + db.on('changes').fire([], false); + } + + return db.table("_syncNodes").update(ourSyncNode, { + lastHeartBeat: Date.now(), + deleteTimeStamp: null, // Reset "deleteTimeStamp" flag if it was there. + myRevision: ourSyncNode.myRevision + }); + }).then(function (nodeWasUpdated) { + if (!nodeWasUpdated) { + // My node has been deleted. We must have been lazy and got removed by another node. + if (browserIsShuttingDown) { + throw new Error("Browser is shutting down"); + } else { + db.close(); + console.error("Out of sync"); // TODO: What to do? Reload the page? + if (global.location) global.location.reload(true); + throw new Error("Out of sync"); // Will make current promise reject + } + } + + // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not + // resolve until all changes have been read. + if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) { + // Either there were more than 1000 changes or additional changes where added while we were reading these changes, + // In either case, call readChanges() again until we're done. + return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial); + } + }).finally(function () { + delete readChanges.ongoingOperation; + }); + + if (!recursion) { + readChanges.ongoingOperation = promise; + } + return promise; + } + + function poll() { + pollHandle = null; + var currentInstance = mySyncNode.id; + Dexie.vip(function () { + // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes. + readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages).catch('DatabaseClosedError', function (e) { + // Handle database closed error gracefully while reading changes. + // Don't signal 'unhandledrejection'. + // Even though we intercept the close() method, it might be called when in the middle of + // reading changes and then that flow will cancel with DatabaseClosedError. + }).finally(function () { + // Poll again in given interval: + if (mySyncNode && mySyncNode.id === currentInstance) { + pollHandle = setTimeout(poll, LOCAL_POLL); + } + }); + }); + } + + function cleanup() { + var ourSyncNode = mySyncNode; + if (!ourSyncNode) return Promise.reject("Database closed"); + return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function () { + // Cleanup dead local nodes that has no heartbeat for over a minute + // Dont do the following: + //nodes.where("lastHeartBeat").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == "local"; }).delete(); + // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes. + // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead. + var weBecameMaster = false; + db._syncNodes.where("lastHeartBeat").below(Date.now() - NODE_TIMEOUT).and(function (node) { + return node.type === 'local'; + }).modify(function (node) { + if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) { + // Delete the node. + delete this.value; + // Cleanup localStorage "deadnode:" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.) + localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name); + // Check if we are deleting a master node + if (node.isMaster) { + // The node we are deleting is master. We must take over that role. + // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction! + db._syncNodes.update(ourSyncNode, { isMaster: 1 }); + weBecameMaster = true; + } + // Cleanup intercomm messages destinated to the node being deleted: + db._intercomm.where("destinationNode").equals(node.id).modify(function (msg) { + // OK to call intercomm. No need to call Dexie.vip() because intercomm is opened in existing transaction! + // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request. + delete this.value; + if (msg.wantReply) { + // Message wants a reply, meaning someone must take over its messages when it dies. Let us be that one! + Dexie.ignoreTransaction(function () { + consumeMessage(msg); + }); + } + }); + } else if (!node.deleteTimeStamp) { + // Mark the node for deletion + node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD; + } + }).then(function () { + // Cleanup old revisions that no node is interested of. + Observable.deleteOldChanges(db); + return db.on("cleanup").fire(weBecameMaster); + }); + }); + } + + function onBeforeUnload(event) { + // Mark our own sync node for deletion. + if (!mySyncNode) return; + browserIsShuttingDown = true; + mySyncNode.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode); // This async operation may be cancelled since the browser is closing down now. + Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff... + // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below: + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.id.toString() + '/' + db.name, "dead"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below. + } + + function onSuicide(dbname, nodeID) { + if (dbname === db.name && !Observable.wereTheOneDying) { + // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies. + // It's own call to put() may have been cancelled. + // Note also that in IE, this event may be called twice, but that doesnt harm! + Dexie.vip(function () { + db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup); + }); + } + } + + // + // Intercommunication between nodes + // + // Enable inter-process communication between browser windows + + var requestsWaitingForReply = {}; + + db.sendMessage = function (type, message, destinationNode, options) { + /// Type of message + /// Message to send + /// ID of destination node + /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent. + if (!mySyncNode) return Promise.reject("Database closed"); + options = options || {}; + var msg = { message: message, destinationNode: destinationNode, sender: mySyncNode.id, type: type }; + Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ... + var tables = ["_intercomm"]; + if (options.wantReply) tables.push("_syncNodes"); // If caller wants a reply, include "_syncNodes" in transaction to check that there's a reciever there. Otherwise, new master will get it. + return db.transaction('rw?', tables, function () { + if (options.wantReply) { + // Check that there is a reciever there to take the request. + return db._syncNodes.where('id').equals(destinationNode).count(function (recieverAlive) { + if (recieverAlive) return addMessage(msg);else return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + msg.destinationNode = masterNode.id; + return addMessage(msg); + }); + }); + } else { + addMessage(msg); // No need to return Promise. Caller dont need a reply. + } + + function addMessage(msg) { + return db._intercomm.add(msg).then(function (messageId) { + localStorage.setItem("Dexie.Observable/intercomm/" + db.name, messageId.toString()); + Dexie.ignoreTransaction(function () { + Observable.on.intercomm.fire(db.name); + }); + if (options.wantReply) { + return new Promise(function (resolve, reject) { + requestsWaitingForReply[messageId.toString()] = { resolve: resolve, reject: reject }; + }); + } + }); + } + }); + }; + + db.broadcastMessage = function (type, message, bIncludeSelf) { + if (!mySyncNode) return Promise.reject("Database closed"); + var mySyncNodeId = mySyncNode.id; + db._syncNodes.each(function (node) { + if (node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId)) { + db.sendMessage(type, message, node.id); + } + }); + }; + + db.observable = {}; + db.observable.SyncNode = SyncNode; + + function consumeIntercommMessages() { + // Check if we got messages: + if (!mySyncNode) return Promise.reject("Database closed"); + return db.table('_intercomm').where("destinationNode").equals(mySyncNode.id).modify(function (msg) { + // For each message, fire the event and remove message. + delete this.value; + Dexie.ignoreTransaction(function () { + consumeMessage(msg); + }); + }); + } + + function consumeMessage(msg) { + if (msg.type === 'response') { + // This is a response. Lookup pending request and fulfill it's promise. + var request = requestsWaitingForReply[msg.requestId.toString()]; + if (request) { + if (msg.isFailure) { + request.reject(msg.message.error); + } else { + request.resolve(msg.message.result); + } + delete requestsWaitingForReply[msg.requestId.toString()]; + } + } else { + // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested + msg.resolve = function (result) { + db.sendMessage('response', { result: result }, msg.sender, { requestId: msg.id }); + }; + msg.reject = function (error) { + db.sendMessage('response', { error: error.toString() }, msg.sender, { isFailure: true, requestId: msg.id }); + }; + var message = msg.message; + delete msg.message; + Dexie.extend(msg, message); + db.on.message.fire(msg); + } + } + + function onIntercomm(dbname) { + // When storage event trigger us to check + if (dbname === db.name) { + consumeIntercommMessages(); + } + } +} + +// +// Help functions +// + +function nop() {} + +function promisableChain(f1, f2) { + if (f1 === nop) return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, + args = arguments; + return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} + +// +// Static properties and methods +// + +Observable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37; +Observable.on = Dexie.Events(null, "latestRevisionIncremented", "suicideNurseCall", "intercomm", "beforeunload"); // fire(dbname, value); +Observable.createUUID = function () { + // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript + var d = Date.now(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (d + Math.random() * 16) % 16 | 0; + d = Math.floor(d / 16); + return (c === 'x' ? r : r & 0x7 | 0x8).toString(16); + }); + return uuid; +}; + +Observable.deleteOldChanges = function (db) { + db._syncNodes.orderBy("myRevision").first(function (oldestNode) { + var timeout = Date.now() + 300, + timedout = false; + db._changes.where("rev").below(oldestNode.myRevision).until(function () { + return timedout = Date.now() > timeout; + }).delete().then(function () { + // If not done garbage collecting, reschedule a continuation of it until done. + if (timedout) setTimeout(function () { + Observable.deleteOldChanges(db); + }, 10); + }); + }); +}; + +Observable._onStorage = function onStorage(event) { + // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well! + if (event.key.indexOf("Dexie.Observable/") === 0) { + // For example "Dexie.Observable/latestRevision/FriendsDB" + var parts = event.key.split('/'); + var prop = parts[1]; + var dbname = parts[2]; + if (prop === 'latestRevision') { + var rev = parseInt(event.newValue, 10); + if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) { + Observable.latestRevision[dbname] = rev; + Dexie.ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(dbname, rev); + }); + } + } else if (prop.indexOf("deadnode:") === 0) { + var nodeID = parseInt(prop.split(':')[1], 10); + if (event.newValue) { + Observable.on.suicideNurseCall.fire(dbname, nodeID); + } + } else if (prop === 'intercomm') { + if (event.newValue) { + Observable.on.intercomm.fire(dbname); + } + } + } +}; + +Observable._onBeforeUnload = function () { + Observable.on.beforeunload.fire(); +}; + +Observable.localStorageImpl = global.localStorage; + +// +// Map window events to static events in Dexie.Observable: +// +if (global.addEventListener) { + global.addEventListener("storage", Observable._onStorage); + global.addEventListener("beforeunload", Observable._onBeforeUnload); +} +// Register addon: +Dexie.Observable = Observable; +Dexie.addons.push(Observable); + +return Observable; + +}))); +//# sourceMappingURL=dexie-observable.js.map diff --git a/addons/Dexie.Observable/dist/dexie-observable.js.map b/addons/Dexie.Observable/dist/dexie-observable.js.map new file mode 100644 index 000000000..6637f0fe6 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-observable.js","sources":["../tools/tmp/src/Dexie.Observable.js"],"sourcesContent":["/// \n\n/**\r\n * Dexie.Observable.js\r\n * ===================\r\n * Dexie addon for observing database changes not just on local db instance but also on other instances and windows.\r\n *\r\n * version: {version} Alpha, {date}\r\n *\r\n * Disclaimber: This addon is in alpha status meaning that\r\n * its API and behavior may change.\r\n *\r\n */\nimport Dexie from 'dexie';\n\nvar global = self;\n\n/** class DatabaseChange\r\n *\r\n * Object contained by the _changes table.\r\n */\nvar DatabaseChange = Dexie.defineClass({\n rev: Number, // Auto-incremented primary key\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\n table: String, // Table name\n key: Object, // Primary key. Any type.\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\n obj: Object, // CREATE: obj contains the object created.\n mods: Object, // UPDATE: mods contains the modifications made to the object.\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\n});\n\n// Import some usable helper functions\nvar override = Dexie.override;\nvar Promise = Dexie.Promise;\nvar browserIsShuttingDown = false;\n\nexport default function Observable(db) {\n /// \n /// Extension to Dexie providing Syncronization capabilities to Dexie.\n /// \n /// \n\n var NODE_TIMEOUT = 20000,\n // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects.\n HIBERNATE_GRACE_PERIOD = 20000,\n // 20 seconds\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \n // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process)\n LOCAL_POLL = 2000,\n // 1 second. In real-world there will be this value + the time it takes to poll().\n CREATE = 1,\n UPDATE = 2,\n DELETE = 3;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\r\n *\r\n * Object contained in the _syncNodes table.\r\n */\n var SyncNode = Dexie.defineClass({\n //id: Number,\n myRevision: Number,\n type: String, // \"local\" or \"remote\"\n lastHeartBeat: Number,\n deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted.\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\n\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \n syncContext: null,\n syncOptions: Object,\n connected: false, // FIXTHIS: Remove! Replace with status.\n status: Number,\n appliedRemoteRevision: null,\n remoteBaseRevisions: [{ local: Number, remote: null }],\n dbUploadState: {\n tablesToUpload: [String],\n currentTable: String,\n currentKey: null,\n localBaseRevision: Number\n }\n });\n\n var mySyncNode = null;\n\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\n Object.defineProperty(db, \"_localSyncNode\", {\n get: function () {\n return mySyncNode;\n }\n });\n\n var pollHandle = null;\n\n if (Dexie.fake) {\n // This code will never run.\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\n db.version(1).stores({\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\n _changes: \"++rev\",\n _intercomm: \"++id,destinationNode\",\n _uncommittedChanges: \"++id,node\"\n });\n db._syncNodes.mapToClass(SyncNode);\n db._changes.mapToClass(DatabaseChange);\n mySyncNode = new SyncNode({\n myRevision: 0,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null\n });\n }\n\n //\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, function (origFunc) {\n return function (stores, dbSchema) {\n // Create the _changes and _syncNodes tables\n stores[\"_changes\"] = \"++rev\";\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,url,isMaster,type,status\";\n stores[\"_intercomm\"] = \"++id,destinationNode\";\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\n // Call default implementation. Will populate the dbSchema structures.\n origFunc.call(this, stores, dbSchema);\n // Allow UUID primary keys using $$ prefix on primary key or indexes\n Object.keys(dbSchema).forEach(function (tableName) {\n var schema = dbSchema[tableName];\n if (schema.primKey.name.indexOf('$$') === 0) {\n schema.primKey.uuid = true;\n schema.primKey.name = schema.primKey.name.substr(2);\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\n }\n });\n // Now mark all observable tables\n Object.keys(dbSchema).forEach(function (tableName) {\n // Marked observable tables with \"observable\" in their TableSchema.\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\n dbSchema[tableName].observable = true;\n }\n });\n };\n });\n\n //\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\n //\n db._tableFactory = override(db._tableFactory, function (origCreateTable) {\n return function createTable(mode, tableSchema, transactionPromiseFactory) {\n var table = origCreateTable.apply(this, arguments);\n if (table.schema.observable && transactionPromiseFactory === db._transPromiseFactory) {\n // Only crudMonitor when creating \n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\" && transactionPromiseFactory === db._transPromiseFactory) {\n table.mapToClass(SyncNode);\n }\n return table;\n };\n });\n\n // changes event on db:\n db.on.addEventType({\n changes: 'asap',\n cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master.\n message: 'asap'\n });\n\n //\n // Overide transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, function (origFunc) {\n return function (mode, storenames, dbschema, parent) {\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\n var addChanges = false;\n if (mode === 'readwrite' && storenames.some(function (storeName) {\n return dbschema[storeName] && dbschema[storeName].observable;\n })) {\n // At least one included store is a observable store. Make sure to also include the _changes store.\n addChanges = true;\n storenames = storenames.slice(0); // Clone\n if (storenames.indexOf(\"_changes\") === -1) storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\n }\n // Call original db._createTransaction()\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\n if (addChanges) {\n trans._lastWrittenRevision = 0;\n trans.on('complete', function () {\n if (trans._lastWrittenRevision) {\n // Changes were written in this transaction.\n if (!parent) {\n // This is root-level transaction, i.e. a physical commit has happened.\n // Delay-trigger a wakeup call:\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\n wakeupObservers.timeoutHandle = setTimeout(function () {\n delete wakeupObservers.timeoutHandle;\n wakeupObservers(trans._lastWrittenRevision);\n }, 25);\n } else {\n // This is just a virtual commit of a sub transaction.\n // Wait with waking up observers until root transaction has committed.\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\n var rootTransaction = function findRootTransaction(trans) {\n return trans.parent ? findRootTransaction(trans.parent) : trans;\n }(parent);\n rootTransaction._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rootTransaction.lastWrittenRevision || 0);\n }\n }\n });\n // Derive \"source\" property from parent transaction by default\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\n }\n return trans;\n };\n });\n\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\n // window with the same database name has been created already, this static property will already be set correctly.\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\n\n function wakeupObservers(lastWrittenRevision) {\n // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too.\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\n // Set the static property lastRevision[db.name] to the revision of the last written change.\n Observable.latestRevision[db.name] = lastWrittenRevision;\n // Wakeup ourselves, and any other db instances on this window:\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\n });\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\n // We need a storage event to wakeup other windwos.\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\n // the purpose to wakeup db instances in other windows.\n localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id.\n }\n }\n\n db.close = override(db.close, function (origClose) {\n return function () {\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\n // Teardown our framework.\n if (wakeupObservers.timeoutHandle) {\n clearTimeout(wakeupObservers.timeoutHandle);\n delete wakeupObservers.timeoutHandle;\n }\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\n Observable.on('intercomm').unsubscribe(onIntercomm);\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\n // Inform other db instances in same window that we are dying:\n if (mySyncNode && mySyncNode.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.id);\n // Inform other windows as well:\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything.\n mySyncNode.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n return origClose.apply(this, arguments);\n };\n });\n\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\n db.delete = override(db.delete, function (origDelete) {\n return function () {\n return origDelete.apply(this, arguments).then(function (result) {\n // Reset Observable.latestRevision[db.name]\n Observable.latestRevision[db.name] = 0;\n return result;\n });\n };\n });\n\n //\n // The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n //\n function crudMonitor(table) {\n /// \n var tableName = table.name;\n\n table.hook('creating').subscribe(function (primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = Observable.createUUID();\n if (table.schema.primKey.keyPath) {\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\n }\n }\n\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey === undefined ? null : primKey,\n type: CREATE,\n obj: obj\n };\n\n var promise = db._changes.add(change).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\n this.onsuccess = function (resultKey) {\n if (primKey != resultKey) promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n this.onerror = function (err) {\n // If the main operation fails, make sure to regret the change\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n\n return rv;\n });\n\n table.hook('updating').subscribe(function (mods, primKey, oldObj, trans) {\n /// \n // mods may contain property paths with undefined as value if the property\n // is being deleted. Since we cannot persist undefined we need to act\n // like those changes is setting the value to null instead.\n var modsWithoutUndefined = {};\n // As of current Dexie version (1.0.3) hook may be called even if it wouldnt really change.\n // Therefore we may do that kind of optimization here - to not add change entries if\n // there's nothing to change.\n var anythingChanged = false;\n var newObj = Dexie.deepClone(oldObj);\n for (var propPath in mods) {\n var mod = mods[propPath];\n if (typeof mod === 'undefined') {\n Dexie.delByKeyPath(newObj, propPath);\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\n anythingChanged = true;\n } else {\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\n Dexie.setByKeyPath(newObj, propPath, mod);\n modsWithoutUndefined[propPath] = mod;\n anythingChanged = true;\n }\n }\n }\n if (anythingChanged) {\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: UPDATE,\n mods: modsWithoutUndefined,\n oldObj: oldObj,\n obj: newObj\n };\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\n this.onsuccess = function () {\n promise._then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n });\n };\n this.onerror = function (err) {\n // If the main operation fails, make sure to regret the change.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n }\n });\n\n table.hook('deleting').subscribe(function (primKey, obj, trans) {\n /// \n var promise = db._changes.add({\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: DELETE,\n oldObj: obj\n }).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n // Using _then because if promise is already fullfilled, the standard then() would\n // do setTimeout() and we would loose the transaction.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n });\n }\n\n // When db opens, make sure to start monitor any changes before other db operations will start.\n db.on(\"ready\", function startObserving() {\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\n return db.table(\"_changes\").orderBy(\"rev\").last(function (lastChange) {\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\n // Therefore we know that the retrieved value will be This query will\n var latestRevision = lastChange ? lastChange.rev : 0;\n mySyncNode = new SyncNode({\n myRevision: latestRevision,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null,\n isMaster: 0\n });\n if (Observable.latestRevision[db.name] < latestRevision) {\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\n // There are other db instances in same window that hasnt yet been informed about a new revision\n Observable.latestRevision[db.name] = latestRevision;\n Dexie.ignoreTransaction(function () {\n Observable.on.latestRevisionIncremented.fire(latestRevision);\n });\n }\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\n return db.transaction('rw', '_syncNodes', function () {\n db._syncNodes.where('isMaster').equals(1).count(function (anyMasterNode) {\n if (!anyMasterNode) {\n // There's no master node. Let's take that role then.\n mySyncNode.isMaster = 1;\n }\n // Add our node to DB and start subscribing to events\n db._syncNodes.add(mySyncNode).then(function () {\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\n Observable.on('beforeunload', onBeforeUnload);\n Observable.on('suicideNurseCall', onSuicide);\n Observable.on('intercomm', onIntercomm);\n // Start polling for changes and do cleanups:\n pollHandle = setTimeout(poll, LOCAL_POLL);\n });\n });\n }).then(function () {\n cleanup();\n });\n //cleanup();\n //});\n });\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\n\n var handledRevision = 0;\n\n function onLatestRevisionIncremented(dbname, latestRevision) {\n if (dbname === db.name) {\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\n handledRevision = latestRevision;\n Dexie.vip(function () {\n readChanges(latestRevision).catch('DatabaseClosedError', function (e) {\n // Handle database closed error gracefully while reading changes.\n // Don't trigger unhandledrejection\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n });\n });\n }\n }\n\n function readChanges(latestRevision, recursion, wasPartial) {\n // Whenever changes are read, fire db.on(\"changes\") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is\n // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario\n // should be handled in case database is totally empty we should fail if sync is not available)\n if (!recursion && readChanges.ongoingOperation) {\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\n // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges().\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\n return readChanges.ongoingOperation;\n }\n\n var partial = false;\n var ourSyncNode = mySyncNode; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened.\n if (!ourSyncNode) {\n return Promise.reject(\"Database closed\");\n }\n var LIMIT = 1000;\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\n if (changes.length > 0) {\n var lastChange = changes[changes.length - 1];\n partial = changes.length === LIMIT;\n db.on('changes').fire(changes, partial);\n ourSyncNode.myRevision = lastChange.rev;\n } else if (wasPartial) {\n // No more changes, BUT since we have triggered on('changes') with partial = true,\n // we HAVE TO trigger changes again with empty list and partial = false\n db.on('changes').fire([], false);\n }\n\n return db.table(\"_syncNodes\").update(ourSyncNode, {\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null, // Reset \"deleteTimeStamp\" flag if it was there.\n myRevision: ourSyncNode.myRevision\n });\n }).then(function (nodeWasUpdated) {\n if (!nodeWasUpdated) {\n // My node has been deleted. We must have been lazy and got removed by another node.\n if (browserIsShuttingDown) {\n throw new Error(\"Browser is shutting down\");\n } else {\n db.close();\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\n if (global.location) global.location.reload(true);\n throw new Error(\"Out of sync\"); // Will make current promise reject\n }\n }\n\n // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not\n // resolve until all changes have been read.\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\n // In either case, call readChanges() again until we're done.\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\n }\n }).finally(function () {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.id;\n Dexie.vip(function () {\n // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages).catch('DatabaseClosedError', function (e) {\n // Handle database closed error gracefully while reading changes.\n // Don't signal 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n }).finally(function () {\n // Poll again in given interval:\n if (mySyncNode && mySyncNode.id === currentInstance) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n function cleanup() {\n var ourSyncNode = mySyncNode;\n if (!ourSyncNode) return Promise.reject(\"Database closed\");\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function () {\n // Cleanup dead local nodes that has no heartbeat for over a minute\n // Dont do the following:\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\n // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead.\n var weBecameMaster = false;\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) {\n return node.type === 'local';\n }).modify(function (node) {\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\n // Delete the node.\n delete this.value;\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n // Check if we are deleting a master node\n if (node.isMaster) {\n // The node we are deleting is master. We must take over that role.\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\n weBecameMaster = true;\n }\n // Cleanup intercomm messages destinated to the node being deleted:\n db._intercomm.where(\"destinationNode\").equals(node.id).modify(function (msg) {\n // OK to call intercomm. No need to call Dexie.vip() because intercomm is opened in existing transaction!\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\n if (msg.wantReply) {\n // Message wants a reply, meaning someone must take over its messages when it dies. Let us be that one!\n Dexie.ignoreTransaction(function () {\n consumeMessage(msg);\n });\n }\n });\n } else if (!node.deleteTimeStamp) {\n // Mark the node for deletion\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\n }\n }).then(function () {\n // Cleanup old revisions that no node is interested of.\n Observable.deleteOldChanges(db);\n return db.on(\"cleanup\").fire(weBecameMaster);\n });\n });\n }\n\n function onBeforeUnload(event) {\n // Mark our own sync node for deletion.\n if (!mySyncNode) return;\n browserIsShuttingDown = true;\n mySyncNode.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode); // This async operation may be cancelled since the browser is closing down now.\n Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff...\n // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below:\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below.\n }\n\n function onSuicide(dbname, nodeID) {\n if (dbname === db.name && !Observable.wereTheOneDying) {\n // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies.\n // It's own call to put() may have been cancelled.\n // Note also that in IE, this event may be called twice, but that doesnt harm!\n Dexie.vip(function () {\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\n });\n }\n }\n\n //\n // Intercommunication between nodes\n //\n // Enable inter-process communication between browser windows\n\n var requestsWaitingForReply = {};\n\n db.sendMessage = function (type, message, destinationNode, options) {\n /// Type of message\n /// Message to send\n /// ID of destination node\n /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n if (!mySyncNode) return Promise.reject(\"Database closed\");\n options = options || {};\n var msg = { message: message, destinationNode: destinationNode, sender: mySyncNode.id, type: type };\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n var tables = [\"_intercomm\"];\n if (options.wantReply) tables.push(\"_syncNodes\"); // If caller wants a reply, include \"_syncNodes\" in transaction to check that there's a reciever there. Otherwise, new master will get it.\n return db.transaction('rw?', tables, function () {\n if (options.wantReply) {\n // Check that there is a reciever there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(function (recieverAlive) {\n if (recieverAlive) return addMessage(msg);else return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return addMessage(msg);\n });\n });\n } else {\n addMessage(msg); // No need to return Promise. Caller dont need a reply.\n }\n\n function addMessage(msg) {\n return db._intercomm.add(msg).then(function (messageId) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n Dexie.ignoreTransaction(function () {\n Observable.on.intercomm.fire(db.name);\n });\n if (options.wantReply) {\n return new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = { resolve: resolve, reject: reject };\n });\n }\n });\n }\n });\n };\n\n db.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode) return Promise.reject(\"Database closed\");\n var mySyncNodeId = mySyncNode.id;\n db._syncNodes.each(function (node) {\n if (node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId)) {\n db.sendMessage(type, message, node.id);\n }\n });\n };\n\n db.observable = {};\n db.observable.SyncNode = SyncNode;\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode) return Promise.reject(\"Database closed\");\n return db.table('_intercomm').where(\"destinationNode\").equals(mySyncNode.id).modify(function (msg) {\n // For each message, fire the event and remove message.\n delete this.value;\n Dexie.ignoreTransaction(function () {\n consumeMessage(msg);\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill it's promise.\n var request = requestsWaitingForReply[msg.requestId.toString()];\n if (request) {\n if (msg.isFailure) {\n request.reject(msg.message.error);\n } else {\n request.resolve(msg.message.result);\n }\n delete requestsWaitingForReply[msg.requestId.toString()];\n }\n } else {\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\n msg.resolve = function (result) {\n db.sendMessage('response', { result: result }, msg.sender, { requestId: msg.id });\n };\n msg.reject = function (error) {\n db.sendMessage('response', { error: error.toString() }, msg.sender, { isFailure: true, requestId: msg.id });\n };\n var message = msg.message;\n delete msg.message;\n Dexie.extend(msg, message);\n db.on.message.fire(msg);\n }\n }\n\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages();\n }\n }\n}\n\n//\n// Help functions\n//\n\nfunction nop() {};\n\nfunction promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n args = arguments;\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\n//\n// Static properties and methods\n// \n\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\nObservable.createUUID = function () {\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n var d = Date.now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : r & 0x7 | 0x8).toString(16);\n });\n return uuid;\n};\n\nObservable.deleteOldChanges = function (db) {\n db._syncNodes.orderBy(\"myRevision\").first(function (oldestNode) {\n var timeout = Date.now() + 300,\n timedout = false;\n db._changes.where(\"rev\").below(oldestNode.myRevision).until(function () {\n return timedout = Date.now() > timeout;\n }).delete().then(function () {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (timedout) setTimeout(function () {\n Observable.deleteOldChanges(db);\n }, 10);\n });\n });\n};\n\nObservable._onStorage = function onStorage(event) {\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) {\n // For example \"Dexie.Observable/latestRevision/FriendsDB\"\n var parts = event.key.split('/');\n var prop = parts[1];\n var dbname = parts[2];\n if (prop === 'latestRevision') {\n var rev = parseInt(event.newValue, 10);\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\n Observable.latestRevision[dbname] = rev;\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\n });\n }\n } else if (prop.indexOf(\"deadnode:\") === 0) {\n var nodeID = parseInt(prop.split(':')[1], 10);\n if (event.newValue) {\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\n }\n } else if (prop === 'intercomm') {\n if (event.newValue) {\n Observable.on.intercomm.fire(dbname);\n }\n }\n }\n};\n\nObservable._onBeforeUnload = function () {\n Observable.on.beforeunload.fire();\n};\n\nObservable.localStorageImpl = global.localStorage;\n\n//\n// Map window events to static events in Dexie.Observable:\n//\nif (global.addEventListener) {\n global.addEventListener(\"storage\", Observable._onStorage);\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\n}\n// Register addon:\nDexie.Observable = Observable;\nDexie.addons.push(Observable);"],"names":[],"mappings":";;;;;;;;AAAA;;;;;;;;;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,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACvE;;AAED,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;AAC9B,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,;;,;;"} \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.min.js b/addons/Dexie.Observable/dist/dexie-observable.min.js new file mode 100644 index 000000000..edeb924cd --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n(require("dexie")):"function"==typeof define&&define.amd?define(["dexie"],n):(e.Dexie=e.Dexie||{},e.Dexie.Observable=n(e.Dexie))}(this,function(e){"use strict";function n(l){function u(t){n.latestRevision[l.name]=t)return;I=t,e.vip(function(){m(t).catch("DatabaseClosedError",function(e){})})}}function m(e,t,i){if(!t&&m.ongoingOperation)return m.ongoingOperation;var r=!1,a=j;if(!a)return s.reject("Database closed");var u=1e3,d=l._changes.where("rev").above(a.myRevision).limit(u).toArray(function(e){if(e.length>0){var n=e[e.length-1];r=e.length===u,l.on("changes").fire(e,r),a.myRevision=n.rev}else i&&l.on("changes").fire([],!1);return l.table("_syncNodes").update(a,{lastHeartBeat:Date.now(),deleteTimeStamp:null,myRevision:a.myRevision})}).then(function(e){if(!e)throw c?new Error("Browser is shutting down"):(l.close(),console.error("Out of sync"),o.location&&o.location.reload(!0),new Error("Out of sync"));if(r||n.latestRevision[l.name]>a.myRevision)return m(n.latestRevision[l.name],(t||0)+1,r)}).finally(function(){delete m.ongoingOperation});return t||(m.ongoingOperation=d),d}function v(){B=null;var t=j.id;e.vip(function(){m(n.latestRevision[l.name]).then(y).then(b).catch("DatabaseClosedError",function(e){}).finally(function(){j&&j.id===t&&(B=setTimeout(v,N))})})}function y(){var t=j;return t?l.transaction("rw","_syncNodes","_changes","_intercomm",function(){var i=!1;l._syncNodes.where("lastHeartBeat").below(Date.now()-x).and(function(e){return"local"===e.type}).modify(function(n){n.deleteTimeStamp&&n.deleteTimeStampi}).delete().then(function(){o&&setTimeout(function(){n.deleteOldChanges(e)},10)})})},n._onStorage=function(t){if(0===t.key.indexOf("Dexie.Observable/")){var i=t.key.split("/"),o=i[1],r=i[2];if("latestRevision"===o){var a=parseInt(t.newValue,10);!isNaN(a)&&a>n.latestRevision[r]&&(n.latestRevision[r]=a,e.ignoreTransaction(function(){n.on("latestRevisionIncremented").fire(r,a)}))}else if(0===o.indexOf("deadnode:")){var s=parseInt(o.split(":")[1],10);t.newValue&&n.on.suicideNurseCall.fire(r,s)}else"intercomm"===o&&t.newValue&&n.on.intercomm.fire(r)}},n._onBeforeUnload=function(){n.on.beforeunload.fire()},n.localStorageImpl=o.localStorage,o.addEventListener&&(o.addEventListener("storage",n._onStorage),o.addEventListener("beforeunload",n._onBeforeUnload)),e.Observable=n,e.addons.push(n),n}); +//# sourceMappingURL=dexie-observable.min.js.map \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.min.js.map b/addons/Dexie.Observable/dist/dexie-observable.min.js.map new file mode 100644 index 000000000..bd9a3cee6 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../tools/tmp/src/Dexie.Observable.js"],"names":["Observable","db","wakeupObservers","lastWrittenRevision","latestRevision","name","Dexie","ignoreTransaction","on","fire","localStorage","setItem","crudMonitor","table","tableName","hook","subscribe","primKey","obj","trans","rv","undefined","schema","uuid","createUUID","keyPath","setByKeyPath","change","source","key","type","CREATE","promise","_changes","add","then","rev","_lastWrittenRevision","Math","max","this","onsuccess","resultKey","_then","put","onerror","err","delete","mods","oldObj","modsWithoutUndefined","anythingChanged","newObj","deepClone","propPath","mod","delByKeyPath","currentValue","getByKeyPath","JSON","stringify","UPDATE","DELETE","onLatestRevisionIncremented","dbname","handledRevision","vip","readChanges","catch","e","recursion","wasPartial","ongoingOperation","partial","ourSyncNode","mySyncNode","Promise","reject","LIMIT","where","above","myRevision","limit","toArray","changes","length","lastChange","update","lastHeartBeat","Date","now","deleteTimeStamp","nodeWasUpdated","browserIsShuttingDown","Error","close","console","error","global","location","reload","finally","poll","pollHandle","currentInstance","id","cleanup","consumeIntercommMessages","setTimeout","LOCAL_POLL","transaction","weBecameMaster","_syncNodes","below","NODE_TIMEOUT","and","node","modify","value","removeItem","isMaster","_intercomm","equals","msg","wantReply","consumeMessage","HIBERNATE_GRACE_PERIOD","deleteOldChanges","onBeforeUnload","event","wereTheOneDying","toString","onSuicide","nodeID","request","requestsWaitingForReply","requestId","isFailure","message","resolve","result","sendMessage","sender","extend","onIntercomm","localStorageImpl","SyncNode","defineClass","Number","String","url","syncProtocol","syncContext","syncOptions","Object","connected","status","appliedRemoteRevision","remoteBaseRevisions","local","remote","dbUploadState","tablesToUpload","currentTable","currentKey","localBaseRevision","defineProperty","get","fake","version","stores","_uncommittedChanges","mapToClass","DatabaseChange","Version","prototype","_parseStoresSpec","override","origFunc","dbSchema","call","keys","forEach","indexOf","substr","observable","_tableFactory","origCreateTable","mode","tableSchema","transactionPromiseFactory","apply","arguments","_transPromiseFactory","addEventType","promisableChain","nop","_createTransaction","storenames","dbschema","parent","dynamicallyOpened","addChanges","some","storeName","slice","push","rootTransaction","findRootTransaction","timeoutHandle","clearTimeout","origClose","unsubscribe","suicideNurseCall","origDelete","orderBy","last","latestRevisionIncremented","count","anyMasterNode","destinationNode","options","tables","addMessage","messageId","intercomm","recieverAlive","first","masterNode","broadcastMessage","bIncludeSelf","mySyncNodeId","each","f1","f2","res","thiz","args","self","Events","d","replace","c","r","random","floor","oldestNode","timeout","timedout","until","_onStorage","parts","split","prop","parseInt","newValue","isNaN","_onBeforeUnload","beforeunload","addEventListener","addons"],"mappings":"mPAqCA,SAAwBA,GAAWC,GA4L/B,QAASC,GAAgBC,GAEjBH,EAAWI,eAAeH,EAAGI,MAAQF,IAErCH,EAAWI,eAAeH,EAAGI,MAAQF,EAErCG,EAAMC,kBAAkB,WACp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* Dexie addon for observing database changes not just on local db instance but also on other instances and windows.\r\n *\r\n * version: {version} Alpha, {date}\r\n *\r\n * Disclaimber: This addon is in alpha status meaning that\r\n * its API and behavior may change.\r\n *\r\n */\nimport Dexie from 'dexie';\n\nvar global = self;\n\n/** class DatabaseChange\r\n *\r\n * Object contained by the _changes table.\r\n */\nvar DatabaseChange = Dexie.defineClass({\n rev: Number, // Auto-incremented primary key\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\n table: String, // Table name\n key: Object, // Primary key. Any type.\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\n obj: Object, // CREATE: obj contains the object created.\n mods: Object, // UPDATE: mods contains the modifications made to the object.\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\n});\n\n// Import some usable helper functions\nvar override = Dexie.override;\nvar Promise = Dexie.Promise;\nvar browserIsShuttingDown = false;\n\nexport default function Observable(db) {\n /// \n /// Extension to Dexie providing Syncronization capabilities to Dexie.\n /// \n /// \n\n var NODE_TIMEOUT = 20000,\n // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects.\n HIBERNATE_GRACE_PERIOD = 20000,\n // 20 seconds\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \n // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process)\n LOCAL_POLL = 2000,\n // 1 second. In real-world there will be this value + the time it takes to poll().\n CREATE = 1,\n UPDATE = 2,\n DELETE = 3;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\r\n *\r\n * Object contained in the _syncNodes table.\r\n */\n var SyncNode = Dexie.defineClass({\n //id: Number,\n myRevision: Number,\n type: String, // \"local\" or \"remote\"\n lastHeartBeat: Number,\n deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted.\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\n\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \n syncContext: null,\n syncOptions: Object,\n connected: false, // FIXTHIS: Remove! Replace with status.\n status: Number,\n appliedRemoteRevision: null,\n remoteBaseRevisions: [{ local: Number, remote: null }],\n dbUploadState: {\n tablesToUpload: [String],\n currentTable: String,\n currentKey: null,\n localBaseRevision: Number\n }\n });\n\n var mySyncNode = null;\n\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\n Object.defineProperty(db, \"_localSyncNode\", {\n get: function () {\n return mySyncNode;\n }\n });\n\n var pollHandle = null;\n\n if (Dexie.fake) {\n // This code will never run.\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\n db.version(1).stores({\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\n _changes: \"++rev\",\n _intercomm: \"++id,destinationNode\",\n _uncommittedChanges: \"++id,node\"\n });\n db._syncNodes.mapToClass(SyncNode);\n db._changes.mapToClass(DatabaseChange);\n mySyncNode = new SyncNode({\n myRevision: 0,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null\n });\n }\n\n //\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, function (origFunc) {\n return function (stores, dbSchema) {\n // Create the _changes and _syncNodes tables\n stores[\"_changes\"] = \"++rev\";\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,url,isMaster,type,status\";\n stores[\"_intercomm\"] = \"++id,destinationNode\";\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\n // Call default implementation. Will populate the dbSchema structures.\n origFunc.call(this, stores, dbSchema);\n // Allow UUID primary keys using $$ prefix on primary key or indexes\n Object.keys(dbSchema).forEach(function (tableName) {\n var schema = dbSchema[tableName];\n if (schema.primKey.name.indexOf('$$') === 0) {\n schema.primKey.uuid = true;\n schema.primKey.name = schema.primKey.name.substr(2);\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\n }\n });\n // Now mark all observable tables\n Object.keys(dbSchema).forEach(function (tableName) {\n // Marked observable tables with \"observable\" in their TableSchema.\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\n dbSchema[tableName].observable = true;\n }\n });\n };\n });\n\n //\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\n //\n db._tableFactory = override(db._tableFactory, function (origCreateTable) {\n return function createTable(mode, tableSchema, transactionPromiseFactory) {\n var table = origCreateTable.apply(this, arguments);\n if (table.schema.observable && transactionPromiseFactory === db._transPromiseFactory) {\n // Only crudMonitor when creating \n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\" && transactionPromiseFactory === db._transPromiseFactory) {\n table.mapToClass(SyncNode);\n }\n return table;\n };\n });\n\n // changes event on db:\n db.on.addEventType({\n changes: 'asap',\n cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master.\n message: 'asap'\n });\n\n //\n // Overide transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, function (origFunc) {\n return function (mode, storenames, dbschema, parent) {\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\n var addChanges = false;\n if (mode === 'readwrite' && storenames.some(function (storeName) {\n return dbschema[storeName] && dbschema[storeName].observable;\n })) {\n // At least one included store is a observable store. Make sure to also include the _changes store.\n addChanges = true;\n storenames = storenames.slice(0); // Clone\n if (storenames.indexOf(\"_changes\") === -1) storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\n }\n // Call original db._createTransaction()\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\n if (addChanges) {\n trans._lastWrittenRevision = 0;\n trans.on('complete', function () {\n if (trans._lastWrittenRevision) {\n // Changes were written in this transaction.\n if (!parent) {\n // This is root-level transaction, i.e. a physical commit has happened.\n // Delay-trigger a wakeup call:\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\n wakeupObservers.timeoutHandle = setTimeout(function () {\n delete wakeupObservers.timeoutHandle;\n wakeupObservers(trans._lastWrittenRevision);\n }, 25);\n } else {\n // This is just a virtual commit of a sub transaction.\n // Wait with waking up observers until root transaction has committed.\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\n var rootTransaction = function findRootTransaction(trans) {\n return trans.parent ? findRootTransaction(trans.parent) : trans;\n }(parent);\n rootTransaction._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rootTransaction.lastWrittenRevision || 0);\n }\n }\n });\n // Derive \"source\" property from parent transaction by default\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\n }\n return trans;\n };\n });\n\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\n // window with the same database name has been created already, this static property will already be set correctly.\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\n\n function wakeupObservers(lastWrittenRevision) {\n // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too.\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\n // Set the static property lastRevision[db.name] to the revision of the last written change.\n Observable.latestRevision[db.name] = lastWrittenRevision;\n // Wakeup ourselves, and any other db instances on this window:\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\n });\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\n // We need a storage event to wakeup other windwos.\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\n // the purpose to wakeup db instances in other windows.\n localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id.\n }\n }\n\n db.close = override(db.close, function (origClose) {\n return function () {\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\n // Teardown our framework.\n if (wakeupObservers.timeoutHandle) {\n clearTimeout(wakeupObservers.timeoutHandle);\n delete wakeupObservers.timeoutHandle;\n }\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\n Observable.on('intercomm').unsubscribe(onIntercomm);\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\n // Inform other db instances in same window that we are dying:\n if (mySyncNode && mySyncNode.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.id);\n // Inform other windows as well:\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything.\n mySyncNode.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n return origClose.apply(this, arguments);\n };\n });\n\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\n db.delete = override(db.delete, function (origDelete) {\n return function () {\n return origDelete.apply(this, arguments).then(function (result) {\n // Reset Observable.latestRevision[db.name]\n Observable.latestRevision[db.name] = 0;\n return result;\n });\n };\n });\n\n //\n // The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n //\n function crudMonitor(table) {\n /// \n var tableName = table.name;\n\n table.hook('creating').subscribe(function (primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = Observable.createUUID();\n if (table.schema.primKey.keyPath) {\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\n }\n }\n\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey === undefined ? null : primKey,\n type: CREATE,\n obj: obj\n };\n\n var promise = db._changes.add(change).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\n this.onsuccess = function (resultKey) {\n if (primKey != resultKey) promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n this.onerror = function (err) {\n // If the main operation fails, make sure to regret the change\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n\n return rv;\n });\n\n table.hook('updating').subscribe(function (mods, primKey, oldObj, trans) {\n /// \n // mods may contain property paths with undefined as value if the property\n // is being deleted. Since we cannot persist undefined we need to act\n // like those changes is setting the value to null instead.\n var modsWithoutUndefined = {};\n // As of current Dexie version (1.0.3) hook may be called even if it wouldnt really change.\n // Therefore we may do that kind of optimization here - to not add change entries if\n // there's nothing to change.\n var anythingChanged = false;\n var newObj = Dexie.deepClone(oldObj);\n for (var propPath in mods) {\n var mod = mods[propPath];\n if (typeof mod === 'undefined') {\n Dexie.delByKeyPath(newObj, propPath);\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\n anythingChanged = true;\n } else {\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\n Dexie.setByKeyPath(newObj, propPath, mod);\n modsWithoutUndefined[propPath] = mod;\n anythingChanged = true;\n }\n }\n }\n if (anythingChanged) {\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: UPDATE,\n mods: modsWithoutUndefined,\n oldObj: oldObj,\n obj: newObj\n };\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\n this.onsuccess = function () {\n promise._then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n });\n };\n this.onerror = function (err) {\n // If the main operation fails, make sure to regret the change.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n }\n });\n\n table.hook('deleting').subscribe(function (primKey, obj, trans) {\n /// \n var promise = db._changes.add({\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: DELETE,\n oldObj: obj\n }).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n // Using _then because if promise is already fullfilled, the standard then() would\n // do setTimeout() and we would loose the transaction.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n });\n }\n\n // When db opens, make sure to start monitor any changes before other db operations will start.\n db.on(\"ready\", function startObserving() {\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\n return db.table(\"_changes\").orderBy(\"rev\").last(function (lastChange) {\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\n // Therefore we know that the retrieved value will be This query will\n var latestRevision = lastChange ? lastChange.rev : 0;\n mySyncNode = new SyncNode({\n myRevision: latestRevision,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null,\n isMaster: 0\n });\n if (Observable.latestRevision[db.name] < latestRevision) {\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\n // There are other db instances in same window that hasnt yet been informed about a new revision\n Observable.latestRevision[db.name] = latestRevision;\n Dexie.ignoreTransaction(function () {\n Observable.on.latestRevisionIncremented.fire(latestRevision);\n });\n }\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\n return db.transaction('rw', '_syncNodes', function () {\n db._syncNodes.where('isMaster').equals(1).count(function (anyMasterNode) {\n if (!anyMasterNode) {\n // There's no master node. Let's take that role then.\n mySyncNode.isMaster = 1;\n }\n // Add our node to DB and start subscribing to events\n db._syncNodes.add(mySyncNode).then(function () {\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\n Observable.on('beforeunload', onBeforeUnload);\n Observable.on('suicideNurseCall', onSuicide);\n Observable.on('intercomm', onIntercomm);\n // Start polling for changes and do cleanups:\n pollHandle = setTimeout(poll, LOCAL_POLL);\n });\n });\n }).then(function () {\n cleanup();\n });\n //cleanup();\n //});\n });\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\n\n var handledRevision = 0;\n\n function onLatestRevisionIncremented(dbname, latestRevision) {\n if (dbname === db.name) {\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\n handledRevision = latestRevision;\n Dexie.vip(function () {\n readChanges(latestRevision).catch('DatabaseClosedError', function (e) {\n // Handle database closed error gracefully while reading changes.\n // Don't trigger unhandledrejection\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n });\n });\n }\n }\n\n function readChanges(latestRevision, recursion, wasPartial) {\n // Whenever changes are read, fire db.on(\"changes\") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is\n // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario\n // should be handled in case database is totally empty we should fail if sync is not available)\n if (!recursion && readChanges.ongoingOperation) {\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\n // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges().\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\n return readChanges.ongoingOperation;\n }\n\n var partial = false;\n var ourSyncNode = mySyncNode; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened.\n if (!ourSyncNode) {\n return Promise.reject(\"Database closed\");\n }\n var LIMIT = 1000;\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\n if (changes.length > 0) {\n var lastChange = changes[changes.length - 1];\n partial = changes.length === LIMIT;\n db.on('changes').fire(changes, partial);\n ourSyncNode.myRevision = lastChange.rev;\n } else if (wasPartial) {\n // No more changes, BUT since we have triggered on('changes') with partial = true,\n // we HAVE TO trigger changes again with empty list and partial = false\n db.on('changes').fire([], false);\n }\n\n return db.table(\"_syncNodes\").update(ourSyncNode, {\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null, // Reset \"deleteTimeStamp\" flag if it was there.\n myRevision: ourSyncNode.myRevision\n });\n }).then(function (nodeWasUpdated) {\n if (!nodeWasUpdated) {\n // My node has been deleted. We must have been lazy and got removed by another node.\n if (browserIsShuttingDown) {\n throw new Error(\"Browser is shutting down\");\n } else {\n db.close();\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\n if (global.location) global.location.reload(true);\n throw new Error(\"Out of sync\"); // Will make current promise reject\n }\n }\n\n // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not\n // resolve until all changes have been read.\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\n // In either case, call readChanges() again until we're done.\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\n }\n }).finally(function () {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.id;\n Dexie.vip(function () {\n // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages).catch('DatabaseClosedError', function (e) {\n // Handle database closed error gracefully while reading changes.\n // Don't signal 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n }).finally(function () {\n // Poll again in given interval:\n if (mySyncNode && mySyncNode.id === currentInstance) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n function cleanup() {\n var ourSyncNode = mySyncNode;\n if (!ourSyncNode) return Promise.reject(\"Database closed\");\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function () {\n // Cleanup dead local nodes that has no heartbeat for over a minute\n // Dont do the following:\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\n // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead.\n var weBecameMaster = false;\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) {\n return node.type === 'local';\n }).modify(function (node) {\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\n // Delete the node.\n delete this.value;\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n // Check if we are deleting a master node\n if (node.isMaster) {\n // The node we are deleting is master. We must take over that role.\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\n weBecameMaster = true;\n }\n // Cleanup intercomm messages destinated to the node being deleted:\n db._intercomm.where(\"destinationNode\").equals(node.id).modify(function (msg) {\n // OK to call intercomm. No need to call Dexie.vip() because intercomm is opened in existing transaction!\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\n if (msg.wantReply) {\n // Message wants a reply, meaning someone must take over its messages when it dies. Let us be that one!\n Dexie.ignoreTransaction(function () {\n consumeMessage(msg);\n });\n }\n });\n } else if (!node.deleteTimeStamp) {\n // Mark the node for deletion\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\n }\n }).then(function () {\n // Cleanup old revisions that no node is interested of.\n Observable.deleteOldChanges(db);\n return db.on(\"cleanup\").fire(weBecameMaster);\n });\n });\n }\n\n function onBeforeUnload(event) {\n // Mark our own sync node for deletion.\n if (!mySyncNode) return;\n browserIsShuttingDown = true;\n mySyncNode.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode); // This async operation may be cancelled since the browser is closing down now.\n Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff...\n // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below:\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below.\n }\n\n function onSuicide(dbname, nodeID) {\n if (dbname === db.name && !Observable.wereTheOneDying) {\n // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies.\n // It's own call to put() may have been cancelled.\n // Note also that in IE, this event may be called twice, but that doesnt harm!\n Dexie.vip(function () {\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\n });\n }\n }\n\n //\n // Intercommunication between nodes\n //\n // Enable inter-process communication between browser windows\n\n var requestsWaitingForReply = {};\n\n db.sendMessage = function (type, message, destinationNode, options) {\n /// Type of message\n /// Message to send\n /// ID of destination node\n /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n if (!mySyncNode) return Promise.reject(\"Database closed\");\n options = options || {};\n var msg = { message: message, destinationNode: destinationNode, sender: mySyncNode.id, type: type };\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n var tables = [\"_intercomm\"];\n if (options.wantReply) tables.push(\"_syncNodes\"); // If caller wants a reply, include \"_syncNodes\" in transaction to check that there's a reciever there. Otherwise, new master will get it.\n return db.transaction('rw?', tables, function () {\n if (options.wantReply) {\n // Check that there is a reciever there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(function (recieverAlive) {\n if (recieverAlive) return addMessage(msg);else return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return addMessage(msg);\n });\n });\n } else {\n addMessage(msg); // No need to return Promise. Caller dont need a reply.\n }\n\n function addMessage(msg) {\n return db._intercomm.add(msg).then(function (messageId) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n Dexie.ignoreTransaction(function () {\n Observable.on.intercomm.fire(db.name);\n });\n if (options.wantReply) {\n return new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = { resolve: resolve, reject: reject };\n });\n }\n });\n }\n });\n };\n\n db.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode) return Promise.reject(\"Database closed\");\n var mySyncNodeId = mySyncNode.id;\n db._syncNodes.each(function (node) {\n if (node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId)) {\n db.sendMessage(type, message, node.id);\n }\n });\n };\n\n db.observable = {};\n db.observable.SyncNode = SyncNode;\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode) return Promise.reject(\"Database closed\");\n return db.table('_intercomm').where(\"destinationNode\").equals(mySyncNode.id).modify(function (msg) {\n // For each message, fire the event and remove message.\n delete this.value;\n Dexie.ignoreTransaction(function () {\n consumeMessage(msg);\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill it's promise.\n var request = requestsWaitingForReply[msg.requestId.toString()];\n if (request) {\n if (msg.isFailure) {\n request.reject(msg.message.error);\n } else {\n request.resolve(msg.message.result);\n }\n delete requestsWaitingForReply[msg.requestId.toString()];\n }\n } else {\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\n msg.resolve = function (result) {\n db.sendMessage('response', { result: result }, msg.sender, { requestId: msg.id });\n };\n msg.reject = function (error) {\n db.sendMessage('response', { error: error.toString() }, msg.sender, { isFailure: true, requestId: msg.id });\n };\n var message = msg.message;\n delete msg.message;\n Dexie.extend(msg, message);\n db.on.message.fire(msg);\n }\n }\n\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages();\n }\n }\n}\n\n//\n// Help functions\n//\n\nfunction nop() {};\n\nfunction promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n args = arguments;\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\n//\n// Static properties and methods\n// \n\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\nObservable.createUUID = function () {\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n var d = Date.now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : r & 0x7 | 0x8).toString(16);\n });\n return uuid;\n};\n\nObservable.deleteOldChanges = function (db) {\n db._syncNodes.orderBy(\"myRevision\").first(function (oldestNode) {\n var timeout = Date.now() + 300,\n timedout = false;\n db._changes.where(\"rev\").below(oldestNode.myRevision).until(function () {\n return timedout = Date.now() > timeout;\n }).delete().then(function () {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (timedout) setTimeout(function () {\n Observable.deleteOldChanges(db);\n }, 10);\n });\n });\n};\n\nObservable._onStorage = function onStorage(event) {\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) {\n // For example \"Dexie.Observable/latestRevision/FriendsDB\"\n var parts = event.key.split('/');\n var prop = parts[1];\n var dbname = parts[2];\n if (prop === 'latestRevision') {\n var rev = parseInt(event.newValue, 10);\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\n Observable.latestRevision[dbname] = rev;\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\n });\n }\n } else if (prop.indexOf(\"deadnode:\") === 0) {\n var nodeID = parseInt(prop.split(':')[1], 10);\n if (event.newValue) {\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\n }\n } else if (prop === 'intercomm') {\n if (event.newValue) {\n Observable.on.intercomm.fire(dbname);\n }\n }\n }\n};\n\nObservable._onBeforeUnload = function () {\n Observable.on.beforeunload.fire();\n};\n\nObservable.localStorageImpl = global.localStorage;\n\n//\n// Map window events to static events in Dexie.Observable:\n//\nif (global.addEventListener) {\n global.addEventListener(\"storage\", Observable._onStorage);\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\n}\n// Register addon:\nDexie.Observable = Observable;\nDexie.addons.push(Observable);"]} \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/README.md b/addons/Dexie.Syncable/dist/README.md deleted file mode 100644 index 38706a48d..000000000 --- a/addons/Dexie.Syncable/dist/README.md +++ /dev/null @@ -1,37 +0,0 @@ -## Can't find dexie-syncable.js? -Transpiled code (dist version) IS ONLY checked in to -the [releases](https://github.com/dfahlander/Dexie.js/tree/releases/addons/Dexie.Syncable/dist). -branch. - -## Download -[unpkg.com/dexie-syncable/dist/dexie-syncable.js](https://unpkg.com/dexie-syncable/dist/dexie-syncable.js) - -[unpkg.com/dexie-syncable/dist/dexie-syncable.min.js](https://unpkg.com/dexie-syncable/dist/dexie-syncable.min.js) - -[unpkg.com/dexie-syncable/dist/dexie-syncable.js.map](https://unpkg.com/dexie-syncable/dist/dexie-syncable.js.map) - -[unpkg.com/dexie-syncable/dist/dexie-syncable.min.js.map](https://unpkg.com/dexie-syncable/dist/dexie-syncable.min.js.map) - -## npm -``` -npm install dexie-syncable --save -``` -## bower -Since Dexie v1.3.4, addons are included in the dexie bower package. -``` -$ bower install dexie --save -$ ls bower_components/dexie/addons/Dexie.Syncable/dist -dexie-syncable.js dexie-syncable.js.map dexie-syncable.min.js dexie-syncable.min.js.map - -``` -## Or build them yourself... -Fork Dexie.js, then: -``` -git clone https://github.com/YOUR-USERNAME/Dexie.js.git -cd Dexie.js -npm install -cd addons/Dexie.Syncable -npm run build # or npm run watch - -``` -If you're on windows, you need to use an elevated command prompt of some reason to get `npm install` to work. diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.js b/addons/Dexie.Syncable/dist/dexie-syncable.js new file mode 100644 index 000000000..d40b9b4c1 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js @@ -0,0 +1,1028 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('dexie'), require('dexie-observable')) : + typeof define === 'function' && define.amd ? define(['dexie', 'dexie-observable'], factory) : + (global.Dexie = global.Dexie || {}, global.Dexie.Syncable = factory(global.Dexie,global.dexieObservable)); +}(this, (function (Dexie,dexieObservable) { 'use strict'; + +Dexie = 'default' in Dexie ? Dexie['default'] : Dexie; + +/// +/// +/// +/** + * Dexie.Syncable.js + * =================== + * Dexie addon for syncing indexedDB with remote endpoints. + * + * version: 0.1.9 Alpha, Thu Oct 13 2016 + * + * Disclaimber: This addon is in alpha status meaning that + * its API and behavior may change. + * + */ + +// Depend on 'dexie-observable' +// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as "Dexie.Observable". +// That way, our plugin works in all UMD cases. +// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from "dexie-observable"'. +var override = Dexie.override; +var Promise = Dexie.Promise; +var setByKeyPath = Dexie.setByKeyPath; +var Observable = Dexie.Observable; + +function Syncable(db) { + /// + + var activePeers = []; + + // Change Types + var CREATE = 1, + UPDATE = 2, + DELETE = 3; + + // Statuses + var Statuses = Syncable.Statuses; + + var MAX_CHANGES_PER_CHUNK = 1000; + + db.on('message', function (msg) { + // Message from other local node arrives... + Dexie.vip(function () { + if (msg.type === 'connect') { + // We are master node and another non-master node wants us to do the connect. + db.syncable.connect(msg.protocolName, msg.url, msg.options).then(msg.resolve, msg.reject); + } else if (msg.type === 'disconnect') { + db.syncable.disconnect(msg.url).then(msg.resolve, msg.reject); + } else if (msg.type === 'syncStatusChanged') { + // We are client and a master node informs us about syncStatus change. + // Lookup the connectedProvider and call its event + db.syncable.on.statusChanged.fire(msg.newStatus, msg.url); + } + }); + }); + + db.on('cleanup', function (weBecameMaster) { + // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master. + if (weBecameMaster) { + // We took over the master role in Observable's cleanup method + db._syncNodes.where('type').equals('remote').and(function (node) { + return node.status !== Statuses.OFFLINE && node.status !== Statuses.ERROR; + }).each(function (connectedRemoteNode) { + // There are connected remote nodes that we must take over + // Since we may be in the on(ready) event, we must get VIPed to continue + Dexie.ignoreTransaction(function () { + Dexie.vip(function () { + db.syncable.connect(connectedRemoteNode.syncProtocol, connectedRemoteNode.url, connectedRemoteNode.syncOptions); + }); + }); + }); + } + }); + + db.on('ready', function onReady() { + // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state. + if (db._localSyncNode && db._localSyncNode.isMaster) { + // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!) + return db._syncNodes.where('type').equals('remote').and(function (node) { + return node.status !== Statuses.OFFLINE && node.status !== Statuses.ERROR; + }).toArray(function (connectedRemoteNodes) { + // There are connected remote nodes that we must take over + if (connectedRemoteNodes.length > 0) { + return Promise.all(connectedRemoteNodes.map(function (node) { + return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(function (err) { + return undefined; // If a node fails to connect, don't make db.open() reject. Accept it! + }); + })); + } + }); + } + }, true); // True means the ready event will survive a db reopen - db.close()/db.open() + + + db.syncable = {}; + + db.syncable.getStatus = function (url, cb) { + if (db.isOpen()) { + return Dexie.vip(function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node ? node.status : Statuses.OFFLINE; + }); + }).then(cb); + } else { + return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb); + } + }; + + db.syncable.list = function () { + return db._syncNodes.where('type').equals('remote').toArray(function (a) { + return a.map(function (node) { + return node.url; + }); + }); + }; + + db.syncable.on = Dexie.Events(db, { statusChanged: "asap" }); + + db.syncable.disconnect = function (url) { + if (db._localSyncNode && db._localSyncNode.isMaster) { + activePeers.filter(function (peer) { + return peer.url === url; + }).forEach(function (peer) { + peer.disconnect(Statuses.OFFLINE); + }); + } else { + db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + db.sendMessage('disconnect', { url: url }, masterNode.id, { wantReply: true }); + }); + } + + return db._syncNodes.where("url").equals(url).modify(function (node) { + node.status = Statuses.OFFLINE; + }); + }; + + db.syncable.connect = function (protocolName, url, options) { + options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined. + var protocolInstance = Syncable.registeredProtocols[protocolName]; + + if (protocolInstance) { + if (db.isOpen() && db._localSyncNode) { + // Database is open + if (db._localSyncNode.isMaster) { + // We are master node + return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id); + } else { + // We are not master node + // Request master node to do the connect: + db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) { + // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves. + return db.sendMessage('connect', { protocolName: protocolName, url: url, options: options }, masterNode.id, { wantReply: true }); + }); + return Promise.resolve(); + } + } else { + // Database not yet open + // Wait for it to open + return new Promise(function (resolve, reject) { + db.on("ready", function syncWhenReady() { + return Dexie.vip(function () { + return db.syncable.connect(protocolName, url, options).then(resolve).catch(function (err) { + // Reject the promise returned to the caller of db.syncable.connect(): + reject(err); + // but resolve the promise that db.on("ready") waits for, because database should succeed to open even if the connect operation fails! + }); + }); + }); + }); + } + } else { + throw new Error("ISyncProtocol '" + protocolName + "' is not registered in Dexie.Syncable.registerSyncProtocol()"); + return new Promise(); // For code completion + } + }; + + db.syncable.delete = function (url) { + // Notice: Caller should call db.syncable.disconnect(url) and wait for it to finish before calling db.syncable.delete(url) + // Surround with a readwrite-transaction + return db.transaction('rw', db._syncNodes, db._changes, db._uncommittedChanges, function () { + // Find the node + db._syncNodes.where("url").equals(url).toArray(function (nodes) { + // If it's found (or even several found, as detected by @martindiphoorn), + // let's delete it (or them) and cleanup _changes and _uncommittedChanges + // accordingly. + if (nodes.length > 0) { + var nodeIDs = nodes.map(function (node) { + return node.id; + }); + // The following 'return' statement is not needed right now, but I leave it + // there because if we would like to add a 'then()' statement to the main , + // operation above ( db._syncNodes.where("url").equals(url).toArray(...) ) , + // this return statement will asure that the whole chain is waited for + // before entering the then() callback. + return db._syncNodes.where('id').anyOf(nodeIDs).delete().then(function () { + // When theese nodes are gone, let's clear the _changes table + // from all revisions older than the oldest node. + // Delete all changes older than revision of oldest node: + Observable.deleteOldChanges(); + // Also don't forget to delete all uncommittedChanges for the deleted node: + return db._uncommittedChanges.where('node').anyOf(nodeIDs).delete(); + }); + } + }); + }); + }; + + db.syncable.unsyncedChanges = function (url) { + return db._syncNodes.where("url").equals(url).first(function (node) { + return db._changes.where('rev').above(node.myRevision).toArray(); + }); + }; + + function connect(protocolInstance, protocolName, url, options, dbAliveID) { + /// + var existingPeer = activePeers.filter(function (peer) { + return peer.url === url; + }); + if (existingPeer.length > 0) { + // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that + // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly. + return existingPeer[0].connectPromise; + } + + var connectPromise = getOrCreateSyncNode(options).then(function (node) { + return connectProtocol(node); + }); + + var rejectConnectPromise = null; + var disconnected = false; + var hasMoreToGive = true; + var activePeer = { + url: url, + status: Statuses.OFFLINE, + connectPromise: connectPromise, + on: Dexie.Events(null, "disconnect"), + disconnect: function (newStatus, error) { + if (!disconnected) { + activePeer.on.disconnect.fire(newStatus, error); + var pos = activePeers.indexOf(activePeer); + if (pos >= 0) activePeers.splice(pos, 1); + if (error && rejectConnectPromise) rejectConnectPromise(error); + } + disconnected = true; + } + }; + activePeers.push(activePeer); + + return connectPromise; + + function stillAlive() { + // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead + // because the new instance should be considered a fresh instance and will have another local node. + return db._localSyncNode && db._localSyncNode.id === dbAliveID; + } + + function getOrCreateSyncNode(options) { + return db.transaction('rw', db._syncNodes, function () { + if (!url) throw new Error("Url cannot be empty"); + // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise. + + + return db._syncNodes.where("url").equalsIgnoreCase(url).first(function (node) { + // + // PersistedContext : IPersistedContext + // + function PersistedContext(nodeID, otherProps) { + this.nodeID = nodeID; + if (otherProps) Dexie.extend(this, otherProps); + } + + PersistedContext.prototype.save = function () { + // Store this instance in the syncContext property of the node it belongs to. + return Dexie.vip(function () { + return node.save(); + }); + }; + + if (node) { + // Node already there. Make syncContext become an instance of PersistedContext: + node.syncContext = new PersistedContext(node.id, node.syncContext); + node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen... + db._syncNodes.put(node); + } else { + // Create new node and sync everything + node = new db.observable.SyncNode(); + node.myRevision = -1; + node.appliedRemoteRevision = null; + node.remoteBaseRevisions = []; + node.type = "remote"; + node.syncProtocol = protocolName; + node.url = url; + node.syncOptions = options; + node.lastHeartBeat = Date.now(); + node.dbUploadState = null; + Promise.resolve(function () { + // If options.initialUpload is explicitely false, set myRevision to currentRevision. + if (options.initialUpload === false) return db._changes.lastKey(function (currentRevision) { + node.myRevision = currentRevision; + }); + }).then(function () { + db._syncNodes.add(node).then(function (nodeId) { + node.syncContext = new PersistedContext(nodeId); // Update syncContext in db with correct nodeId. + db._syncNodes.put(node); + }); + }); + } + + return node; // returning node will make the db.transaction()-promise resolve with this value. + }); + }); + } + + function connectProtocol(node) { + /// + + function changeStatusTo(newStatus) { + if (node.status !== newStatus) { + node.status = newStatus; + node.save(); + db.syncable.on.statusChanged.fire(newStatus, url); + // Also broadcast message to other nodes about the status + db.broadcastMessage("syncStatusChanged", { newStatus: newStatus, url: url }, false); + } + } + + activePeer.on('disconnect', function (newStatus) { + if (!isNaN(newStatus)) changeStatusTo(newStatus); + }); + + var connectedContinuation; + changeStatusTo(Statuses.CONNECTING); + return doSync(); + + function doSync() { + // Use enque() to ensure only a single promise execution at a time. + return enque(doSync, function () { + // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence. + return getLocalChangesForNode_autoAckIfEmpty(node, function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess(). + // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants. + var finalSyncPromise = new Promise(function (resolve, reject) { + rejectConnectPromise = function (err) { + reject(err); + }; + Dexie.asap(function () { + try { + protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, function (continuation) { + resolve(continuation); + }, onError); + } catch (ex) { + onError(ex, Infinity); + } + + function onError(error, again) { + reject(error); + if (stillAlive()) { + if (!isNaN(again) && again < Infinity) { + setTimeout(function () { + if (stillAlive()) { + changeStatusTo(Statuses.SYNCING); + doSync(); + } + }, again); + changeStatusTo(Statuses.ERROR_WILL_RETRY, error); + if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect(); + connectedContinuation = null; + } else { + abortTheProvider(error); // Will fire ERROR on statusChanged event. + } + } + } + }); + }); + + return finalSyncPromise.then(function () { + // Resolve caller of db.syncable.connect() with undefined. Not with continuation! + }); + + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save(); + // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately, + // otherwise it will execute when finalSyncPromise resolves. + finalSyncPromise.then(continueSendingChanges); + } + }); + }, dbAliveID); + } + + function abortTheProvider(error) { + activePeer.disconnect(Statuses.ERROR, error); + } + + function getBaseRevisionAndMaxClientRevision(node) { + /// + if (node.remoteBaseRevisions.length === 0) return { + // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision: + maxClientRevision: Infinity, + remoteBaseRevision: null + }; + for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) { + if (node.myRevision >= node.remoteBaseRevisions[i].local) { + // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on. + return { + maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local, + remoteBaseRevision: node.remoteBaseRevisions[i].remote + }; + } + } + // There are at least one item in the list but the server hasnt yet become up-to-date with the 0 revision from client. + return { + maxClientRevision: node.remoteBaseRevisions[0].local, + remoteBaseRevision: null + }; + } + + function getLocalChangesForNode_autoAckIfEmpty(node, cb) { + return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save(); + return getLocalChangesForNode(node, autoAck); + } else { + return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck); + } + }); + } + + function getLocalChangesForNode(node, cb) { + /// + /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes + /// for that node. + /// + /// + /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result. + + if (node.myRevision >= 0) { + // Node is based on a revision in our local database and will just need to get the changes that has occurred since that revision. + var brmcr = getBaseRevisionAndMaxClientRevision(node); + return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) { + return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck); + }); + } else { + // Node hasn't got anything from our local database yet. We will need to upload entire DB to the node in the form of CREATE changes. + // Check if we're in the middle of already doing that: + if (node.dbUploadState === null) { + // Initiatalize dbUploadState + var tablesToUpload = db.tables.filter(function (table) { + return table.schema.observable; + }).map(function (table) { + return table.name; + }); + if (tablesToUpload.length === 0) return Promise.resolve(cb([], null, false, {})); // There are no synched tables at all. + var dbUploadState = { + tablesToUpload: tablesToUpload, + currentTable: tablesToUpload.shift(), + currentKey: null + }; + return db._changes.orderBy('rev').last(function (lastChange) { + dbUploadState.localBaseRevision = lastChange && lastChange.rev || 0; + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(dbUploadState, [], collection); + }); + } else if (node.dbUploadState.currentKey) { + var collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey); + return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection); + } else { + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection); + } + } + + function getTableObjectsAsChanges(state, changes, collection) { + /// + /// + /// + var limitReached = false; + return collection.until(function () { + if (changes.length === MAX_CHANGES_PER_CHUNK) { + limitReached = true; + return true; + } + }).each(function (item, cursor) { + changes.push({ + type: CREATE, + table: state.currentTable, + key: cursor.key, + obj: cursor.value + }); + state.currentKey = cursor.key; + }).then(function () { + if (limitReached) { + // Limit reached. Send partial result. + hasMoreToGive = true; + return cb(changes, null, true, { dbUploadState: state }); + } else { + // Done iterating this table. Check if there are more tables to go through: + if (state.tablesToUpload.length === 0) { + // Done iterating all tables + // Now append changes occurred during our dbUpload: + var brmcr = getBaseRevisionAndMaxClientRevision(node); + return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) { + changes = changes.concat(additionalChanges); + nodeModificationsOnAck.dbUploadState = null; + return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck); + }); + } else { + // Not done iterating all tables. Continue on next table: + state.currentTable = state.tablesToUpload.shift(); + return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id')); + } + } + }); + } + + function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) { + /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result. + var changeSet = {}; + var numChanges = 0; + var partial = false; + var ignoreSource = node.id; + var nextRevision = revision; + return db.transaction('r', db._changes, function () { + var query = maxRevision === Infinity ? db._changes.where('rev').above(revision) : db._changes.where('rev').between(revision, maxRevision, false, true); + query.until(function () { + if (numChanges === maxChanges) { + partial = true; + return true; + } + }).each(function (change) { + // Note the revision in nextRevision: + nextRevision = change.rev; + if (change.source === ignoreSource) return; + // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the nescessary info: + var changeToSend = { + type: change.type, + table: change.table, + key: change.key + }; + if (change.type === CREATE) changeToSend.obj = change.obj;else if (change.type === UPDATE) changeToSend.mods = change.mods; + + var id = change.table + ":" + change.key; + var prevChange = changeSet[id]; + if (!prevChange) { + // This is the first change on this key. Add it unless it comes from the source that we are working against + changeSet[id] = changeToSend; + ++numChanges; + } else { + // Merge the oldchange with the new change + var nextChange = changeToSend; + var mergedChange = function () { + switch (prevChange.type) { + case CREATE: + switch (nextChange.type) { + case CREATE: + return nextChange; // Another CREATE replaces previous CREATE. + case UPDATE: + return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj + case DELETE: + return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm! + } + break; + case UPDATE: + switch (nextChange.type) { + case CREATE: + return nextChange; // Another CREATE replaces previous update. + case UPDATE: + return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set. + case DELETE: + return nextChange; // Only send the delete change. What was updated earlier is no longer of interest. + } + break; + case DELETE: + switch (nextChange.type) { + case CREATE: + return nextChange; // A resurection occurred. Only create change is of interest. + case UPDATE: + return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there. + case DELETE: + return prevChange; // Still a delete change. Leave as is. + } + break; + } + }(); + changeSet[id] = mergedChange; + } + }); + }).then(function () { + var changes = Object.keys(changeSet).map(function (key) { + return changeSet[key]; + }); + hasMoreToGive = partial; + return cb(changes, partial, { myRevision: nextRevision }); + }); + } + } + + function applyRemoteChanges(remoteChanges, remoteRevision, partial, clear) { + return enque(applyRemoteChanges, function () { + if (!stillAlive()) return Promise.reject("Database not open"); + // FIXTHIS: Check what to do if clear() is true! + return (partial ? saveToUncommitedChanges(remoteChanges) : finallyCommitAllChanges(remoteChanges, remoteRevision)).catch(function (error) { + abortTheProvider(error); + return Promise.reject(error); + }); + }, dbAliveID); + + function saveToUncommitedChanges(changes) { + return db.transaction('rw', db._uncommittedChanges, function () { + changes.forEach(function (change) { + var changeToAdd = { + node: node.id, + type: change.type, + table: change.table, + key: change.key + }; + if (change.obj) changeToAdd.obj = change.obj; + if (change.mods) changeToAdd.mods = change.mods; + db._uncommittedChanges.add(changeToAdd); + }); + }).then(function () { + node.appliedRemoteRevision = remoteRevision; + node.save(); + }); + } + + function finallyCommitAllChanges(changes, remoteRevision) { + //alert("finallyCommitAllChanges() will now start its job."); + //var tick = Date.now(); + + // 1. Open a write transaction on all tables in DB + return db.transaction('rw', db.tables.filter(function (table) { + return table.name === '_changes' || table.name === '_uncommittedChanges' || table.schema.observable; + }), function () { + var trans = Dexie.currentTransaction; + var localRevisionBeforeChanges = 0; + db._changes.orderBy('rev').last(function (lastChange) { + // Store what revision we were at before committing the changes + localRevisionBeforeChanges = lastChange && lastChange.rev || 0; + }).then(function () { + // Specify the source. Important for the change consumer to ignore changes originated from self! + trans.source = node.id; + // 2. Apply uncommitted changes and delete each uncommitted change + return db._uncommittedChanges.where('node').equals(node.id).toArray(); + }).then(function (uncommittedChanges) { + return applyChanges(uncommittedChanges, 0); + }).then(function () { + return db._uncommittedChanges.where('node').equals(node.id).delete(); + }).then(function () { + // 3. Apply last chunk of changes + return applyChanges(changes, 0); + }).then(function () { + // Get what revision we are at now: + return db._changes.orderBy('rev').last(); + }).then(function (lastChange) { + var currentLocalRevision = lastChange && lastChange.rev || 0; + // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision) + node.appliedRemoteRevision = remoteRevision; + node.remoteBaseRevisions.push({ remote: remoteRevision, local: currentLocalRevision }); + if (node.myRevision === localRevisionBeforeChanges) { + // If server was up-to-date before we added new changes from the server, update myRevision to last change + // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from + // ever sending an empty change list to server, which would otherwise be done every second time it would send changes. + node.myRevision = currentLocalRevision; + } + // Garbage collect remoteBaseRevisions not in use anymore: + if (node.remoteBaseRevisions.length > 1) { + for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) { + if (node.myRevision >= node.remoteBaseRevisions[i].local) { + node.remoteBaseRevisions.splice(0, i); + break; + } + } + } + node.save(); // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction. + //var tock = Date.now(); + //alert("finallyCommitAllChanges() has done its job. " + changes.length + " changes applied in " + ((tock - tick) / 1000) + "seconds"); + }); + + function applyChanges(changes, offset) { + /// + /// + var lastChangeType = 0; + var lastCreatePromise = null; + if (offset >= changes.length) return Promise.resolve(null); + var change = changes[offset]; + var table = db.table(change.table); + while (change && change.type === CREATE) { + // Optimize CREATE changes because on initial sync with server, the entire DB will be downloaded in forms of CREATE changes. + // Instead of waiting for each change to resolve, do all CREATE changes in bulks until another type of change is stepped upon. + // This case is the only case that allows i to increment and the for-loop to continue since it does not return anything. + var specifyKey = !table.schema.primKey.keyPath; + lastCreatePromise = function (change, table, specifyKey) { + return (specifyKey ? table.add(change.obj, change.key) : table.add(change.obj)).catch("ConstraintError", function (e) { + return specifyKey ? table.put(change.obj, change.key) : table.put(change.obj); + }); + }(change, table, specifyKey); + change = changes[++offset]; + if (change) table = db.table(change.table); + } + + if (lastCreatePromise) { + // We did some CREATE changes but now stumbled upon another type of change. + // Let's wait for the last CREATE change to resolve and then call applyChanges again at current position. Next time, lastCreatePromise will be null and a case below will happen. + return lastCreatePromise.then(function () { + return offset < changes.length ? applyChanges(changes, offset) : null; + }); + } + + if (change) { + if (change.type === UPDATE) { + return table.update(change.key, change.mods).then(function () { + // Wait for update to resolve before taking next change. Why? Because it will lock transaction anyway since we are listening to CRUD events here. + return applyChanges(changes, offset + 1); + }); + } + + if (change.type === DELETE) { + return table.delete(change.key).then(function () { + // Wait for delete to resolve before taking next change. Why? Because it will lock transaction anyway since we are listening to CRUD events here. + return applyChanges(changes, offset + 1); + }); + } + } + + return Promise.resolve(null); // Will return null or a Promise and make the entire applyChanges promise finally resolve. + } + }); + } + } + + // + // + // Continuation Patterns Follows + // + // + + function continueSendingChanges(continuation) { + if (!stillAlive()) { + // Database was closed. + if (continuation.disconnect) continuation.disconnect(); + return; + } + + connectedContinuation = continuation; + activePeer.on('disconnect', function () { + if (connectedContinuation) { + if (connectedContinuation.react) { + try { + // react pattern must provide a disconnect function. + connectedContinuation.disconnect(); + } catch (e) {} + } + connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice. + } + }); + + if (continuation.react) { + continueUsingReactPattern(continuation); + } else { + continueUsingPollPattern(continuation); + } + } + + // React Pattern (eager) + function continueUsingReactPattern(continuation) { + var changesWaiting, // Boolean + isWaitingForServer; // Boolean + + + function onChanges() { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + if (isWaitingForServer) changesWaiting = true;else { + reactToChanges(); + } + } + } + + db.on('changes', onChanges); + + // Override disconnect() to also unsubscribe to onChanges. + activePeer.on('disconnect', function () { + db.on.changes.unsubscribe(onChanges); + }); + + function reactToChanges() { + if (!connectedContinuation) return; + changesWaiting = false; + isWaitingForServer = true; + getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + if (!connectedContinuation) return; + if (changes.length > 0) { + continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save(); + // More changes may be waiting: + reactToChanges(); + }); + } else { + isWaitingForServer = false; + if (changesWaiting) { + // A change jumped in between the time-spot of quering _changes and getting called back with zero changes. + // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory. + reactToChanges(); + } else { + changeStatusTo(Statuses.ONLINE); + } + } + }).catch(abortTheProvider); + } + + reactToChanges(); + } + + // Poll Pattern + function continueUsingPollPattern() { + + function syncAgain() { + getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + + protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError); + + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save(); + } + + function onSuccess(continuation) { + if (!connectedContinuation) { + // Got disconnected before succeeding. Quit. + return; + } + connectedContinuation = continuation; + if (partial) { + // We only sent partial changes. Need to do another round asap. + syncAgain(); + } else { + // We've sent all changes now (in sync!) + if (!isNaN(continuation.again) && continuation.again < Infinity) { + // Provider wants to keep polling. Set Status to ONLINE. + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, continuation.again); + } else { + // Provider seems finished polling. Since we are never going to poll again, + // disconnect provider and set status to OFFLINE until another call to db.syncable.connect(). + activePeer.disconnect(Statuses.OFFLINE); + } + } + } + + function onError(error, again) { + if (!isNaN(again) && again < Infinity) { + if (connectedContinuation) { + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, again); + changeStatusTo(Statuses.ERROR_WILL_RETRY); + } // else status is already changed since we got disconnected. + } else { + abortTheProvider(error); // Will fire ERROR on onStatusChanged. + } + } + }).catch(abortTheProvider); + } + + if (hasMoreToGive) { + syncAgain(); + } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) { + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, connectedContinuation.again); + } + } + } + } + + db.close = override(db.close, function (origClose) { + return function () { + activePeers.forEach(function (peer) { + peer.disconnect(); + }); + return origClose.apply(this, arguments); + }; + }); + + var syncNodeSaveQueContexts = {}; + db.observable.SyncNode.prototype.save = function () { + var self = this; + return db.transaction('rw?', db._syncNodes, function () { + db._syncNodes.put(self); + }); + }; + + function enque(context, fn, instanceID) { + function _enque() { + if (!context.ongoingOperation) { + context.ongoingOperation = Dexie.ignoreTransaction(function () { + return Dexie.vip(function () { + return fn(); + }); + }).then(function (res) { + delete context.ongoingOperation; + return res; + }); + } else { + context.ongoingOperation = context.ongoingOperation.then(function () { + return enque(context, fn, instanceID); + }); + } + return context.ongoingOperation; + } + + if (!instanceID) { + // Caller wants to enque it until database becomes open. + if (db.isOpen()) { + return _enque(); + } else { + return Promise.reject(new Error("Database was closed")); + } + } else if (db._localSyncNode && instanceID === db._localSyncNode.id) { + // DB is already open but queuer doesnt want it to be queued if database has been closed (request bound to current instance of DB) + return _enque(); + } else { + return Promise.reject(new Error("Database was closed")); + } + } + + function combineCreateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered. + Object.keys(nextChange.mods).forEach(function (keyPath) { + setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]); + }); + return clonedChange; + } + + function combineUpdateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered. + Object.keys(nextChange.mods).forEach(function (keyPath) { + // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath + var hadParentPath = false; + Object.keys(prevChange.mods).filter(function (parentPath) { + return keyPath.indexOf(parentPath + '.') === 0; + }).forEach(function (parentPath) { + setByKeyPath(clonedChange[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]); + hadParentPath = true; + }); + if (!hadParentPath) { + // Add or replace this keyPath and its new value + clonedChange.mods[keyPath] = nextChange.mods[keyPath]; + } + // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since + // we must mimic what would happen if applying the two changes after each other: + Object.keys(prevChange.mods).filter(function (subPath) { + return subPath.indexOf(keyPath + '.') === 0; + }).forEach(function (subPath) { + delete clonedChange[subPath]; + }); + }); + return clonedChange; + } +} + +Syncable.Statuses = { + ERROR: -1, // An irrepairable error occurred and the sync provider is dead. + OFFLINE: 0, // The sync provider hasnt yet become online, or it has been disconnected. + CONNECTING: 1, // Trying to connect to server + ONLINE: 2, // Connected to server and currently in sync with server + SYNCING: 3, // Syncing with server. For poll pattern, this is every poll call. For react pattern, this is when local changes are being sent to server. + ERROR_WILL_RETRY: 4 // An error occured such as net down but the sync provider will retry to connect. +}; + +Syncable.StatusTexts = { + "-1": "ERROR", + "0": "OFFLINE", + "1": "CONNECTING", + "2": "ONLINE", + "3": "SYNCING", + "4": "ERROR_WILL_RETRY" +}; + +Syncable.registeredProtocols = {}; // Map when key is the provider name. + +Syncable.registerSyncProtocol = function (name, protocolInstance) { + /// + /// Register a syncronization protocol that can syncronize databases with remote servers. + /// + /// Provider name + /// Implementation of ISyncProtocol + Syncable.registeredProtocols[name] = protocolInstance; +}; + +// Register addon in Dexie: +Dexie.Syncable = Syncable; +Dexie.addons.push(Syncable); + +return Syncable; + +}))); +//# sourceMappingURL=dexie-syncable.js.map diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.js.map b/addons/Dexie.Syncable/dist/dexie-syncable.js.map new file mode 100644 index 000000000..ae32a2552 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-syncable.js","sources":["../tools/tmp/src/Dexie.Syncable.js"],"sourcesContent":["/// \n/// \n/// \n/**\r\n * Dexie.Syncable.js\r\n * ===================\r\n * Dexie addon for syncing indexedDB with remote endpoints.\r\n *\r\n * version: {version} Alpha, {date}\r\n *\r\n * Disclaimber: This addon is in alpha status meaning that\r\n * its API and behavior may change.\r\n *\r\n */\n\nimport Dexie from \"dexie\";\n// Depend on 'dexie-observable'\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\n// That way, our plugin works in all UMD cases.\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\nimport \"dexie-observable\";\n\nvar override = Dexie.override,\n Promise = Dexie.Promise,\n setByKeyPath = Dexie.setByKeyPath,\n Observable = Dexie.Observable;\n\nexport default function Syncable(db) {\n /// \n\n var activePeers = [];\n\n // Change Types\n var CREATE = 1,\n UPDATE = 2,\n DELETE = 3;\n\n // Statuses\n var Statuses = Syncable.Statuses;\n\n var MAX_CHANGES_PER_CHUNK = 1000;\n\n db.on('message', function (msg) {\n // Message from other local node arrives...\n Dexie.vip(function () {\n if (msg.type === 'connect') {\n // We are master node and another non-master node wants us to do the connect.\n db.syncable.connect(msg.protocolName, msg.url, msg.options).then(msg.resolve, msg.reject);\n } else if (msg.type === 'disconnect') {\n db.syncable.disconnect(msg.url).then(msg.resolve, msg.reject);\n } else if (msg.type === 'syncStatusChanged') {\n // We are client and a master node informs us about syncStatus change.\n // Lookup the connectedProvider and call its event\n db.syncable.on.statusChanged.fire(msg.newStatus, msg.url);\n }\n });\n });\n\n db.on('cleanup', function (weBecameMaster) {\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\n if (weBecameMaster) {\n // We took over the master role in Observable's cleanup method\n db._syncNodes.where('type').equals('remote').and(function (node) {\n return node.status !== Statuses.OFFLINE && node.status !== Statuses.ERROR;\n }).each(function (connectedRemoteNode) {\n // There are connected remote nodes that we must take over\n // Since we may be in the on(ready) event, we must get VIPed to continue\n Dexie.ignoreTransaction(function () {\n Dexie.vip(function () {\n db.syncable.connect(connectedRemoteNode.syncProtocol, connectedRemoteNode.url, connectedRemoteNode.syncOptions);\n });\n });\n });\n }\n });\n\n db.on('ready', function onReady() {\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\n return db._syncNodes.where('type').equals('remote').and(function (node) {\n return node.status !== Statuses.OFFLINE && node.status !== Statuses.ERROR;\n }).toArray(function (connectedRemoteNodes) {\n // There are connected remote nodes that we must take over\n if (connectedRemoteNodes.length > 0) {\n return Promise.all(connectedRemoteNodes.map(function (node) {\n return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(function (err) {\n return undefined; // If a node fails to connect, don't make db.open() reject. Accept it!\n });\n }));\n }\n });\n }\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\n\n\n db.syncable = {};\n\n db.syncable.getStatus = function (url, cb) {\n if (db.isOpen()) {\n return Dexie.vip(function () {\n return db._syncNodes.where('url').equals(url).first(function (node) {\n return node ? node.status : Statuses.OFFLINE;\n });\n }).then(cb);\n } else {\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\n }\n };\n\n db.syncable.list = function () {\n return db._syncNodes.where('type').equals('remote').toArray(function (a) {\n return a.map(function (node) {\n return node.url;\n });\n });\n };\n\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\n\n db.syncable.disconnect = function (url) {\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n activePeers.filter(function (peer) {\n return peer.url === url;\n }).forEach(function (peer) {\n peer.disconnect(Statuses.OFFLINE);\n });\n } else {\n db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n db.sendMessage('disconnect', { url: url }, masterNode.id, { wantReply: true });\n });\n }\n\n return db._syncNodes.where(\"url\").equals(url).modify(function (node) {\n node.status = Statuses.OFFLINE;\n });\n };\n\n db.syncable.connect = function (protocolName, url, options) {\n options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined.\n var protocolInstance = Syncable.registeredProtocols[protocolName];\n\n if (protocolInstance) {\n if (db.isOpen() && db._localSyncNode) {\n // Database is open\n if (db._localSyncNode.isMaster) {\n // We are master node\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\n } else {\n // We are not master node\n // Request master node to do the connect:\n db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\n // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves.\n return db.sendMessage('connect', { protocolName: protocolName, url: url, options: options }, masterNode.id, { wantReply: true });\n });\n return Promise.resolve();\n }\n } else {\n // Database not yet open\n // Wait for it to open\n return new Promise(function (resolve, reject) {\n db.on(\"ready\", function syncWhenReady() {\n return Dexie.vip(function () {\n return db.syncable.connect(protocolName, url, options).then(resolve).catch(function (err) {\n // Reject the promise returned to the caller of db.syncable.connect():\n reject(err);\n // but resolve the promise that db.on(\"ready\") waits for, because database should succeed to open even if the connect operation fails!\n });\n });\n });\n });\n }\n } else {\n throw new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\");\n return new Promise(); // For code completion\n }\n };\n\n db.syncable.delete = function (url) {\n // Notice: Caller should call db.syncable.disconnect(url) and wait for it to finish before calling db.syncable.delete(url)\n // Surround with a readwrite-transaction\n return db.transaction('rw', db._syncNodes, db._changes, db._uncommittedChanges, function () {\n // Find the node\n db._syncNodes.where(\"url\").equals(url).toArray(function (nodes) {\n // If it's found (or even several found, as detected by @martindiphoorn),\n // let's delete it (or them) and cleanup _changes and _uncommittedChanges\n // accordingly.\n if (nodes.length > 0) {\n var nodeIDs = nodes.map(function (node) {\n return node.id;\n });\n // The following 'return' statement is not needed right now, but I leave it \n // there because if we would like to add a 'then()' statement to the main ,\n // operation above ( db._syncNodes.where(\"url\").equals(url).toArray(...) ) , \n // this return statement will asure that the whole chain is waited for \n // before entering the then() callback.\n return db._syncNodes.where('id').anyOf(nodeIDs).delete().then(function () {\n // When theese nodes are gone, let's clear the _changes table\n // from all revisions older than the oldest node.\n // Delete all changes older than revision of oldest node:\n Observable.deleteOldChanges();\n // Also don't forget to delete all uncommittedChanges for the deleted node:\n return db._uncommittedChanges.where('node').anyOf(nodeIDs).delete();\n });\n }\n });\n });\n };\n\n db.syncable.unsyncedChanges = function (url) {\n return db._syncNodes.where(\"url\").equals(url).first(function (node) {\n return db._changes.where('rev').above(node.myRevision).toArray();\n });\n };\n\n function connect(protocolInstance, protocolName, url, options, dbAliveID) {\n /// \n var existingPeer = activePeers.filter(function (peer) {\n return peer.url === url;\n });\n if (existingPeer.length > 0) {\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\n // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly.\n return existingPeer[0].connectPromise;\n }\n\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\n return connectProtocol(node);\n });\n\n var rejectConnectPromise = null;\n var disconnected = false;\n var hasMoreToGive = true;\n var activePeer = {\n url: url,\n status: Statuses.OFFLINE,\n connectPromise: connectPromise,\n on: Dexie.Events(null, \"disconnect\"),\n disconnect: function (newStatus, error) {\n if (!disconnected) {\n activePeer.on.disconnect.fire(newStatus, error);\n var pos = activePeers.indexOf(activePeer);\n if (pos >= 0) activePeers.splice(pos, 1);\n if (error && rejectConnectPromise) rejectConnectPromise(error);\n }\n disconnected = true;\n }\n };\n activePeers.push(activePeer);\n\n return connectPromise;\n\n function stillAlive() {\n // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead\n // because the new instance should be considered a fresh instance and will have another local node.\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\n }\n\n function getOrCreateSyncNode(options) {\n return db.transaction('rw', db._syncNodes, function () {\n if (!url) throw new Error(\"Url cannot be empty\");\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\n\n\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\n //\n // PersistedContext : IPersistedContext\n //\n function PersistedContext(nodeID, otherProps) {\n this.nodeID = nodeID;\n if (otherProps) Dexie.extend(this, otherProps);\n }\n\n PersistedContext.prototype.save = function () {\n // Store this instance in the syncContext property of the node it belongs to.\n return Dexie.vip(function () {\n return node.save();\n });\n };\n\n if (node) {\n // Node already there. Make syncContext become an instance of PersistedContext:\n node.syncContext = new PersistedContext(node.id, node.syncContext);\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\n db._syncNodes.put(node);\n } else {\n // Create new node and sync everything\n node = new db.observable.SyncNode();\n node.myRevision = -1;\n node.appliedRemoteRevision = null;\n node.remoteBaseRevisions = [];\n node.type = \"remote\";\n node.syncProtocol = protocolName;\n node.url = url;\n node.syncOptions = options;\n node.lastHeartBeat = Date.now();\n node.dbUploadState = null;\n Promise.resolve(function () {\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\n if (options.initialUpload === false) return db._changes.lastKey(function (currentRevision) {\n node.myRevision = currentRevision;\n });\n }).then(function () {\n db._syncNodes.add(node).then(function (nodeId) {\n node.syncContext = new PersistedContext(nodeId); // Update syncContext in db with correct nodeId.\n db._syncNodes.put(node);\n });\n });\n }\n\n return node; // returning node will make the db.transaction()-promise resolve with this value.\n });\n });\n }\n\n function connectProtocol(node) {\n /// \n\n function changeStatusTo(newStatus) {\n if (node.status !== newStatus) {\n node.status = newStatus;\n node.save();\n db.syncable.on.statusChanged.fire(newStatus, url);\n // Also broadcast message to other nodes about the status\n db.broadcastMessage(\"syncStatusChanged\", { newStatus: newStatus, url: url }, false);\n }\n }\n\n activePeer.on('disconnect', function (newStatus) {\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\n });\n\n var connectedContinuation;\n changeStatusTo(Statuses.CONNECTING);\n return doSync();\n\n function doSync() {\n // Use enque() to ensure only a single promise execution at a time.\n return enque(doSync, function () {\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\n return getLocalChangesForNode_autoAckIfEmpty(node, function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\n var finalSyncPromise = new Promise(function (resolve, reject) {\n rejectConnectPromise = function (err) {\n reject(err);\n };\n Dexie.asap(function () {\n try {\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, function (continuation) {\n resolve(continuation);\n }, onError);\n } catch (ex) {\n onError(ex, Infinity);\n }\n\n function onError(error, again) {\n reject(error);\n if (stillAlive()) {\n if (!isNaN(again) && again < Infinity) {\n setTimeout(function () {\n if (stillAlive()) {\n changeStatusTo(Statuses.SYNCING);\n doSync();\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\n connectedContinuation = null;\n } else {\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\n }\n }\n }\n });\n });\n\n return finalSyncPromise.then(function () {\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\n });\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\n // otherwise it will execute when finalSyncPromise resolves.\n finalSyncPromise.then(continueSendingChanges);\n }\n });\n }, dbAliveID);\n }\n\n function abortTheProvider(error) {\n activePeer.disconnect(Statuses.ERROR, error);\n }\n\n function getBaseRevisionAndMaxClientRevision(node) {\n /// \n if (node.remoteBaseRevisions.length === 0) return {\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\n maxClientRevision: Infinity,\n remoteBaseRevision: null\n };\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\n return {\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\n };\n }\n }\n // There are at least one item in the list but the server hasnt yet become up-to-date with the 0 revision from client. \n return {\n maxClientRevision: node.remoteBaseRevisions[0].local,\n remoteBaseRevision: null\n };\n }\n\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n return getLocalChangesForNode(node, autoAck);\n } else {\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\n }\n });\n }\n\n function getLocalChangesForNode(node, cb) {\n /// \n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\n /// for that node.\n /// \n /// \n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n\n if (node.myRevision >= 0) {\n // Node is based on a revision in our local database and will just need to get the changes that has occurred since that revision.\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Node hasn't got anything from our local database yet. We will need to upload entire DB to the node in the form of CREATE changes.\n // Check if we're in the middle of already doing that:\n if (node.dbUploadState === null) {\n // Initiatalize dbUploadState\n var tablesToUpload = db.tables.filter(function (table) {\n return table.schema.observable;\n }).map(function (table) {\n return table.name;\n });\n if (tablesToUpload.length === 0) return Promise.resolve(cb([], null, false, {})); // There are no synched tables at all.\n var dbUploadState = {\n tablesToUpload: tablesToUpload,\n currentTable: tablesToUpload.shift(),\n currentKey: null\n };\n return db._changes.orderBy('rev').last(function (lastChange) {\n dbUploadState.localBaseRevision = lastChange && lastChange.rev || 0;\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(dbUploadState, [], collection);\n });\n } else if (node.dbUploadState.currentKey) {\n var collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n } else {\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n }\n }\n\n function getTableObjectsAsChanges(state, changes, collection) {\n /// \n /// \n /// \n var limitReached = false;\n return collection.until(function () {\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\n limitReached = true;\n return true;\n }\n }).each(function (item, cursor) {\n changes.push({\n type: CREATE,\n table: state.currentTable,\n key: cursor.key,\n obj: cursor.value\n });\n state.currentKey = cursor.key;\n }).then(function () {\n if (limitReached) {\n // Limit reached. Send partial result.\n hasMoreToGive = true;\n return cb(changes, null, true, { dbUploadState: state });\n } else {\n // Done iterating this table. Check if there are more tables to go through:\n if (state.tablesToUpload.length === 0) {\n // Done iterating all tables\n // Now append changes occurred during our dbUpload:\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\n changes = changes.concat(additionalChanges);\n nodeModificationsOnAck.dbUploadState = null;\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Not done iterating all tables. Continue on next table:\n state.currentTable = state.tablesToUpload.shift();\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\n }\n }\n });\n }\n\n function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n var changeSet = {};\n var numChanges = 0;\n var partial = false;\n var ignoreSource = node.id;\n var nextRevision = revision;\n return db.transaction('r', db._changes, function () {\n var query = maxRevision === Infinity ? db._changes.where('rev').above(revision) : db._changes.where('rev').between(revision, maxRevision, false, true);\n query.until(function () {\n if (numChanges === maxChanges) {\n partial = true;\n return true;\n }\n }).each(function (change) {\n // Note the revision in nextRevision:\n nextRevision = change.rev;\n if (change.source === ignoreSource) return;\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the nescessary info:\n var changeToSend = {\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.type === CREATE) changeToSend.obj = change.obj;else if (change.type === UPDATE) changeToSend.mods = change.mods;\n\n var id = change.table + \":\" + change.key;\n var prevChange = changeSet[id];\n if (!prevChange) {\n // This is the first change on this key. Add it unless it comes from the source that we are working against\n changeSet[id] = changeToSend;\n ++numChanges;\n } else {\n // Merge the oldchange with the new change\n var nextChange = changeToSend;\n var mergedChange = function () {\n switch (prevChange.type) {\n case CREATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous CREATE.\n case UPDATE:\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\n case DELETE:\n return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm!\n }\n break;\n case UPDATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous update.\n case UPDATE:\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\n case DELETE:\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\n }\n break;\n case DELETE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // A resurection occurred. Only create change is of interest.\n case UPDATE:\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\n case DELETE:\n return prevChange; // Still a delete change. Leave as is.\n }\n break;\n }\n }();\n changeSet[id] = mergedChange;\n }\n });\n }).then(function () {\n var changes = Object.keys(changeSet).map(function (key) {\n return changeSet[key];\n });\n hasMoreToGive = partial;\n return cb(changes, partial, { myRevision: nextRevision });\n });\n }\n }\n\n function applyRemoteChanges(remoteChanges, remoteRevision, partial, clear) {\n return enque(applyRemoteChanges, function () {\n if (!stillAlive()) return Promise.reject(\"Database not open\");\n // FIXTHIS: Check what to do if clear() is true!\n return (partial ? saveToUncommitedChanges(remoteChanges) : finallyCommitAllChanges(remoteChanges, remoteRevision)).catch(function (error) {\n abortTheProvider(error);\n return Promise.reject(error);\n });\n }, dbAliveID);\n\n function saveToUncommitedChanges(changes) {\n return db.transaction('rw', db._uncommittedChanges, function () {\n changes.forEach(function (change) {\n var changeToAdd = {\n node: node.id,\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.obj) changeToAdd.obj = change.obj;\n if (change.mods) changeToAdd.mods = change.mods;\n db._uncommittedChanges.add(changeToAdd);\n });\n }).then(function () {\n node.appliedRemoteRevision = remoteRevision;\n node.save();\n });\n }\n\n function finallyCommitAllChanges(changes, remoteRevision) {\n //alert(\"finallyCommitAllChanges() will now start its job.\");\n //var tick = Date.now();\n\n // 1. Open a write transaction on all tables in DB\n return db.transaction('rw', db.tables.filter(function (table) {\n return table.name === '_changes' || table.name === '_uncommittedChanges' || table.schema.observable;\n }), function () {\n var trans = Dexie.currentTransaction;\n var localRevisionBeforeChanges = 0;\n db._changes.orderBy('rev').last(function (lastChange) {\n // Store what revision we were at before committing the changes\n localRevisionBeforeChanges = lastChange && lastChange.rev || 0;\n }).then(function () {\n // Specify the source. Important for the change consumer to ignore changes originated from self!\n trans.source = node.id;\n // 2. Apply uncommitted changes and delete each uncommitted change\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\n }).then(function (uncommittedChanges) {\n return applyChanges(uncommittedChanges, 0);\n }).then(function () {\n return db._uncommittedChanges.where('node').equals(node.id).delete();\n }).then(function () {\n // 3. Apply last chunk of changes\n return applyChanges(changes, 0);\n }).then(function () {\n // Get what revision we are at now:\n return db._changes.orderBy('rev').last();\n }).then(function (lastChange) {\n var currentLocalRevision = lastChange && lastChange.rev || 0;\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\n node.appliedRemoteRevision = remoteRevision;\n node.remoteBaseRevisions.push({ remote: remoteRevision, local: currentLocalRevision });\n if (node.myRevision === localRevisionBeforeChanges) {\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\n node.myRevision = currentLocalRevision;\n }\n // Garbage collect remoteBaseRevisions not in use anymore:\n if (node.remoteBaseRevisions.length > 1) {\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n node.remoteBaseRevisions.splice(0, i);\n break;\n }\n }\n }\n node.save(); // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\n //var tock = Date.now();\n //alert(\"finallyCommitAllChanges() has done its job. \" + changes.length + \" changes applied in \" + ((tock - tick) / 1000) + \"seconds\");\n });\n\n function applyChanges(changes, offset) {\n /// \n /// \n var lastChangeType = 0;\n var lastCreatePromise = null;\n if (offset >= changes.length) return Promise.resolve(null);\n var change = changes[offset];\n var table = db.table(change.table);\n while (change && change.type === CREATE) {\n // Optimize CREATE changes because on initial sync with server, the entire DB will be downloaded in forms of CREATE changes.\n // Instead of waiting for each change to resolve, do all CREATE changes in bulks until another type of change is stepped upon.\n // This case is the only case that allows i to increment and the for-loop to continue since it does not return anything.\n var specifyKey = !table.schema.primKey.keyPath;\n lastCreatePromise = function (change, table, specifyKey) {\n return (specifyKey ? table.add(change.obj, change.key) : table.add(change.obj)).catch(\"ConstraintError\", function (e) {\n return specifyKey ? table.put(change.obj, change.key) : table.put(change.obj);\n });\n }(change, table, specifyKey);\n change = changes[++offset];\n if (change) table = db.table(change.table);\n }\n\n if (lastCreatePromise) {\n // We did some CREATE changes but now stumbled upon another type of change.\n // Let's wait for the last CREATE change to resolve and then call applyChanges again at current position. Next time, lastCreatePromise will be null and a case below will happen.\n return lastCreatePromise.then(function () {\n return offset < changes.length ? applyChanges(changes, offset) : null;\n });\n }\n\n if (change) {\n if (change.type === UPDATE) {\n return table.update(change.key, change.mods).then(function () {\n // Wait for update to resolve before taking next change. Why? Because it will lock transaction anyway since we are listening to CRUD events here.\n return applyChanges(changes, offset + 1);\n });\n }\n\n if (change.type === DELETE) {\n return table.delete(change.key).then(function () {\n // Wait for delete to resolve before taking next change. Why? Because it will lock transaction anyway since we are listening to CRUD events here.\n return applyChanges(changes, offset + 1);\n });\n }\n }\n\n return Promise.resolve(null); // Will return null or a Promise and make the entire applyChanges promise finally resolve.\n }\n });\n }\n }\n\n //\n //\n // Continuation Patterns Follows\n //\n //\n\n function continueSendingChanges(continuation) {\n if (!stillAlive()) {\n // Database was closed.\n if (continuation.disconnect) continuation.disconnect();\n return;\n }\n\n connectedContinuation = continuation;\n activePeer.on('disconnect', function () {\n if (connectedContinuation) {\n if (connectedContinuation.react) {\n try {\n // react pattern must provide a disconnect function.\n connectedContinuation.disconnect();\n } catch (e) {}\n }\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\n }\n });\n\n if (continuation.react) {\n continueUsingReactPattern(continuation);\n } else {\n continueUsingPollPattern(continuation);\n }\n }\n\n // React Pattern (eager)\n function continueUsingReactPattern(continuation) {\n var changesWaiting, // Boolean\n isWaitingForServer; // Boolean\n\n\n function onChanges() {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n if (isWaitingForServer) changesWaiting = true;else {\n reactToChanges();\n }\n }\n }\n\n db.on('changes', onChanges);\n\n // Override disconnect() to also unsubscribe to onChanges.\n activePeer.on('disconnect', function () {\n db.on.changes.unsubscribe(onChanges);\n });\n\n function reactToChanges() {\n if (!connectedContinuation) return;\n changesWaiting = false;\n isWaitingForServer = true;\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (!connectedContinuation) return;\n if (changes.length > 0) {\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n // More changes may be waiting:\n reactToChanges();\n });\n } else {\n isWaitingForServer = false;\n if (changesWaiting) {\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\n reactToChanges();\n } else {\n changeStatusTo(Statuses.ONLINE);\n }\n }\n }).catch(abortTheProvider);\n }\n\n reactToChanges();\n }\n\n // Poll Pattern\n function continueUsingPollPattern() {\n\n function syncAgain() {\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n }\n\n function onSuccess(continuation) {\n if (!connectedContinuation) {\n // Got disconnected before succeeding. Quit.\n return;\n }\n connectedContinuation = continuation;\n if (partial) {\n // We only sent partial changes. Need to do another round asap.\n syncAgain();\n } else {\n // We've sent all changes now (in sync!)\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\n // Provider wants to keep polling. Set Status to ONLINE.\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, continuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n }\n\n function onError(error, again) {\n if (!isNaN(again) && again < Infinity) {\n if (connectedContinuation) {\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\n } // else status is already changed since we got disconnected.\n } else {\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\n }\n }\n }).catch(abortTheProvider);\n }\n\n if (hasMoreToGive) {\n syncAgain();\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, connectedContinuation.again);\n }\n }\n }\n }\n\n db.close = override(db.close, function (origClose) {\n return function () {\n activePeers.forEach(function (peer) {\n peer.disconnect();\n });\n return origClose.apply(this, arguments);\n };\n });\n\n var syncNodeSaveQueContexts = {};\n db.observable.SyncNode.prototype.save = function () {\n var self = this;\n return db.transaction('rw?', db._syncNodes, function () {\n db._syncNodes.put(self);\n });\n };\n\n function enque(context, fn, instanceID) {\n function _enque() {\n if (!context.ongoingOperation) {\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\n return Dexie.vip(function () {\n return fn();\n });\n }).then(function (res) {\n delete context.ongoingOperation;\n return res;\n });\n } else {\n context.ongoingOperation = context.ongoingOperation.then(function () {\n return enque(context, fn, instanceID);\n });\n }\n return context.ongoingOperation;\n }\n\n if (!instanceID) {\n // Caller wants to enque it until database becomes open.\n if (db.isOpen()) {\n return _enque();\n } else {\n return Promise.reject(new Error(\"Database was closed\"));\n }\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\n // DB is already open but queuer doesnt want it to be queued if database has been closed (request bound to current instance of DB)\n return _enque();\n } else {\n return Promise.reject(new Error(\"Database was closed\"));\n }\n }\n\n function combineCreateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\n });\n return clonedChange;\n }\n\n function combineUpdateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\n var hadParentPath = false;\n Object.keys(prevChange.mods).filter(function (parentPath) {\n return keyPath.indexOf(parentPath + '.') === 0;\n }).forEach(function (parentPath) {\n setByKeyPath(clonedChange[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\n hadParentPath = true;\n });\n if (!hadParentPath) {\n // Add or replace this keyPath and its new value\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\n }\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\n // we must mimic what would happen if applying the two changes after each other:\n Object.keys(prevChange.mods).filter(function (subPath) {\n return subPath.indexOf(keyPath + '.') === 0;\n }).forEach(function (subPath) {\n delete clonedChange[subPath];\n });\n });\n return clonedChange;\n }\n};\n\nSyncable.Statuses = {\n ERROR: -1, // An irrepairable error occurred and the sync provider is dead.\n OFFLINE: 0, // The sync provider hasnt yet become online, or it has been disconnected.\n CONNECTING: 1, // Trying to connect to server\n ONLINE: 2, // Connected to server and currently in sync with server\n SYNCING: 3, // Syncing with server. For poll pattern, this is every poll call. For react pattern, this is when local changes are being sent to server.\n ERROR_WILL_RETRY: 4 // An error occured such as net down but the sync provider will retry to connect.\n};\n\nSyncable.StatusTexts = {\n \"-1\": \"ERROR\",\n \"0\": \"OFFLINE\",\n \"1\": \"CONNECTING\",\n \"2\": \"ONLINE\",\n \"3\": \"SYNCING\",\n \"4\": \"ERROR_WILL_RETRY\"\n};\n\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\n\nSyncable.registerSyncProtocol = function (name, protocolInstance) {\n /// \n /// Register a syncronization protocol that can syncronize databases with remote servers.\n /// \n /// Provider name\n /// Implementation of ISyncProtocol\n Syncable.registeredProtocols[name] = protocolInstance;\n};\n\n// Register addon in Dexie:\nDexie.Syncable = Syncable;\nDexie.addons.push(Syncable);"],"names":[],"mappings":";;;;;;;;AAAA;;;;;;;;;;;;;;;AAeA,AACA;;;;AAIA,AAEA,IAAI,QAAQ,GAAG,KAAK,CAAC,QAAQ;IACzB,OAAO,GAAG,KAAK,CAAC,OAAO;I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AAG,UAAU,IAAI,EAAE,gBAAgB,EAAE;;;;;;IAM9D,QAAQ,CAAC,mBAAmB,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC;CACzD,CAAC;;;AAGF,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC1B,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,;;,;;"} \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.min.js b/addons/Dexie.Syncable/dist/dexie-syncable.min.js new file mode 100644 index 000000000..95e572845 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n(require("dexie"),require("dexie-observable")):"function"==typeof define&&define.amd?define(["dexie","dexie-observable"],n):(e.Dexie=e.Dexie||{},e.Dexie.Syncable=n(e.Dexie,e.dexieObservable))}(this,function(e,n){"use strict";function t(n){function s(t,o,i,c,s){function p(){return n._localSyncNode&&n._localSyncNode.id===s}function m(t){return n.transaction("rw",n._syncNodes,function(){if(!i)throw new Error("Url cannot be empty");return n._syncNodes.where("url").equalsIgnoreCase(i).first(function(c){function s(n,t){this.nodeID=n,t&&e.extend(this,t)}return s.prototype.save=function(){return e.vip(function(){return c.save()})},c?(c.syncContext=new s(c.id,c.syncContext),c.syncProtocol=o,n._syncNodes.put(c)):(c=new n.observable.SyncNode,c.myRevision=-1,c.appliedRemoteRevision=null,c.remoteBaseRevisions=[],c.type="remote",c.syncProtocol=o,c.url=i,c.syncOptions=t,c.lastHeartBeat=Date.now(),c.dbUploadState=null,r.resolve(function(){if(t.initialUpload===!1)return n._changes.lastKey(function(e){c.myRevision=e})}).then(function(){n._syncNodes.add(c).then(function(e){c.syncContext=new s(e),n._syncNodes.put(c)})})),c})})}function N(o){function f(e){o.status!==e&&(o.status=e,o.save(),n.syncable.on.statusChanged.fire(e,i),n.broadcastMessage("syncStatusChanged",{newStatus:e,url:i},!1))}function m(){return a(m,function(){return g(o,function(n,s,a,u){function l(){Object.keys(u).forEach(function(n){e.setByKeyPath(o,n,u[n])}),o.save(),d.then(C)}var d=new r(function(r,u){O=function(e){u(e)},e.asap(function(){function e(e,n){u(e),p()&&(!isNaN(n)&&n<1/0?(setTimeout(function(){p()&&(f(v.SYNCING),m())},n),f(v.ERROR_WILL_RETRY,e),j&&j.disconnect&&j.disconnect(),j=null):N(e))}try{t.sync(o.syncContext,i,c,s,o.appliedRemoteRevision,n,a,S,l,function(e){r(e)},e)}catch(n){e(n,1/0)}})});return d.then(function(){})})},s)}function N(e){w.disconnect(v.ERROR,e)}function R(e){if(0===e.remoteBaseRevisions.length)return{maxClientRevision:1/0,remoteBaseRevision:null};for(var n=e.remoteBaseRevisions.length-1;n>=0;--n)if(e.myRevision>=e.remoteBaseRevisions[n].local)return{maxClientRevision:n===e.remoteBaseRevisions.length-1?1/0:e.remoteBaseRevisions[n+1].local,remoteBaseRevision:e.remoteBaseRevisions[n].remote};return{maxClientRevision:e.remoteBaseRevisions[0].local,remoteBaseRevision:null}}function g(n,t){return _(n,function o(r,i,c,s){return 0===r.length&&"myRevision"in s&&s.myRevision!==n.myRevision?(Object.keys(s).forEach(function(t){e.setByKeyPath(n,t,s[t])}),n.save(),_(n,o)):t(r,i,c,s)})}function _(t,o){function i(e,r,s){var a=!1;return s.until(function(){if(r.length===b)return a=!0,!0}).each(function(n,t){r.push({type:d,table:e.currentTable,key:t.key,obj:t.value}),e.currentKey=t.key}).then(function(){if(a)return E=!0,o(r,null,!0,{dbUploadState:e});if(0===e.tablesToUpload.length){var s=R(t);return c(e.localBaseRevision,b-r.length,s.maxClientRevision,function(e,n,t){return r=r.concat(e),t.dbUploadState=null,o(r,s.remoteBaseRevision,n,t)})}return e.currentTable=e.tablesToUpload.shift(),i(e,r,n.table(e.currentTable).orderBy(":id"))})}function c(e,o,r,i){var c={},s=0,a=!1,f=t.id,v=e;return n.transaction("r",n._changes,function(){var t=r===1/0?n._changes.where("rev").above(e):n._changes.where("rev").between(e,r,!1,!0);t.until(function(){if(s===o)return a=!0,!0}).each(function(e){if(v=e.rev,e.source!==f){var n={type:e.type,table:e.table,key:e.key};e.type===d?n.obj=e.obj:e.type===y&&(n.mods=e.mods);var t=e.table+":"+e.key,o=c[t];if(o){var r=n,i=function(){switch(o.type){case d:switch(r.type){case d:return r;case y:return u(o,r);case h:return r}break;case y:switch(r.type){case d:return r;case y:return l(o,r);case h:return r}break;case h:switch(r.type){case d:return r;case y:return o;case h:return o}}}();c[t]=i}else c[t]=n,++s}})}).then(function(){var e=Object.keys(c).map(function(e){return c[e]});return E=a,i(e,a,{myRevision:v})})}if(t.myRevision>=0){var s=R(t);return c(t.myRevision,b,s.maxClientRevision,function(e,n,t){return o(e,s.remoteBaseRevision,n,t)})}if(null===t.dbUploadState){var a=n.tables.filter(function(e){return e.schema.observable}).map(function(e){return e.name});if(0===a.length)return r.resolve(o([],null,!1,{}));var f={tablesToUpload:a,currentTable:a.shift(),currentKey:null};return n._changes.orderBy("rev").last(function(e){f.localBaseRevision=e&&e.rev||0;var t=n.table(f.currentTable).orderBy(":id");return i(f,[],t)})}if(t.dbUploadState.currentKey){var v=n.table(t.dbUploadState.currentTable).where(":id").above(t.dbUploadState.currentKey);return i(e.deepClone(t.dbUploadState),[],v)}var v=n.table(f.currentTable).orderBy(":id");return i(e.deepClone(t.dbUploadState),[],v)}function S(t,i,c,u){function l(e){return n.transaction("rw",n._uncommittedChanges,function(){e.forEach(function(e){var t={node:o.id,type:e.type,table:e.table,key:e.key};e.obj&&(t.obj=e.obj),e.mods&&(t.mods=e.mods),n._uncommittedChanges.add(t)})}).then(function(){o.appliedRemoteRevision=i,o.save()})}function f(t,i){return n.transaction("rw",n.tables.filter(function(e){return"_changes"===e.name||"_uncommittedChanges"===e.name||e.schema.observable}),function(){function c(e,t){var o=null;if(t>=e.length)return r.resolve(null);for(var i=e[t],s=n.table(i.table);i&&i.type===d;){var a=!s.schema.primKey.keyPath;o=function(e,n,t){return(t?n.add(e.obj,e.key):n.add(e.obj)).catch("ConstraintError",function(o){return t?n.put(e.obj,e.key):n.put(e.obj)})}(i,s,a),i=e[++t],i&&(s=n.table(i.table))}if(o)return o.then(function(){return t1)for(var t=o.remoteBaseRevisions.length-1;t>0;--t)if(o.myRevision>=o.remoteBaseRevisions[t].local){o.remoteBaseRevisions.splice(0,t);break}o.save()})})}return a(S,function(){return p()?(c?l(t):f(t,i)).catch(function(e){return N(e),r.reject(e)}):r.reject("Database not open")},s)}function C(e){return p()?(j=e,w.on("disconnect",function(){if(j){if(j.react)try{j.disconnect()}catch(e){}j=null}}),void(e.react?B(e):I(e))):void(e.disconnect&&e.disconnect())}function B(t){function r(){j&&(f(v.SYNCING),s?c=!0:i())}function i(){j&&(c=!1,s=!0,g(o,function(n,r,a,u){j&&(n.length>0?t.react(n,r,a,function(){Object.keys(u).forEach(function(n){e.setByKeyPath(o,n,u[n])}),o.save(),i()}):(s=!1,c?i():f(v.ONLINE)))}).catch(N))}var c,s;n.on("changes",r),w.on("disconnect",function(){n.on.changes.unsubscribe(r)}),i()}function I(){function n(){g(o,function(r,s,a,u){function l(){Object.keys(u).forEach(function(n){e.setByKeyPath(o,n,u[n])}),o.save()}function d(e){j&&(j=e,a?n():!isNaN(e.again)&&e.again<1/0?(f(v.ONLINE),setTimeout(function(){j&&(f(v.SYNCING),n())},e.again)):w.disconnect(v.OFFLINE))}function y(e,t){!isNaN(t)&&t<1/0?j&&(setTimeout(function(){j&&(f(v.SYNCING),n())},t),f(v.ERROR_WILL_RETRY)):N(e)}t.sync(o.syncContext,i,c,s,o.appliedRemoteRevision,r,a,S,l,d,y)}).catch(N)}E?n():j&&!isNaN(j.again)&&j.again<1/0&&(f(v.ONLINE),setTimeout(function(){j&&(f(v.SYNCING),n())},j.again))}w.on("disconnect",function(e){isNaN(e)||f(e)});var j;return f(v.CONNECTING),m()}var R=f.filter(function(e){return e.url===i});if(R.length>0)return R[0].connectPromise;var g=m(c).then(function(e){return N(e)}),O=null,_=!1,E=!0,w={url:i,status:v.OFFLINE,connectPromise:g,on:e.Events(null,"disconnect"),disconnect:function(e,n){if(!_){w.on.disconnect.fire(e,n);var t=f.indexOf(w);t>=0&&f.splice(t,1),n&&O&&O(n)}_=!0}};return f.push(w),g}function a(t,o,i){function c(){return t.ongoingOperation?t.ongoingOperation=t.ongoingOperation.then(function(){return a(t,o,i)}):t.ongoingOperation=e.ignoreTransaction(function(){return e.vip(function(){return o()})}).then(function(e){return delete t.ongoingOperation,e}),t.ongoingOperation}return i?n._localSyncNode&&i===n._localSyncNode.id?c():r.reject(new Error("Database was closed")):n.isOpen()?c():r.reject(new Error("Database was closed"))}function u(n,t){var o=e.deepClone(n);return Object.keys(t.mods).forEach(function(e){i(o.obj,e,t.mods[e])}),o}function l(n,t){var o=e.deepClone(n);return Object.keys(t.mods).forEach(function(e){var r=!1;Object.keys(n.mods).filter(function(n){return 0===e.indexOf(n+".")}).forEach(function(n){i(o[n],e.substr(n.length+1),t.mods[e]),r=!0}),r||(o.mods[e]=t.mods[e]),Object.keys(n.mods).filter(function(n){return 0===n.indexOf(e+".")}).forEach(function(e){delete o[e]})}),o}var f=[],d=1,y=2,h=3,v=t.Statuses,b=1e3;n.on("message",function(t){e.vip(function(){"connect"===t.type?n.syncable.connect(t.protocolName,t.url,t.options).then(t.resolve,t.reject):"disconnect"===t.type?n.syncable.disconnect(t.url).then(t.resolve,t.reject):"syncStatusChanged"===t.type&&n.syncable.on.statusChanged.fire(t.newStatus,t.url)})}),n.on("cleanup",function(t){t&&n._syncNodes.where("type").equals("remote").and(function(e){return e.status!==v.OFFLINE&&e.status!==v.ERROR}).each(function(t){e.ignoreTransaction(function(){e.vip(function(){n.syncable.connect(t.syncProtocol,t.url,t.syncOptions)})})})}),n.on("ready",function(){if(n._localSyncNode&&n._localSyncNode.isMaster)return n._syncNodes.where("type").equals("remote").and(function(e){return e.status!==v.OFFLINE&&e.status!==v.ERROR}).toArray(function(e){if(e.length>0)return r.all(e.map(function(e){return n.syncable.connect(e.syncProtocol,e.url,e.syncOptions).catch(function(e){})}))})},!0),n.syncable={},n.syncable.getStatus=function(o,i){return n.isOpen()?e.vip(function(){return n._syncNodes.where("url").equals(o).first(function(e){return e?e.status:v.OFFLINE})}).then(i):r.resolve(t.Statuses.OFFLINE).then(i)},n.syncable.list=function(){return n._syncNodes.where("type").equals("remote").toArray(function(e){return e.map(function(e){return e.url})})},n.syncable.on=e.Events(n,{statusChanged:"asap"}),n.syncable.disconnect=function(e){return n._localSyncNode&&n._localSyncNode.isMaster?f.filter(function(n){return n.url===e}).forEach(function(e){e.disconnect(v.OFFLINE)}):n._syncNodes.where("isMaster").above(0).first(function(t){n.sendMessage("disconnect",{url:e},t.id,{wantReply:!0})}),n._syncNodes.where("url").equals(e).modify(function(e){e.status=v.OFFLINE})},n.syncable.connect=function(o,i,c){c=c||{};var a=t.registeredProtocols[o];if(a)return n.isOpen()&&n._localSyncNode?n._localSyncNode.isMaster?s(a,o,i,c,n._localSyncNode.id):(n.table("_syncNodes").where("isMaster").above(0).first(function(e){return n.sendMessage("connect",{protocolName:o,url:i,options:c},e.id,{wantReply:!0})}),r.resolve()):new r(function(t,r){n.on("ready",function(){return e.vip(function(){return n.syncable.connect(o,i,c).then(t).catch(function(e){r(e)})})})});throw new Error("ISyncProtocol '"+o+"' is not registered in Dexie.Syncable.registerSyncProtocol()")},n.syncable.delete=function(e){return n.transaction("rw",n._syncNodes,n._changes,n._uncommittedChanges,function(){n._syncNodes.where("url").equals(e).toArray(function(e){if(e.length>0){var t=e.map(function(e){return e.id});return n._syncNodes.where("id").anyOf(t).delete().then(function(){return c.deleteOldChanges(),n._uncommittedChanges.where("node").anyOf(t).delete()})}})})},n.syncable.unsyncedChanges=function(e){return n._syncNodes.where("url").equals(e).first(function(e){return n._changes.where("rev").above(e.myRevision).toArray()})},n.close=o(n.close,function(e){return function(){return f.forEach(function(e){e.disconnect()}),e.apply(this,arguments)}});n.observable.SyncNode.prototype.save=function(){var e=this;return n.transaction("rw?",n._syncNodes,function(){n._syncNodes.put(e)})}}e="default"in e?e.default:e;var o=e.override,r=e.Promise,i=e.setByKeyPath,c=e.Observable;return t.Statuses={ERROR:-1,OFFLINE:0,CONNECTING:1,ONLINE:2,SYNCING:3,ERROR_WILL_RETRY:4},t.StatusTexts={"-1":"ERROR",0:"OFFLINE",1:"CONNECTING",2:"ONLINE",3:"SYNCING",4:"ERROR_WILL_RETRY"},t.registeredProtocols={},t.registerSyncProtocol=function(e,n){t.registeredProtocols[e]=n},e.Syncable=t,e.addons.push(t),t}); +//# sourceMappingURL=dexie-syncable.min.js.map \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.min.js.map b/addons/Dexie.Syncable/dist/dexie-syncable.min.js.map new file mode 100644 index 000000000..fd6d4f4c7 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../tools/tmp/src/Dexie.Syncable.js"],"names":["Syncable","db","connect","protocolInstance","protocolName","url","options","dbAliveID","stillAlive","_localSyncNode","id","getOrCreateSyncNode","transaction","_syncNodes","Error","where","equalsIgnoreCase","first","node","PersistedContext","nodeID","otherProps","this","Dexie","extend","prototype","save","vip","syncContext","syncProtocol","put","observable","SyncNode","myRevision","appliedRemoteRevision","remoteBaseRevisions","type","syncOptions","lastHeartBeat","Date","now","dbUploadState","Promise","resolve","initialUpload","_changes","lastKey","currentRevision","then","add","nodeId","connectProtocol","changeStatusTo","newStatus","status","syncable","on","statusChanged","fire","broadcastMessage","doSync","enque","getLocalChangesForNode_autoAckIfEmpty","changes","remoteBaseRevision","partial","nodeModificationsOnAck","onChangesAccepted","Object","keys","forEach","keyPath","setByKeyPath","finalSyncPromise","continueSendingChanges","reject","rejectConnectPromise","err","asap","onError","error","again","isNaN","Infinity","setTimeout","Statuses","SYNCING","ERROR_WILL_RETRY","connectedContinuation","disconnect","abortTheProvider","sync","applyRemoteChanges","continuation","ex","activePeer","ERROR","getBaseRevisionAndMaxClientRevision","length","maxClientRevision","i","local","remote","cb","getLocalChangesForNode","autoAck","getTableObjectsAsChanges","state","collection","limitReached","until","MAX_CHANGES_PER_CHUNK","each","item","cursor","push","CREATE","table","currentTable","key","obj","value","currentKey","hasMoreToGive","tablesToUpload","brmcr","getChangesSinceRevision","localBaseRevision","additionalChanges","concat","shift","orderBy","revision","maxChanges","maxRevision","changeSet","numChanges","ignoreSource","nextRevision","query","above","between","change","rev","source","changeToSend","UPDATE","mods","prevChange","nextChange","mergedChange","combineCreateAndUpdate","DELETE","combineUpdateAndUpdate","map","tables","filter","schema","name","last","lastChange","deepClone","remoteChanges","remoteRevision","clear","saveToUncommitedChanges","_uncommittedChanges","changeToAdd","finallyCommitAllChanges","applyChanges","offset","lastCreatePromise","specifyKey","primKey","catch","e","update","delete","trans","currentTransaction","localRevisionBeforeChanges","equals","toArray","uncommittedChanges","currentLocalRevision","splice","react","continueUsingReactPattern","continueUsingPollPattern","onChanges","isWaitingForServer","changesWaiting","reactToChanges","ONLINE","unsubscribe","syncAgain","onSuccess","OFFLINE","CONNECTING","existingPeer","activePeers","peer","connectPromise","disconnected","Events","pos","indexOf","context","fn","instanceID","_enque","ongoingOperation","ignoreTransaction","res","isOpen","clonedChange","hadParentPath","parentPath","substr","subPath","msg","weBecameMaster","and","connectedRemoteNode","isMaster","connectedRemoteNodes","all","getStatus","list","a","masterNode","sendMessage","wantReply","modify","registeredProtocols","nodes","nodeIDs","anyOf","Observable","deleteOldChanges","unsyncedChanges","close","override","origClose","apply","arguments","self","StatusTexts","-1","0","1","2","3","4","registerSyncProtocol","addons"],"mappings":"oTA2BA,SAAwBA,GAASC,GA4L7B,QAASC,GAAQC,EAAkBC,EAAcC,EAAKC,EAASC,GAqC3D,QAASC,KAGL,MAAOP,GAAGQ,gBAAkBR,EAAGQ,eAAeC,KAAOH,EAGzD,QAASI,GAAoBL,GACzB,MAAOL,GAAGW,YAAY,KAAMX,EAAGY,WAAY,WACvC,IAAKR,E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,GAAKR,IAOhB,OAAOT,GAAGY,WAAWE,MAAM,MAAM8N,MAAMD,GAAS3D,SAASjI,KAAK,WAM1D,MAFA8L,GAAWC,mBAEJ9O,EAAGqK,oBAAoBvJ,MAAM,QAAQ8N,MAAMD,GAAS3D,iBAO/EhL,EAAGsD,SAASyL,gBAAkB,SAAU3O,GACpC,MAAOJ,GAAGY,WAAWE,MAAM,OAAOsK,OAAOhL,GAAKY,MAAM,SAAUC,GAC1D,MAAOjB,GAAG4C,SAAS9B,MAAM,OAAO6H,MAAM1H,EAAKe,YAAYqJ,aAirB/DrL,EAAGgP,MAAQC,EAASjP,EAAGgP,MAAO,SAAUE,GACpC,MAAO,YAIH,MAHA3C,GAAYlI,QAAQ,SAAUmI,GAC1BA,EAAKhH,eAEF0J,EAAUC,MAAM9N,KAAM+N,aAKrCpP,GAAG8B,WAAWC,SAASP,UAAUC,KAAO,WACpC,GAAI4N,GAAOhO,IACX,OAAOrB,GAAGW,YAAY,MAAOX,EAAGY,WAAY,WACxCZ,EAAGY,WAAWiB,IAAIwN,iCA73B9B,IAEIJ,GAAW3N,EAAM2N,SACjBxM,EAAUnB,EAAMmB,QAChB8B,EAAejD,EAAMiD,aACrBsK,EAAavN,EAAMuN,iBAi8BvB9O,GAASqF,UACLW,OAAO,EACPqG,QAAS,EACTC,WAAY,EACZL,OAAQ,EACR3G,QAAS,EACTC,iBAAkB,GAGtBvF,EAASuP,aACLC,KAAM,QACNC,EAAK,UACLC,EAAK,aACLC,EAAK,SACLC,EAAK,UACLC,EAAK,oBAGT7P,EAAS0O,uBAET1O,EAAS8P,qBAAuB,SAAUhG,EAAM3J,GAM5CH,EAAS0O,oBAAoB5E,GAAQ3J,GAIzCoB,EAAMvB,SAAWA,EACjBuB,EAAMwO,OAAO5I,KAAKnH","file":"dist/dexie-syncable.min.js.map","sourcesContent":["/// \n/// \n/// \n/**\r\n * Dexie.Syncable.js\r\n * ===================\r\n * Dexie addon for syncing indexedDB with remote endpoints.\r\n *\r\n * version: {version} Alpha, {date}\r\n *\r\n * Disclaimber: This addon is in alpha status meaning that\r\n * its API and behavior may change.\r\n *\r\n */\n\nimport Dexie from \"dexie\";\n// Depend on 'dexie-observable'\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\n// That way, our plugin works in all UMD cases.\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\nimport \"dexie-observable\";\n\nvar override = Dexie.override,\n Promise = Dexie.Promise,\n setByKeyPath = Dexie.setByKeyPath,\n Observable = Dexie.Observable;\n\nexport default function Syncable(db) {\n /// \n\n var activePeers = [];\n\n // Change Types\n var CREATE = 1,\n UPDATE = 2,\n DELETE = 3;\n\n // Statuses\n var Statuses = Syncable.Statuses;\n\n var MAX_CHANGES_PER_CHUNK = 1000;\n\n db.on('message', function (msg) {\n // Message from other local node arrives...\n Dexie.vip(function () {\n if (msg.type === 'connect') {\n // We are master node and another non-master node wants us to do the connect.\n db.syncable.connect(msg.protocolName, msg.url, msg.options).then(msg.resolve, msg.reject);\n } else if (msg.type === 'disconnect') {\n db.syncable.disconnect(msg.url).then(msg.resolve, msg.reject);\n } else if (msg.type === 'syncStatusChanged') {\n // We are client and a master node informs us about syncStatus change.\n // Lookup the connectedProvider and call its event\n db.syncable.on.statusChanged.fire(msg.newStatus, msg.url);\n }\n });\n });\n\n db.on('cleanup', function (weBecameMaster) {\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\n if (weBecameMaster) {\n // We took over the master role in Observable's cleanup method\n db._syncNodes.where('type').equals('remote').and(function (node) {\n return node.status !== Statuses.OFFLINE && node.status !== Statuses.ERROR;\n }).each(function (connectedRemoteNode) {\n // There are connected remote nodes that we must take over\n // Since we may be in the on(ready) event, we must get VIPed to continue\n Dexie.ignoreTransaction(function () {\n Dexie.vip(function () {\n db.syncable.connect(connectedRemoteNode.syncProtocol, connectedRemoteNode.url, connectedRemoteNode.syncOptions);\n });\n });\n });\n }\n });\n\n db.on('ready', function onReady() {\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\n return db._syncNodes.where('type').equals('remote').and(function (node) {\n return node.status !== Statuses.OFFLINE && node.status !== Statuses.ERROR;\n }).toArray(function (connectedRemoteNodes) {\n // There are connected remote nodes that we must take over\n if (connectedRemoteNodes.length > 0) {\n return Promise.all(connectedRemoteNodes.map(function (node) {\n return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(function (err) {\n return undefined; // If a node fails to connect, don't make db.open() reject. Accept it!\n });\n }));\n }\n });\n }\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\n\n\n db.syncable = {};\n\n db.syncable.getStatus = function (url, cb) {\n if (db.isOpen()) {\n return Dexie.vip(function () {\n return db._syncNodes.where('url').equals(url).first(function (node) {\n return node ? node.status : Statuses.OFFLINE;\n });\n }).then(cb);\n } else {\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\n }\n };\n\n db.syncable.list = function () {\n return db._syncNodes.where('type').equals('remote').toArray(function (a) {\n return a.map(function (node) {\n return node.url;\n });\n });\n };\n\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\n\n db.syncable.disconnect = function (url) {\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n activePeers.filter(function (peer) {\n return peer.url === url;\n }).forEach(function (peer) {\n peer.disconnect(Statuses.OFFLINE);\n });\n } else {\n db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n db.sendMessage('disconnect', { url: url }, masterNode.id, { wantReply: true });\n });\n }\n\n return db._syncNodes.where(\"url\").equals(url).modify(function (node) {\n node.status = Statuses.OFFLINE;\n });\n };\n\n db.syncable.connect = function (protocolName, url, options) {\n options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined.\n var protocolInstance = Syncable.registeredProtocols[protocolName];\n\n if (protocolInstance) {\n if (db.isOpen() && db._localSyncNode) {\n // Database is open\n if (db._localSyncNode.isMaster) {\n // We are master node\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\n } else {\n // We are not master node\n // Request master node to do the connect:\n db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\n // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves.\n return db.sendMessage('connect', { protocolName: protocolName, url: url, options: options }, masterNode.id, { wantReply: true });\n });\n return Promise.resolve();\n }\n } else {\n // Database not yet open\n // Wait for it to open\n return new Promise(function (resolve, reject) {\n db.on(\"ready\", function syncWhenReady() {\n return Dexie.vip(function () {\n return db.syncable.connect(protocolName, url, options).then(resolve).catch(function (err) {\n // Reject the promise returned to the caller of db.syncable.connect():\n reject(err);\n // but resolve the promise that db.on(\"ready\") waits for, because database should succeed to open even if the connect operation fails!\n });\n });\n });\n });\n }\n } else {\n throw new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\");\n return new Promise(); // For code completion\n }\n };\n\n db.syncable.delete = function (url) {\n // Notice: Caller should call db.syncable.disconnect(url) and wait for it to finish before calling db.syncable.delete(url)\n // Surround with a readwrite-transaction\n return db.transaction('rw', db._syncNodes, db._changes, db._uncommittedChanges, function () {\n // Find the node\n db._syncNodes.where(\"url\").equals(url).toArray(function (nodes) {\n // If it's found (or even several found, as detected by @martindiphoorn),\n // let's delete it (or them) and cleanup _changes and _uncommittedChanges\n // accordingly.\n if (nodes.length > 0) {\n var nodeIDs = nodes.map(function (node) {\n return node.id;\n });\n // The following 'return' statement is not needed right now, but I leave it \n // there because if we would like to add a 'then()' statement to the main ,\n // operation above ( db._syncNodes.where(\"url\").equals(url).toArray(...) ) , \n // this return statement will asure that the whole chain is waited for \n // before entering the then() callback.\n return db._syncNodes.where('id').anyOf(nodeIDs).delete().then(function () {\n // When theese nodes are gone, let's clear the _changes table\n // from all revisions older than the oldest node.\n // Delete all changes older than revision of oldest node:\n Observable.deleteOldChanges();\n // Also don't forget to delete all uncommittedChanges for the deleted node:\n return db._uncommittedChanges.where('node').anyOf(nodeIDs).delete();\n });\n }\n });\n });\n };\n\n db.syncable.unsyncedChanges = function (url) {\n return db._syncNodes.where(\"url\").equals(url).first(function (node) {\n return db._changes.where('rev').above(node.myRevision).toArray();\n });\n };\n\n function connect(protocolInstance, protocolName, url, options, dbAliveID) {\n /// \n var existingPeer = activePeers.filter(function (peer) {\n return peer.url === url;\n });\n if (existingPeer.length > 0) {\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\n // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly.\n return existingPeer[0].connectPromise;\n }\n\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\n return connectProtocol(node);\n });\n\n var rejectConnectPromise = null;\n var disconnected = false;\n var hasMoreToGive = true;\n var activePeer = {\n url: url,\n status: Statuses.OFFLINE,\n connectPromise: connectPromise,\n on: Dexie.Events(null, \"disconnect\"),\n disconnect: function (newStatus, error) {\n if (!disconnected) {\n activePeer.on.disconnect.fire(newStatus, error);\n var pos = activePeers.indexOf(activePeer);\n if (pos >= 0) activePeers.splice(pos, 1);\n if (error && rejectConnectPromise) rejectConnectPromise(error);\n }\n disconnected = true;\n }\n };\n activePeers.push(activePeer);\n\n return connectPromise;\n\n function stillAlive() {\n // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead\n // because the new instance should be considered a fresh instance and will have another local node.\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\n }\n\n function getOrCreateSyncNode(options) {\n return db.transaction('rw', db._syncNodes, function () {\n if (!url) throw new Error(\"Url cannot be empty\");\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\n\n\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\n //\n // PersistedContext : IPersistedContext\n //\n function PersistedContext(nodeID, otherProps) {\n this.nodeID = nodeID;\n if (otherProps) Dexie.extend(this, otherProps);\n }\n\n PersistedContext.prototype.save = function () {\n // Store this instance in the syncContext property of the node it belongs to.\n return Dexie.vip(function () {\n return node.save();\n });\n };\n\n if (node) {\n // Node already there. Make syncContext become an instance of PersistedContext:\n node.syncContext = new PersistedContext(node.id, node.syncContext);\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\n db._syncNodes.put(node);\n } else {\n // Create new node and sync everything\n node = new db.observable.SyncNode();\n node.myRevision = -1;\n node.appliedRemoteRevision = null;\n node.remoteBaseRevisions = [];\n node.type = \"remote\";\n node.syncProtocol = protocolName;\n node.url = url;\n node.syncOptions = options;\n node.lastHeartBeat = Date.now();\n node.dbUploadState = null;\n Promise.resolve(function () {\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\n if (options.initialUpload === false) return db._changes.lastKey(function (currentRevision) {\n node.myRevision = currentRevision;\n });\n }).then(function () {\n db._syncNodes.add(node).then(function (nodeId) {\n node.syncContext = new PersistedContext(nodeId); // Update syncContext in db with correct nodeId.\n db._syncNodes.put(node);\n });\n });\n }\n\n return node; // returning node will make the db.transaction()-promise resolve with this value.\n });\n });\n }\n\n function connectProtocol(node) {\n /// \n\n function changeStatusTo(newStatus) {\n if (node.status !== newStatus) {\n node.status = newStatus;\n node.save();\n db.syncable.on.statusChanged.fire(newStatus, url);\n // Also broadcast message to other nodes about the status\n db.broadcastMessage(\"syncStatusChanged\", { newStatus: newStatus, url: url }, false);\n }\n }\n\n activePeer.on('disconnect', function (newStatus) {\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\n });\n\n var connectedContinuation;\n changeStatusTo(Statuses.CONNECTING);\n return doSync();\n\n function doSync() {\n // Use enque() to ensure only a single promise execution at a time.\n return enque(doSync, function () {\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\n return getLocalChangesForNode_autoAckIfEmpty(node, function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\n var finalSyncPromise = new Promise(function (resolve, reject) {\n rejectConnectPromise = function (err) {\n reject(err);\n };\n Dexie.asap(function () {\n try {\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, function (continuation) {\n resolve(continuation);\n }, onError);\n } catch (ex) {\n onError(ex, Infinity);\n }\n\n function onError(error, again) {\n reject(error);\n if (stillAlive()) {\n if (!isNaN(again) && again < Infinity) {\n setTimeout(function () {\n if (stillAlive()) {\n changeStatusTo(Statuses.SYNCING);\n doSync();\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\n connectedContinuation = null;\n } else {\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\n }\n }\n }\n });\n });\n\n return finalSyncPromise.then(function () {\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\n });\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\n // otherwise it will execute when finalSyncPromise resolves.\n finalSyncPromise.then(continueSendingChanges);\n }\n });\n }, dbAliveID);\n }\n\n function abortTheProvider(error) {\n activePeer.disconnect(Statuses.ERROR, error);\n }\n\n function getBaseRevisionAndMaxClientRevision(node) {\n /// \n if (node.remoteBaseRevisions.length === 0) return {\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\n maxClientRevision: Infinity,\n remoteBaseRevision: null\n };\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\n return {\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\n };\n }\n }\n // There are at least one item in the list but the server hasnt yet become up-to-date with the 0 revision from client. \n return {\n maxClientRevision: node.remoteBaseRevisions[0].local,\n remoteBaseRevision: null\n };\n }\n\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n return getLocalChangesForNode(node, autoAck);\n } else {\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\n }\n });\n }\n\n function getLocalChangesForNode(node, cb) {\n /// \n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\n /// for that node.\n /// \n /// \n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n\n if (node.myRevision >= 0) {\n // Node is based on a revision in our local database and will just need to get the changes that has occurred since that revision.\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Node hasn't got anything from our local database yet. We will need to upload entire DB to the node in the form of CREATE changes.\n // Check if we're in the middle of already doing that:\n if (node.dbUploadState === null) {\n // Initiatalize dbUploadState\n var tablesToUpload = db.tables.filter(function (table) {\n return table.schema.observable;\n }).map(function (table) {\n return table.name;\n });\n if (tablesToUpload.length === 0) return Promise.resolve(cb([], null, false, {})); // There are no synched tables at all.\n var dbUploadState = {\n tablesToUpload: tablesToUpload,\n currentTable: tablesToUpload.shift(),\n currentKey: null\n };\n return db._changes.orderBy('rev').last(function (lastChange) {\n dbUploadState.localBaseRevision = lastChange && lastChange.rev || 0;\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(dbUploadState, [], collection);\n });\n } else if (node.dbUploadState.currentKey) {\n var collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n } else {\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n }\n }\n\n function getTableObjectsAsChanges(state, changes, collection) {\n /// \n /// \n /// \n var limitReached = false;\n return collection.until(function () {\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\n limitReached = true;\n return true;\n }\n }).each(function (item, cursor) {\n changes.push({\n type: CREATE,\n table: state.currentTable,\n key: cursor.key,\n obj: cursor.value\n });\n state.currentKey = cursor.key;\n }).then(function () {\n if (limitReached) {\n // Limit reached. Send partial result.\n hasMoreToGive = true;\n return cb(changes, null, true, { dbUploadState: state });\n } else {\n // Done iterating this table. Check if there are more tables to go through:\n if (state.tablesToUpload.length === 0) {\n // Done iterating all tables\n // Now append changes occurred during our dbUpload:\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\n changes = changes.concat(additionalChanges);\n nodeModificationsOnAck.dbUploadState = null;\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Not done iterating all tables. Continue on next table:\n state.currentTable = state.tablesToUpload.shift();\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\n }\n }\n });\n }\n\n function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n var changeSet = {};\n var numChanges = 0;\n var partial = false;\n var ignoreSource = node.id;\n var nextRevision = revision;\n return db.transaction('r', db._changes, function () {\n var query = maxRevision === Infinity ? db._changes.where('rev').above(revision) : db._changes.where('rev').between(revision, maxRevision, false, true);\n query.until(function () {\n if (numChanges === maxChanges) {\n partial = true;\n return true;\n }\n }).each(function (change) {\n // Note the revision in nextRevision:\n nextRevision = change.rev;\n if (change.source === ignoreSource) return;\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the nescessary info:\n var changeToSend = {\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.type === CREATE) changeToSend.obj = change.obj;else if (change.type === UPDATE) changeToSend.mods = change.mods;\n\n var id = change.table + \":\" + change.key;\n var prevChange = changeSet[id];\n if (!prevChange) {\n // This is the first change on this key. Add it unless it comes from the source that we are working against\n changeSet[id] = changeToSend;\n ++numChanges;\n } else {\n // Merge the oldchange with the new change\n var nextChange = changeToSend;\n var mergedChange = function () {\n switch (prevChange.type) {\n case CREATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous CREATE.\n case UPDATE:\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\n case DELETE:\n return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm!\n }\n break;\n case UPDATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous update.\n case UPDATE:\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\n case DELETE:\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\n }\n break;\n case DELETE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // A resurection occurred. Only create change is of interest.\n case UPDATE:\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\n case DELETE:\n return prevChange; // Still a delete change. Leave as is.\n }\n break;\n }\n }();\n changeSet[id] = mergedChange;\n }\n });\n }).then(function () {\n var changes = Object.keys(changeSet).map(function (key) {\n return changeSet[key];\n });\n hasMoreToGive = partial;\n return cb(changes, partial, { myRevision: nextRevision });\n });\n }\n }\n\n function applyRemoteChanges(remoteChanges, remoteRevision, partial, clear) {\n return enque(applyRemoteChanges, function () {\n if (!stillAlive()) return Promise.reject(\"Database not open\");\n // FIXTHIS: Check what to do if clear() is true!\n return (partial ? saveToUncommitedChanges(remoteChanges) : finallyCommitAllChanges(remoteChanges, remoteRevision)).catch(function (error) {\n abortTheProvider(error);\n return Promise.reject(error);\n });\n }, dbAliveID);\n\n function saveToUncommitedChanges(changes) {\n return db.transaction('rw', db._uncommittedChanges, function () {\n changes.forEach(function (change) {\n var changeToAdd = {\n node: node.id,\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.obj) changeToAdd.obj = change.obj;\n if (change.mods) changeToAdd.mods = change.mods;\n db._uncommittedChanges.add(changeToAdd);\n });\n }).then(function () {\n node.appliedRemoteRevision = remoteRevision;\n node.save();\n });\n }\n\n function finallyCommitAllChanges(changes, remoteRevision) {\n //alert(\"finallyCommitAllChanges() will now start its job.\");\n //var tick = Date.now();\n\n // 1. Open a write transaction on all tables in DB\n return db.transaction('rw', db.tables.filter(function (table) {\n return table.name === '_changes' || table.name === '_uncommittedChanges' || table.schema.observable;\n }), function () {\n var trans = Dexie.currentTransaction;\n var localRevisionBeforeChanges = 0;\n db._changes.orderBy('rev').last(function (lastChange) {\n // Store what revision we were at before committing the changes\n localRevisionBeforeChanges = lastChange && lastChange.rev || 0;\n }).then(function () {\n // Specify the source. Important for the change consumer to ignore changes originated from self!\n trans.source = node.id;\n // 2. Apply uncommitted changes and delete each uncommitted change\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\n }).then(function (uncommittedChanges) {\n return applyChanges(uncommittedChanges, 0);\n }).then(function () {\n return db._uncommittedChanges.where('node').equals(node.id).delete();\n }).then(function () {\n // 3. Apply last chunk of changes\n return applyChanges(changes, 0);\n }).then(function () {\n // Get what revision we are at now:\n return db._changes.orderBy('rev').last();\n }).then(function (lastChange) {\n var currentLocalRevision = lastChange && lastChange.rev || 0;\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\n node.appliedRemoteRevision = remoteRevision;\n node.remoteBaseRevisions.push({ remote: remoteRevision, local: currentLocalRevision });\n if (node.myRevision === localRevisionBeforeChanges) {\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\n node.myRevision = currentLocalRevision;\n }\n // Garbage collect remoteBaseRevisions not in use anymore:\n if (node.remoteBaseRevisions.length > 1) {\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n node.remoteBaseRevisions.splice(0, i);\n break;\n }\n }\n }\n node.save(); // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\n //var tock = Date.now();\n //alert(\"finallyCommitAllChanges() has done its job. \" + changes.length + \" changes applied in \" + ((tock - tick) / 1000) + \"seconds\");\n });\n\n function applyChanges(changes, offset) {\n /// \n /// \n var lastChangeType = 0;\n var lastCreatePromise = null;\n if (offset >= changes.length) return Promise.resolve(null);\n var change = changes[offset];\n var table = db.table(change.table);\n while (change && change.type === CREATE) {\n // Optimize CREATE changes because on initial sync with server, the entire DB will be downloaded in forms of CREATE changes.\n // Instead of waiting for each change to resolve, do all CREATE changes in bulks until another type of change is stepped upon.\n // This case is the only case that allows i to increment and the for-loop to continue since it does not return anything.\n var specifyKey = !table.schema.primKey.keyPath;\n lastCreatePromise = function (change, table, specifyKey) {\n return (specifyKey ? table.add(change.obj, change.key) : table.add(change.obj)).catch(\"ConstraintError\", function (e) {\n return specifyKey ? table.put(change.obj, change.key) : table.put(change.obj);\n });\n }(change, table, specifyKey);\n change = changes[++offset];\n if (change) table = db.table(change.table);\n }\n\n if (lastCreatePromise) {\n // We did some CREATE changes but now stumbled upon another type of change.\n // Let's wait for the last CREATE change to resolve and then call applyChanges again at current position. Next time, lastCreatePromise will be null and a case below will happen.\n return lastCreatePromise.then(function () {\n return offset < changes.length ? applyChanges(changes, offset) : null;\n });\n }\n\n if (change) {\n if (change.type === UPDATE) {\n return table.update(change.key, change.mods).then(function () {\n // Wait for update to resolve before taking next change. Why? Because it will lock transaction anyway since we are listening to CRUD events here.\n return applyChanges(changes, offset + 1);\n });\n }\n\n if (change.type === DELETE) {\n return table.delete(change.key).then(function () {\n // Wait for delete to resolve before taking next change. Why? Because it will lock transaction anyway since we are listening to CRUD events here.\n return applyChanges(changes, offset + 1);\n });\n }\n }\n\n return Promise.resolve(null); // Will return null or a Promise and make the entire applyChanges promise finally resolve.\n }\n });\n }\n }\n\n //\n //\n // Continuation Patterns Follows\n //\n //\n\n function continueSendingChanges(continuation) {\n if (!stillAlive()) {\n // Database was closed.\n if (continuation.disconnect) continuation.disconnect();\n return;\n }\n\n connectedContinuation = continuation;\n activePeer.on('disconnect', function () {\n if (connectedContinuation) {\n if (connectedContinuation.react) {\n try {\n // react pattern must provide a disconnect function.\n connectedContinuation.disconnect();\n } catch (e) {}\n }\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\n }\n });\n\n if (continuation.react) {\n continueUsingReactPattern(continuation);\n } else {\n continueUsingPollPattern(continuation);\n }\n }\n\n // React Pattern (eager)\n function continueUsingReactPattern(continuation) {\n var changesWaiting, // Boolean\n isWaitingForServer; // Boolean\n\n\n function onChanges() {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n if (isWaitingForServer) changesWaiting = true;else {\n reactToChanges();\n }\n }\n }\n\n db.on('changes', onChanges);\n\n // Override disconnect() to also unsubscribe to onChanges.\n activePeer.on('disconnect', function () {\n db.on.changes.unsubscribe(onChanges);\n });\n\n function reactToChanges() {\n if (!connectedContinuation) return;\n changesWaiting = false;\n isWaitingForServer = true;\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (!connectedContinuation) return;\n if (changes.length > 0) {\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n // More changes may be waiting:\n reactToChanges();\n });\n } else {\n isWaitingForServer = false;\n if (changesWaiting) {\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\n reactToChanges();\n } else {\n changeStatusTo(Statuses.ONLINE);\n }\n }\n }).catch(abortTheProvider);\n }\n\n reactToChanges();\n }\n\n // Poll Pattern\n function continueUsingPollPattern() {\n\n function syncAgain() {\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save();\n }\n\n function onSuccess(continuation) {\n if (!connectedContinuation) {\n // Got disconnected before succeeding. Quit.\n return;\n }\n connectedContinuation = continuation;\n if (partial) {\n // We only sent partial changes. Need to do another round asap.\n syncAgain();\n } else {\n // We've sent all changes now (in sync!)\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\n // Provider wants to keep polling. Set Status to ONLINE.\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, continuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n }\n\n function onError(error, again) {\n if (!isNaN(again) && again < Infinity) {\n if (connectedContinuation) {\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\n } // else status is already changed since we got disconnected.\n } else {\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\n }\n }\n }).catch(abortTheProvider);\n }\n\n if (hasMoreToGive) {\n syncAgain();\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, connectedContinuation.again);\n }\n }\n }\n }\n\n db.close = override(db.close, function (origClose) {\n return function () {\n activePeers.forEach(function (peer) {\n peer.disconnect();\n });\n return origClose.apply(this, arguments);\n };\n });\n\n var syncNodeSaveQueContexts = {};\n db.observable.SyncNode.prototype.save = function () {\n var self = this;\n return db.transaction('rw?', db._syncNodes, function () {\n db._syncNodes.put(self);\n });\n };\n\n function enque(context, fn, instanceID) {\n function _enque() {\n if (!context.ongoingOperation) {\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\n return Dexie.vip(function () {\n return fn();\n });\n }).then(function (res) {\n delete context.ongoingOperation;\n return res;\n });\n } else {\n context.ongoingOperation = context.ongoingOperation.then(function () {\n return enque(context, fn, instanceID);\n });\n }\n return context.ongoingOperation;\n }\n\n if (!instanceID) {\n // Caller wants to enque it until database becomes open.\n if (db.isOpen()) {\n return _enque();\n } else {\n return Promise.reject(new Error(\"Database was closed\"));\n }\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\n // DB is already open but queuer doesnt want it to be queued if database has been closed (request bound to current instance of DB)\n return _enque();\n } else {\n return Promise.reject(new Error(\"Database was closed\"));\n }\n }\n\n function combineCreateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\n });\n return clonedChange;\n }\n\n function combineUpdateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\n var hadParentPath = false;\n Object.keys(prevChange.mods).filter(function (parentPath) {\n return keyPath.indexOf(parentPath + '.') === 0;\n }).forEach(function (parentPath) {\n setByKeyPath(clonedChange[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\n hadParentPath = true;\n });\n if (!hadParentPath) {\n // Add or replace this keyPath and its new value\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\n }\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\n // we must mimic what would happen if applying the two changes after each other:\n Object.keys(prevChange.mods).filter(function (subPath) {\n return subPath.indexOf(keyPath + '.') === 0;\n }).forEach(function (subPath) {\n delete clonedChange[subPath];\n });\n });\n return clonedChange;\n }\n};\n\nSyncable.Statuses = {\n ERROR: -1, // An irrepairable error occurred and the sync provider is dead.\n OFFLINE: 0, // The sync provider hasnt yet become online, or it has been disconnected.\n CONNECTING: 1, // Trying to connect to server\n ONLINE: 2, // Connected to server and currently in sync with server\n SYNCING: 3, // Syncing with server. For poll pattern, this is every poll call. For react pattern, this is when local changes are being sent to server.\n ERROR_WILL_RETRY: 4 // An error occured such as net down but the sync provider will retry to connect.\n};\n\nSyncable.StatusTexts = {\n \"-1\": \"ERROR\",\n \"0\": \"OFFLINE\",\n \"1\": \"CONNECTING\",\n \"2\": \"ONLINE\",\n \"3\": \"SYNCING\",\n \"4\": \"ERROR_WILL_RETRY\"\n};\n\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\n\nSyncable.registerSyncProtocol = function (name, protocolInstance) {\n /// \n /// Register a syncronization protocol that can syncronize databases with remote servers.\n /// \n /// Provider name\n /// Implementation of ISyncProtocol\n Syncable.registeredProtocols[name] = protocolInstance;\n};\n\n// Register addon in Dexie:\nDexie.Syncable = Syncable;\nDexie.addons.push(Syncable);"]} \ No newline at end of file diff --git a/dist/README.md b/dist/README.md deleted file mode 100644 index edbd0da65..000000000 --- a/dist/README.md +++ /dev/null @@ -1,51 +0,0 @@ -## Can't find dexie.js? -Dexie's dist files are no longer checked in to github except temporarily when tagging -a release version (just so that bower will continue to work). The reason for this is because -checking in dist files bloats the commit history and makes it error prone to contribute to the -repo. To support bower though, we have to continue checking in dist files when releasing, -but that is now handled by the release.sh script, who also removes them directly afterwards. - -If you still just want to download dexie.js to include in a test HTML page, go -to the following download site: - -### Download -[dexie.min.js](https://unpkg.com/dexie/dist/dexie.min.js) - -[dexie.min.js.map](https://unpkg.com/dexie/dist/dexie.min.js.map) - -### Typings -[dexie.d.ts](https://unpkg.com/dexie/dist/dexie.d.ts) - -### Optional Stuff -[dexie.js (non-minified version)](https://unpkg.com/dexie/dist/dexie.js) - -[dexie.js.map](https://unpkg.com/dexie/dist/dexie.js.map) - -[dexie.min.js.gz (Minified and gzipped)](https://unpkg.com/dexie/dist/dexie.min.js.gz) - -## Install from NPM -``` -npm install dexie --save -``` - -## Install from bower -``` -bower install dexie --save -``` - -## How to build -1. cd to dexie package -2. npm install -3. npm run build - -## Contributing to Dexie.js? - -Watch: -``` -npm run watch -``` - -Test: -``` -npm test -``` diff --git a/dist/dexie.d.ts b/dist/dexie.d.ts new file mode 100644 index 000000000..40e4f3402 --- /dev/null +++ b/dist/dexie.d.ts @@ -0,0 +1,454 @@ +// Type definitions for Dexie v1.5.0 +// Project: https://github.com/dfahlander/Dexie.js +// Definitions by: David Fahlander +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Thenable { + then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; + then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; +} + +declare type IndexableType = string | number | Date | Array; + +declare class Dexie { + constructor(databaseName: string, options?: { + addons?: Array<(db: Dexie) => void>, + autoOpen?: boolean, + indexedDB?: IDBFactory, + IDBKeyRange?: IDBKeyRange + }); + + name: string; + tables: Dexie.Table[]; + verno: number; + + static addons: Array<(db: Dexie) => void>; + static version: number; + static semVer: string; + static currentTransaction: Dexie.Transaction; + + static getDatabaseNames(): Dexie.Promise>; + + static getDatabaseNames(onFulfilled: (value: Array) => Thenable): Dexie.Promise; + + static getDatabaseNames(onFulfilled: (value: Array) => U): Dexie.Promise; + + static override (origFunc:F, overridedFactory: (fn:any)=>any) : F; + + static getByKeyPath(obj: Object, keyPath: string): any; + + static setByKeyPath(obj: Object, keyPath: string, value: any): void; + + static delByKeyPath(obj: Object, keyPath: string): void; + + static shallowClone (obj: T): T; + + static deepClone(obj: T): T; + + static asap(fn: Function) : void; + + static maxKey: Array; + + static dependencies: { + indexedDB: IDBFactory, + IDBKeyRange: IDBKeyRange, + localStorage?: Storage + }; + + static default: Dexie; + + version(versionNumber: Number): Dexie.Version; + + on: { + (eventName: string, subscriber: Function, ...args : any[]): void; + (eventName: 'ready', subscriber: () => any, bSticky: boolean): void; + (eventName: 'error', subscriber: (error: any) => any): void; + (eventName: 'populate', subscriber: () => any): void; + (eventName: 'blocked', subscriber: () => any): void; + (eventName: 'versionchange', subscriber: (event: IDBVersionChangeEvent) => any): void; + ready: Dexie.DexieOnReadyEvent; + error: Dexie.DexieErrorEvent; + populate: Dexie.DexieEvent; + blocked: Dexie.DexieEvent; + versionchange: Dexie.DexieVersionChangeEvent; + } + + open(): Dexie.Promise; + + table(tableName: string): Dexie.Table; + + table(tableName: string): Dexie.Table; + + table(tableName: string): Dexie.Table; + + transaction(mode: string, table: Dexie.Table, scope: () => Thenable): Dexie.Promise; + + transaction(mode: string, table: Dexie.Table, table2: Dexie.Table, scope: () => Thenable): Dexie.Promise; + + transaction(mode: string, table: Dexie.Table, table2: Dexie.Table, table3: Dexie.Table, scope: () => Thenable): Dexie.Promise; + + transaction(mode: string, tables: Dexie.Table[], scope: () => Thenable): Dexie.Promise; + + transaction(mode: string, table: Dexie.Table, scope: () => U): Dexie.Promise; + + transaction(mode: string, table: Dexie.Table, table2: Dexie.Table, scope: () => U): Dexie.Promise; + + transaction(mode: string, table: Dexie.Table, table2: Dexie.Table, table3: Dexie.Table, scope: () => U): Dexie.Promise; + + transaction(mode: string, tables: Dexie.Table[], scope: () => U): Dexie.Promise; + + close(): void; + + delete(): Dexie.Promise; + + exists(name : string) : Dexie.Promise; + + isOpen(): boolean; + + hasFailed(): boolean; + + backendDB(): IDBDatabase; + + vip(scopeFunction: () => U): U; + + // Make it possible to touch physical class constructors where they reside - as properties on db instance. + // For example, checking if (x instanceof db.Table). Can't do (x instanceof Dexie.Table because it's just a virtual interface) + Table : new()=>Dexie.Table; + WhereClause: new()=>Dexie.WhereClause; + Version: new()=>Dexie.Version; + WriteableTable: new()=>Dexie.Table; + Transaction: new()=>Dexie.Transaction; + Collection: new()=>Dexie.Collection; + WriteableCollection: new()=>Dexie.Collection; +} + +declare module Dexie { + + class Promise implements Thenable { + constructor(callback: (resolve: (value?: Thenable) => void, reject: (error?: any) => void) => void); + + constructor(callback: (resolve: (value?: R) => void, reject: (error?: any) => void) => void); + + then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Promise; + + then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Promise; + + then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Promise; + + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Promise; + + catch(onRejected: (error: any) => Thenable): Promise; + + catch(onRejected: (error: any) => U): Promise; + + catch(ExceptionType: (new() => ET), onRejected: (error: ET) => Promise): Promise; + + catch(ExceptionType: (new() => ET), onRejected: (error: ET) => U): Promise; + + catch(errorName: string, onRejected: (error: {name: string}) => Promise): Promise; + + catch(errorName: string, onRejected: (error: {name: string}) => U): Promise; + + finally(onFinally: () => any): Promise; + + onuncatched: () => any; + } + + module Promise { + function resolve(value?: Thenable): Promise; + + function resolve(value?: R): Promise; + + function reject(error: any): Promise; + + function all(promises: Thenable[]): Promise; + + function all(...promises: Thenable[]): Promise; + + function race(promises: Thenable[]): Promise; + + function newPSD(scope: () => R): R; + + var PSD: any; + + var on: { + (eventName: string, subscriber: Function): void; + (eventName: 'error', subscriber: (error: any) => any): void; + error: DexieErrorEvent; + } + } + + + interface Version { + stores(schema: { [key: string]: string }): Version; + upgrade(fn: (trans: Transaction) => void): Version; + } + + interface Transaction { + active: boolean; + db: Dexie; + mode: string; + idbtrans: IDBTransaction; + tables: { [type: string]: Table }; + storeNames: Array; + on: { + (eventName: string, subscriber: () => any): void; + (eventName: 'complete', subscriber: () => any): void; + (eventName: 'abort', subscriber: () => any): void; + (eventName: 'error', subscriber: (error:any) => any): void; + complete: DexieEvent; + abort: DexieEvent; + error: DexieEvent; + } + abort(): void; + table(tableName: string): Table; + table(tableName: string): Table; + table(tableName: string): Table; + } + + interface DexieEvent { + subscribe(fn: () => any): void; + unsubscribe(fn: () => any): void; + fire(): any; + } + + interface DexieErrorEvent { + subscribe(fn: (error: any) => any): void; + unsubscribe(fn: (error: any) => any): void; + fire(error: any): any; + } + + interface DexieVersionChangeEvent { + subscribe(fn: (event: IDBVersionChangeEvent) => any): void; + unsubscribe(fn: (event: IDBVersionChangeEvent) => any): void; + fire(event: IDBVersionChangeEvent): any; + } + + interface DexieOnReadyEvent { + subscribe(fn: () => any, bSticky: boolean): void; + unsubscribe(fn: () => any): void; + fire(): any; + } + + interface Table { + name: string; + schema: TableSchema; + hook: { + (eventName: string, subscriber: () => any): void; + creating: DexieEvent; + reading: DexieEvent; + updating: DexieEvent; + deleting: DexieEvent; + } + + get(key: Key): Promise; + where(index: string): WhereClause; + + filter(fn: (obj: T) => boolean): Collection; + + count(): Promise; + count(onFulfilled: (value: number) => Thenable): Promise; + count(onFulfilled: (value: number) => U): Promise; + + offset(n: number): Collection; + + limit(n: number): Collection; + + each(callback: (obj: T, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + + toArray(): Promise>; + toArray(onFulfilled: (value: Array) => Thenable): Promise; + toArray(onFulfilled: (value: Array) => U): Promise; + + toCollection(): Collection; + orderBy(index: string): Collection; + reverse(): Collection; + mapToClass(constructor: Function): Function; + add(item: T, key?: Key): Promise; + update(key: Key, changes: { [keyPath: string]: any }): Promise; + put(item: T, key?: Key): Promise; + delete(key: Key): Promise; + clear(): Promise; + bulkAdd(items: T[], keys?: IndexableType[]): Promise; + bulkPut(items: T[], keys?: IndexableType[]): Promise; + bulkDelete(keys: IndexableType[]) : Promise; + } + + interface WhereClause { + above(key: IndexableType): Collection; + aboveOrEqual(key: IndexableType): Collection; + anyOf(keys: IndexableType[]): Collection; + anyOf(...keys: IndexableType[]): Collection; + anyOfIgnoreCase(keys: string[]): Collection; + anyOfIgnoreCase(...keys: string[]): Collection; + below(key: IndexableType): Collection; + belowOrEqual(key: IndexableType): Collection; + between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean): Collection; + equals(key: IndexableType): Collection; + equalsIgnoreCase(key: string): Collection; + inAnyRange(ranges: Array): Collection; + startsWith(key: string): Collection; + startsWithAnyOf(prefixes: string[]): Collection; + startsWithAnyOf(...prefixes: string[]): Collection; + startsWithIgnoreCase(key: string): Collection; + startsWithAnyOfIgnoreCase(prefixes: string[]): Collection; + startsWithAnyOfIgnoreCase(...prefixes: string[]): Collection; + noneOf(keys: Array): Collection; + notEqual(key: IndexableType): Collection; + } + + interface Collection { + and(filter: (x: T) => boolean): Collection; + clone(props?: Object): Collection; + count(): Promise; + count(onFulfilled: (value: number) => Thenable): Promise; + count(onFulfilled: (value: number) => U): Promise; + distinct(): Collection; + each(callback: (obj: T, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + eachKey(callback: (key: IndexableType, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + eachPrimaryKey(callback: (key: Key, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + eachUniqueKey(callback: (key: IndexableType, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + filter(filter: (x: T) => boolean): Collection; + first(): Promise; + first(onFulfilled: (value: T) => Thenable): Promise; + first(onFulfilled: (value: T) => U): Promise; + keys(): Promise; + keys(onFulfilled: (value: IndexableType[]) => Thenable): Promise; + keys(onFulfilled: (value: IndexableType[]) => U): Promise; + primaryKeys(): Promise; + primaryKeys(onFulfilled: (value: Key[]) => Thenable): Promise; + primaryKeys(onFulfilled: (value: Key[]) => U): Promise; + last(): Promise; + last(onFulfilled: (value: T) => Thenable): Promise; + last(onFulfilled: (value: T) => U): Promise; + limit(n: number): Collection; + offset(n: number): Collection; + or(indexOrPrimayKey: string): WhereClause; + raw(): Collection; + reverse(): Collection; + sortBy(keyPath: string): Promise; + sortBy(keyPath: string, onFulfilled: (value: T[]) => Thenable): Promise; + sortBy(keyPath: string, onFulfilled: (value: T[]) => U): Promise; + toArray(): Promise>; + toArray(onFulfilled: (value: Array) => Thenable): Promise; + toArray(onFulfilled: (value: Array) => U): Promise; + uniqueKeys(): Promise; + uniqueKeys(onFulfilled: (value: IndexableType[]) => Thenable): Promise; + uniqueKeys(onFulfilled: (value: IndexableType[]) => U): Promise; + until(filter: (value: T) => boolean, includeStopEntry?: boolean): Collection; + // WriteableCollection: + delete(): Promise; + modify(changeCallback: (obj: T, ctx:{value: T}) => void): Promise; + modify(changes: { [keyPath: string]: any } ): Promise; + } + + interface TableSchema { + name: string; + primKey: IndexSpec; + indexes: IndexSpec[]; + mappedClass: Function; + } + + interface IndexSpec { + name: string; + keyPath: string | Array; + unique: boolean; + multi: boolean; + auto: boolean; + compound: boolean; + src: string; + } + + // Make it possible to touch physical classes as they are + var TableSchema: new()=>TableSchema, + IndexSpec: new()=>IndexSpec, + Events: any; // Too complex to define correctly right now. + + // errnames - handy spellcheck in switch (error.name) {} cases. + var errnames: { + // Error names generated by indexedDB: + Unknown: 'UnknownError'; + Constraint: 'ConstraintError'; + Data: 'DataError'; + TransactionInactive: 'TransactionInactiveError'; + ReadOnly: 'ReadOnlyError'; + Version: 'VersionError'; + NotFound: 'NotFoundError'; + InvalidState: 'InvalidStateError'; + InvalidAccess: 'InvalidAccessError'; + Abort: 'AbortError'; + Timeout: 'TimeoutError'; + QuotaExceeded: 'QuotaExceededError'; + Syntax: 'SyntaxError'; + DataClone: 'DataCloneError'; + + // Dexie-specific error names: + Modify: 'ModifyError'; + OpenFailed: 'OpenFailedError'; + VersionChange: 'VersionChangeError'; + Schema: 'SchemaError'; + Upgrade: 'UpgradeError'; + InvalidTable: 'InvalidTableError'; + MissingAPI: 'MissingAPIError'; + NoSuchDatabase: 'NoSuchDatabaseError'; + InvalidArgument: 'InvalidArgumentError'; + SubTransaction: 'Error'; + Unsupported: 'UnsupportedError'; + Internal: 'InternalError'; + DatabaseClosed: 'DatabaseClosedError'; + }; + + class DexieError extends Error { + name: string; + message: string; + stack: string; + inner: any; + + constructor (name?:string, message?:string); + toString(): string; + } + + class ModifyError extends DexieError{ + constructor (msg?:string, failures?: any[], successCount?: number, failedKeys?: IndexableType[]); + failures: Array; + failedKeys: Array; + successCount: number; + } + + class BulkError extends DexieError{ + constructor (msg?:string, failures?: any[]); + failures: Array; + } + + class OpenFailedError extends DexieError {constructor (msg?: string, inner?: Object);constructor (inner: Object);} + class VersionChangeError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class SchemaError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class UpgradeError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidTableError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class MissingAPIError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class NoSuchDatabaseError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidArgumentError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class SubTransactionError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class UnsupportedError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InternalError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class DatabaseClosedError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class IncompatiblePromiseError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class UnknownError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class ConstraintError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class DataError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class TransactionInactiveError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class ReadOnlyError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class VersionError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class NotFoundError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidStateError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidAccessError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class AbortError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class TimeoutError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class QuotaExceededError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class SyntaxError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class DataCloneError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} +} + +export default Dexie; diff --git a/dist/dexie.es6.js b/dist/dexie.es6.js new file mode 100644 index 000000000..5140d2704 --- /dev/null +++ b/dist/dexie.es6.js @@ -0,0 +1,4497 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 1.5.0, Thu Oct 13 2016 + * www.dexie.com + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ +var keys = Object.keys; +var isArray = Array.isArray; +var _global = + typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; + +function extend(obj, extension) { + if (typeof extension !== 'object') return obj; + keys(extension).forEach(function (key) { + obj[key] = extension[key]; + }); + return obj; +} + +const getProto = Object.getPrototypeOf; +const _hasOwn = {}.hasOwnProperty; +function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); +} + +function props (proto, extension) { + if (typeof extension === 'function') extension = extension(getProto(proto)); + keys(extension).forEach(key => { + setProp(proto, key, extension[key]); + }); +} + +function setProp(obj, prop, functionOrGetSet, options) { + Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? + {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} : + {value: functionOrGetSet, configurable: true, writable: true}, options)); +} + +function derive(Child) { + return { + from: function (Parent) { + Child.prototype = Object.create(Parent.prototype); + setProp(Child.prototype, "constructor", Child); + return { + extend: props.bind(null, Child.prototype) + }; + } + }; +} + +const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +function getPropertyDescriptor(obj, prop) { + var pd = getOwnPropertyDescriptor(obj, prop), + proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop); +} + +var _slice = [].slice; +function slice(args, start, end) { + return _slice.call(args, start, end); +} + +function override(origFunc, overridedFactory) { + return overridedFactory(origFunc); +} + +function doFakeAutoComplete(fn) { + var to = setTimeout(fn, 1000); + clearTimeout(to); +} + +function assert (b) { + if (!b) throw new Error("Assertion Failed"); +} + +function asap(fn) { + if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0); +} + + + +/** Generate an object (hash map) based on given array. + * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to + * instert on the resulting object for each item in the array. If this function returns a falsy value, the + * current item wont affect the resulting object. + */ +function arrayToObject (array, extractor) { + return array.reduce((result, item, i) => { + var nameAndValue = extractor(item, i); + if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1]; + return result; + }, {}); +} + +function trycatcher(fn, reject) { + return function () { + try { + fn.apply(this, arguments); + } catch (e) { + reject(e); + } + }; +} + +function tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } catch (ex) { + onerror && onerror(ex); + } +} + +function getByKeyPath(obj, keyPath) { + // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path + if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose. + if (!keyPath) return obj; + if (typeof keyPath !== 'string') { + var rv = []; + for (var i = 0, l = keyPath.length; i < l; ++i) { + var val = getByKeyPath(obj, keyPath[i]); + rv.push(val); + } + return rv; + } + var period = keyPath.indexOf('.'); + if (period !== -1) { + var innerObj = obj[keyPath.substr(0, period)]; + return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); + } + return undefined; +} + +function setByKeyPath(obj, keyPath, value) { + if (!obj || keyPath === undefined) return; + if ('isFrozen' in Object && Object.isFrozen(obj)) return; + if (typeof keyPath !== 'string' && 'length' in keyPath) { + assert(typeof value !== 'string' && 'length' in value); + for (var i = 0, l = keyPath.length; i < l; ++i) { + setByKeyPath(obj, keyPath[i], value[i]); + } + } else { + var period = keyPath.indexOf('.'); + if (period !== -1) { + var currentKeyPath = keyPath.substr(0, period); + var remainingKeyPath = keyPath.substr(period + 1); + if (remainingKeyPath === "") + if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value; + else { + var innerObj = obj[currentKeyPath]; + if (!innerObj) innerObj = (obj[currentKeyPath] = {}); + setByKeyPath(innerObj, remainingKeyPath, value); + } + } else { + if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value; + } + } +} + +function delByKeyPath(obj, keyPath) { + if (typeof keyPath === 'string') + setByKeyPath(obj, keyPath, undefined); + else if ('length' in keyPath) + [].map.call(keyPath, function(kp) { + setByKeyPath(obj, kp, undefined); + }); +} + +function shallowClone(obj) { + var rv = {}; + for (var m in obj) { + if (hasOwn(obj, m)) rv[m] = obj[m]; + } + return rv; +} + +function deepClone(any) { + if (!any || typeof any !== 'object') return any; + var rv; + if (isArray(any)) { + rv = []; + for (var i = 0, l = any.length; i < l; ++i) { + rv.push(deepClone(any[i])); + } + } else if (any instanceof Date) { + rv = new Date(); + rv.setTime(any.getTime()); + } else { + rv = any.constructor ? Object.create(any.constructor.prototype) : {}; + for (var prop in any) { + if (hasOwn(any, prop)) { + rv[prop] = deepClone(any[prop]); + } + } + } + return rv; +} + +function getObjectDiff(a, b, rv, prfx) { + // Compares objects a and b and produces a diff object. + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(prop => { + if (!hasOwn(b, prop)) + rv[prfx+prop] = undefined; // Property removed + else { + var ap = a[prop], + bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && + ap && bp && + ap.constructor === bp.constructor) + // Same type of object but its properties may have changed + getObjectDiff (ap, bp, rv, prfx + prop + "."); + else if (ap !== bp) + rv[prfx + prop] = b[prop];// Primitive value changed + } + }); + keys(b).forEach(prop => { + if (!hasOwn(a, prop)) { + rv[prfx+prop] = b[prop]; // Property added + } + }); + return rv; +} + +// If first argument is iterable or array-like, return it as an array +const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; +const getIteratorOf = iteratorSymbol ? function(x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); +} : function () { return null; }; + +const NO_CHAR_ARRAY = {}; +// Takes one or several arguments and returns an array based on the following criteras: +// * If several arguments provided, return arguments converted to an array in a way that +// still allows javascript engine to optimize the code. +// * If single argument is an array, return a clone of it. +// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special +// case to the two bullets below. +// * If single argument is an iterable, convert it to an array and return the resulting array. +// * If single argument is array-like (has length of type number), convert it to an array. +function getArrayOf (arrayLike) { + var i, a, x, it; + if (arguments.length === 1) { + if (isArray(arrayLike)) return arrayLike.slice(); + if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike]; + if ((it = getIteratorOf(arrayLike))) { + a = []; + while ((x = it.next()), !x.done) a.push(x.value); + return a; + } + if (arrayLike == null) return [arrayLike]; + i = arrayLike.length; + if (typeof i === 'number') { + a = new Array(i); + while (i--) a[i] = arrayLike[i]; + return a; + } + return [arrayLike]; + } + i = arguments.length; + a = new Array(i); + while (i--) a[i] = arguments[i]; + return a; +} + +const concat = [].concat; +function flatten (a) { + return concat.apply([], a); +} + +function nop() { } +function mirror(val) { return val; } +function pureFunctionChain(f1, f2) { + // Enables chained events that takes ONE argument and returns it to the next function in chain. + // This pattern is used in the hook("reading") event. + if (f1 == null || f1 === mirror) return f2; + return function (val) { + return f2(f1(val)); + }; +} + +function callBoth(on1, on2) { + return function () { + on1.apply(this, arguments); + on2.apply(this, arguments); + }; +} + +function hookCreatingChain(f1, f2) { + // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance. + // This pattern is used in the hook("creating") event. + if (f1 === nop) return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) arguments[0] = res; + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res2 !== undefined ? res2 : res; + }; +} + +function hookDeletingChain(f1, f2) { + if (f1 === nop) return f2; + return function () { + f1.apply(this, arguments); + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = this.onerror = null; + f2.apply(this, arguments); + if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + }; +} + +function hookUpdatingChain(f1, f2) { + if (f1 === nop) return f2; + return function (modifications) { + var res = f1.apply(this, arguments); + extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain. + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res === undefined ? + (res2 === undefined ? undefined : res2) : + (extend(res, res2)); + }; +} + +function reverseStoppableEventChain(f1, f2) { + if (f1 === nop) return f2; + return function () { + if (f2.apply(this, arguments) === false) return false; + return f1.apply(this, arguments); + }; +} + + + +function promisableChain(f1, f2) { + if (f1 === nop) return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, + i = arguments.length, + args = new Array(i); + while (i--) args[i] = arguments[i]; + return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} + +// By default, debug will be true only if platform is a web platform and its page is served from localhost. +// When debug = true, error's stacks will contain asyncronic long stacks. +var debug = typeof location !== 'undefined' && + // By default, use debug mode if served from localhost. + /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); + +function setDebug(value, filter) { + debug = value; + libraryFilter = filter; +} + +var libraryFilter = () => true; + +const NEEDS_THROW_FOR_STACK = !new Error("").stack; + +function getErrorWithStack() { + "use strict"; + if (NEEDS_THROW_FOR_STACK) try { + // Doing something naughty in strict mode here to trigger a specific error + // that can be explicitely ignored in debugger's exception settings. + // If we'd just throw new Error() here, IE's debugger's exception settings + // will just consider it as "exception thrown by javascript code" which is + // something you wouldn't want it to ignore. + getErrorWithStack.arguments; + throw new Error(); // Fallback if above line don't throw. + } catch(e) { + return e; + } + return new Error(); +} + +function prettyStack(exception, numIgnoredFrames) { + var stack = exception.stack; + if (!stack) return ""; + numIgnoredFrames = (numIgnoredFrames || 0); + if (stack.indexOf(exception.name) === 0) + numIgnoredFrames += (exception.name + exception.message).split('\n').length; + return stack.split('\n') + .slice(numIgnoredFrames) + .filter(libraryFilter) + .map(frame => "\n" + frame) + .join(''); +} + +function deprecated (what, fn) { + return function () { + console.warn(`${what} is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`); + return fn.apply(this, arguments); + } +} + +var dexieErrorNames = [ + 'Modify', + 'Bulk', + 'OpenFailed', + 'VersionChange', + 'Schema', + 'Upgrade', + 'InvalidTable', + 'MissingAPI', + 'NoSuchDatabase', + 'InvalidArgument', + 'SubTransaction', + 'Unsupported', + 'Internal', + 'DatabaseClosed', + 'IncompatiblePromise' +]; + +var idbDomErrorNames = [ + 'Unknown', + 'Constraint', + 'Data', + 'TransactionInactive', + 'ReadOnly', + 'Version', + 'NotFound', + 'InvalidState', + 'InvalidAccess', + 'Abort', + 'Timeout', + 'QuotaExceeded', + 'Syntax', + 'DataClone' +]; + +var errorList = dexieErrorNames.concat(idbDomErrorNames); + +var defaultTexts = { + VersionChanged: "Database version changed by other database connection", + DatabaseClosed: "Database has been closed", + Abort: "Transaction aborted", + TransactionInactive: "Transaction has already completed or failed" +}; + +// +// DexieError - base class of all out exceptions. +// +function DexieError (name, msg) { + // Reason we don't use ES6 classes is because: + // 1. It bloats transpiled code and increases size of minified code. + // 2. It doesn't give us much in this case. + // 3. It would require sub classes to call super(), which + // is not needed when deriving from Error. + this._e = getErrorWithStack(); + this.name = name; + this.message = msg; +} + +derive(DexieError).from(Error).extend({ + stack: { + get: function() { + return this._stack || + (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); + } + }, + toString: function(){ return this.name + ": " + this.message; } +}); + +function getMultiErrorMessage (msg, failures) { + return msg + ". Errors: " + failures + .map(f=>f.toString()) + .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings + .join('\n'); +} + +// +// ModifyError - thrown in WriteableCollection.modify() +// Specific constructor because it contains members failures and failedKeys. +// +function ModifyError (msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; +} +derive(ModifyError).from(DexieError); + +function BulkError (msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = failures; + this.message = getMultiErrorMessage(msg, failures); +} +derive(BulkError).from(DexieError); + +// +// +// Dynamically generate error names and exception classes based +// on the names in errorList. +// +// + +// Map of {ErrorName -> ErrorName + "Error"} +var errnames = errorList.reduce((obj,name)=>(obj[name]=name+"Error",obj),{}); + +// Need an alias for DexieError because we're gonna create subclasses with the same name. +const BaseException = DexieError; +// Map of {ErrorName -> exception constructor} +var exceptions = errorList.reduce((obj,name)=>{ + // Let the name be "DexieError" because this name may + // be shown in call stack and when debugging. DexieError is + // the most true name because it derives from DexieError, + // and we cannot change Function.name programatically without + // dynamically create a Function object, which would be considered + // 'eval-evil'. + var fullName = name + "Error"; + function DexieError (msgOrInner, inner){ + this._e = getErrorWithStack(); + this.name = fullName; + if (!msgOrInner) { + this.message = defaultTexts[name] || fullName; + this.inner = null; + } else if (typeof msgOrInner === 'string') { + this.message = msgOrInner; + this.inner = inner || null; + } else if (typeof msgOrInner === 'object') { + this.message = `${msgOrInner.name} ${msgOrInner.message}`; + this.inner = msgOrInner; + } + } + derive(DexieError).from(BaseException); + obj[name]=DexieError; + return obj; +},{}); + +// Use ECMASCRIPT standard exceptions where applicable: +exceptions.Syntax = SyntaxError; +exceptions.Type = TypeError; +exceptions.Range = RangeError; + +var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{ + obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); + +function mapError (domError, message) { + if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) + return domError; + var rv = new exceptionMap[domError.name](message || domError.message, domError); + if ("stack" in domError) { + // Derive stack from inner exception if it has a stack + setProp(rv, "stack", {get: function(){ + return this.inner.stack; + }}); + } + return rv; +} + +var fullNameExceptions = errorList.reduce((obj, name)=>{ + if (["Syntax","Type","Range"].indexOf(name) === -1) + obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); + +fullNameExceptions.ModifyError = ModifyError; +fullNameExceptions.DexieError = DexieError; +fullNameExceptions.BulkError = BulkError; + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + // Subscribe. If additional arguments than just the subscriber was provided, forward them as well. + var i = arguments.length, args = new Array(i - 1); + while (--i) args[i - 1] = arguments[i]; + evs[eventName].subscribe.apply(null, args); + return ctx; + } else if (typeof (eventName) === 'string') { + // Return interface allowing to fire or unsubscribe from event + return evs[eventName]; + } + }; + rv.addEventType = add; + + for (var i = 1, l = arguments.length; i < l; ++i) { + add(arguments[i]); + } + + return rv; + + function add(eventName, chainFunction, defaultFunction) { + if (typeof eventName === 'object') return addConfiguredEvents(eventName); + if (!chainFunction) chainFunction = reverseStoppableEventChain; + if (!defaultFunction) defaultFunction = nop; + + var context = { + subscribers: [], + fire: defaultFunction, + subscribe: function (cb) { + if (context.subscribers.indexOf(cb) === -1) { + context.subscribers.push(cb); + context.fire = chainFunction(context.fire, cb); + } + }, + unsubscribe: function (cb) { + context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); + context.fire = context.subscribers.reduce(chainFunction, defaultFunction); + } + }; + evs[eventName] = rv[eventName] = context; + return context; + } + + function addConfiguredEvents(cfg) { + // events(this, {reading: [functionChain, nop]}); + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } else if (args === 'asap') { + // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack + // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten. + var context = add(eventName, mirror, function fire() { + // Optimazation-safe cloning of arguments into args. + var i = arguments.length, args = new Array(i); + while (i--) args[i] = arguments[i]; + // All each subscriber: + context.subscribers.forEach(function (fn) { + asap(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } else throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +// +// Promise Class for Dexie library +// +// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by +// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. +// +// Modifications needed to be done to support indexedDB because it wont accept setTimeout() +// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) . +// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45 +// +// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since +// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise. +// +// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another +// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use +// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick +// engine that is used instead of setImmediate() or setTimeout(). +// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. +// Also with inspiration from bluebird, asyncronic stacks in debug mode. +// +// Specific non-standard features of this Promise class: +// * Async static context support (Promise.PSD) +// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame +// and below + all promises that those promises creates or awaits. +// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). +// +// David Fahlander, https://github.com/dfahlander +// + +// Just a pointer that only this module knows about. +// Used in Promise constructor to emulate a private constructor. +var INTERNAL = {}; + +// Async stacks (long stacks) must not grow infinitely. +var LONG_STACKS_CLIP_LIMIT = 100; +var MAX_LONG_STACKS = 20; +var stack_being_generated = false; + +/* The default "nextTick" function used only for the very first promise in a promise chain. + As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks + emulated in this module. For indexedDB compatibility, this means that every method needs to + execute at least one promise before doing an indexedDB operation. Dexie will always call + db.ready().then() for every operation to make sure the indexedDB event is started in an + emulated micro tick. +*/ +var schedulePhysicalTick = (_global.setImmediate ? + // setImmediate supported. Those modern platforms also supports Function.bind(). + setImmediate.bind(null, physicalTick) : + _global.MutationObserver ? + // MutationObserver supported + () => { + var hiddenDiv = document.createElement("div"); + (new MutationObserver(() => { + physicalTick(); + hiddenDiv = null; + })).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); + } : + // No support for setImmediate or MutationObserver. No worry, setTimeout is only called + // once time. Every tick that follows will be our emulated micro tick. + // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug + ()=>{setTimeout(physicalTick,0);} +); + +// Confifurable through Promise.scheduler. +// Don't export because it would be unsafe to let unknown +// code call it unless they do try..catch within their callback. +// This function can be retrieved through getter of Promise.scheduler though, +// but users must not do Promise.scheduler (myFuncThatThrows exception)! +var asap$1 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; + +var isOutsideMicroTick = true; +var needsNewPhysicalTick = true; +var unhandledErrors = []; +var rejectingErrors = []; +var currentFulfiller = null; +var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions + +var globalPSD = { + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + //env: null, // Will be set whenever leaving a scope using wrappers.snapshot() + finalize: function () { + this.unhandleds.forEach(uh => { + try { + globalError(uh[0], uh[1]); + } catch (e) {} + }); + } +}; + +var PSD = globalPSD; + +var microtickQueue = []; // Callbacks to call in this or next physical tick. +var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. +var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. + +// Wrappers are not being used yet. Their framework is functioning and can be used +// to replace environment during a PSD scope (a.k.a. 'zone'). +/* **KEEP** export var wrappers = (() => { + var wrappers = []; + + return { + snapshot: () => { + var i = wrappers.length, + result = new Array(i); + while (i--) result[i] = wrappers[i].snapshot(); + return result; + }, + restore: values => { + var i = wrappers.length; + while (i--) wrappers[i].restore(values[i]); + }, + wrap: () => wrappers.map(w => w.wrap()), + add: wrapper => { + wrappers.push(wrapper); + } + }; +})(); +*/ + +function Promise(fn) { + if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. + + // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() + // execute the microtask engine implicitely within the call to resolve() or reject(). + // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack + // only contains library code when calling resolve() or reject(). + // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from + // global scope (event handler, timer etc)! + this._lib = false; + // Current async scope + var psd = (this._PSD = PSD); + + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; // Number of previous promises (for long stacks) + linkToPreviousPromise(this, currentFulfiller); + } + + if (typeof fn !== 'function') { + if (fn !== INTERNAL) throw new TypeError('Not a function'); + // Private constructor (INTERNAL, state, value). + // Used internally by Promise.resolve() and Promise.reject(). + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). + return; + } + + this._state = null; // null (=pending), false (=rejected) or true (=resolved) + this._value = null; // error or result + ++psd.ref; // Refcounting current scope + executePromiseTask(this, fn); +} + +props(Promise.prototype, { + + then: function (onFulfilled, onRejected) { + var rv = new Promise((resolve, reject) => { + propagateToListener(this, new Listener(onFulfilled, onRejected, resolve, reject)); + }); + debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this); + return rv; + }, + + _then: function (onFulfilled, onRejected) { + // A little tinier version of then() that don't have to create a resulting promise. + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected)); + }, + + catch: function (onRejected) { + if (arguments.length === 1) return this.then(null, onRejected); + // First argument is the Error type to catch + var type = arguments[0], + handler = arguments[1]; + return typeof type === 'function' ? this.then(null, err => + // Catching errors by its constructor type (similar to java / c++ / c#) + // Sample: promise.catch(TypeError, function (e) { ... }); + err instanceof type ? handler(err) : PromiseReject(err)) + : this.then(null, err => + // Catching errors by the error.name property. Makes sense for indexedDB where error type + // is always DOMError but where e.name tells the actual error type. + // Sample: promise.catch('ConstraintError', function (e) { ... }); + err && err.name === type ? handler(err) : PromiseReject(err)); + }, + + finally: function (onFinally) { + return this.then(value => { + onFinally(); + return value; + }, err => { + onFinally(); + return PromiseReject(err); + }); + }, + + // Deprecate in next major. Needed only for db.on.error. + uncaught: function (uncaughtHandler) { + // Be backward compatible and use "onuncatched" as the event name on this. + // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops. + this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler); + // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not + // a previous promise. Reason: the prevous promise may lack onuncatched handler. + if (this._state === false && unhandledErrors.indexOf(this) === -1) { + // Replace unhandled error's destinaion promise with this one! + unhandledErrors.some((p,i,l) => p._value === this._value && (l[i] = this)); + // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could + // take away this piece of code as well as the onuncatched and uncaught() method. + } + return this; + }, + + stack: { + get: function() { + if (this._stack) return this._stack; + try { + stack_being_generated = true; + var stacks = getStack (this, [], MAX_LONG_STACKS); + var stack = stacks.join("\nFrom previous: "); + if (this._state !== null) this._stack = stack; // Stack may be updated on reject. + return stack; + } finally { + stack_being_generated = false; + } + } + } +}); + +function Listener(onFulfilled, onRejected, resolve, reject) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = PSD; +} + +// Promise Static Properties +props (Promise, { + all: function () { + var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like. + return new Promise(function (resolve, reject) { + if (values.length === 0) resolve([]); + var remaining = values.length; + values.forEach((a,i) => Promise.resolve(a).then(x => { + values[i] = x; + if (!--remaining) resolve(values); + }, reject)); + }); + }, + + resolve: value => { + if (value instanceof Promise) return value; + if (value && typeof value.then === 'function') return new Promise((resolve, reject)=>{ + value.then(resolve, reject); + }); + return new Promise(INTERNAL, true, value); + }, + + reject: PromiseReject, + + race: function () { + var values = getArrayOf.apply(null, arguments); + return new Promise((resolve, reject) => { + values.map(value => Promise.resolve(value).then(resolve, reject)); + }); + }, + + PSD: { + get: ()=>PSD, + set: value => PSD = value + }, + + newPSD: newScope, + + usePSD: usePSD, + + scheduler: { + get: () => asap$1, + set: value => {asap$1 = value;} + }, + + rejectionMapper: { + get: () => rejectionMapper, + set: value => {rejectionMapper = value;} // Map reject failures + }, + + follow: fn => { + return new Promise((resolve, reject) => { + return newScope((resolve, reject) => { + var psd = PSD; + psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() + psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. + psd.finalize = callBoth(function () { + // Unhandled standard or 3rd part promises are put in PSD.unhandleds and + // examined upon scope completion while unhandled rejections in this Promise + // will trigger directly through psd.onunhandled + run_at_end_of_this_or_next_physical_tick(()=>{ + this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, resolve, reject); + }); + }, + + on: Events(null, {"error": [ + reverseStoppableEventChain, + defaultErrorHandler] // Default to defaultErrorHandler + }) + +}); + +var PromiseOnError = Promise.on.error; +PromiseOnError.subscribe = deprecated ("Promise.on('error')", PromiseOnError.subscribe); +PromiseOnError.unsubscribe = deprecated ("Promise.on('error').unsubscribe", PromiseOnError.unsubscribe); + +/** +* Take a potentially misbehaving resolver function and make sure +* onFulfilled and onRejected are only called once. +* +* Makes no guarantees about asynchrony. +*/ +function executePromiseTask (promise, fn) { + // Promise Resolution Procedure: + // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + try { + fn(value => { + if (promise._state !== null) return; + if (value === promise) throw new TypeError('A promise cannot be resolved with itself.'); + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + if (value && typeof value.then === 'function') { + executePromiseTask(promise, (resolve, reject) => { + value instanceof Promise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) endMicroTickScope(); + }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below + } catch (ex) { + handleRejection(promise, ex); + } +} + +function handleRejection (promise, reason) { + rejectingErrors.push(reason); + if (promise._state !== null) return; + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + reason = rejectionMapper(reason); + promise._state = false; + promise._value = reason; + debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{ + var origProp = getPropertyDescriptor(reason, "stack"); + reason._promise = promise; + setProp(reason, "stack", { + get: () => + stack_being_generated ? + origProp && (origProp.get ? + origProp.get.apply(reason) : + origProp.value) : + promise.stack + }); + }); + // Add the failure to a list of possibly uncaught errors + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) endMicroTickScope(); +} + +function propagateAllListeners (promise) { + //debug && linkToPreviousPromise(promise); + var listeners = promise._listeners; + promise._listeners = []; + for (var i = 0, len = listeners.length; i < len; ++i) { + propagateToListener(promise, listeners[i]); + } + var psd = promise._PSD; + --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); + if (numScheduledCalls === 0) { + // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, + // and that no deferreds where listening to this rejection or success. + // Since there is a risk that our stack can contain application code that may + // do stuff after this code is finished that may generate new calls, we cannot + // call finalizers here. + ++numScheduledCalls; + asap$1(()=>{ + if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors + }, []); + } +} + +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() + return (promise._state ? listener.resolve : listener.reject) (promise._value); + } + var psd = listener.psd; + ++psd.ref; + ++numScheduledCalls; + asap$1 (callListener, [cb, promise, listener]); +} + +function callListener (cb, promise, listener) { + var outerScope = PSD; + var psd = listener.psd; + try { + if (psd !== outerScope) { + // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment. + PSD = psd; + // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. + } + + // Set static variable currentFulfiller to the promise that is being fullfilled, + // so that we connect the chain of promises (for long stacks support) + currentFulfiller = promise; + + // Call callback and resolve our listener with it's return value. + var value = promise._value, + ret; + if (promise._state) { + ret = cb (value); + } else { + if (rejectingErrors.length) rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. + } + listener.resolve(ret); + } catch (e) { + // Exception thrown in callback. Reject our listener. + listener.reject(e); + } finally { + // Restore PSD, env and currentFulfiller. + if (psd !== outerScope) { + PSD = outerScope; + // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment + } + currentFulfiller = null; + if (--numScheduledCalls === 0) finalizePhysicalTick(); + --psd.ref || psd.finalize(); + } +} + +function getStack (promise, stacks, limit) { + if (stacks.length === limit) return stacks; + var stack = ""; + if (promise._state === false) { + var failure = promise._value, + errorName, + message; + + if (failure != null) { + errorName = failure.name || "Error"; + message = failure.message || failure; + stack = prettyStack(failure, 0); + } else { + errorName = failure; // If error is undefined or null, show that. + message = ""; + } + stacks.push(errorName + (message ? ": " + message : "") + stack); + } + if (debug) { + stack = prettyStack(promise._stackHolder, 2); + if (stack && stacks.indexOf(stack) === -1) stacks.push(stack); + if (promise._prev) getStack(promise._prev, stacks, limit); + } + return stacks; +} + +function linkToPreviousPromise(promise, prev) { + // Support long stacks by linking to previous completed promise. + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming "tail". + promise._prev = prev; + promise._numPrev = numPrev; + } +} + +/* The callback to schedule with setImmediate() or setTimeout(). + It runs a virtual microtick and executes any callback registered in microtickQueue. + */ +function physicalTick() { + beginMicroTickScope() && endMicroTickScope(); +} + +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} + +/* Executes micro-ticks without doing try..catch. + This can be possible because we only use this internally and + the registered functions are exception-safe (they do try..catch + internally before calling any external method). If registering + functions in the microtickQueue that are not exception-safe, this + would destroy the framework and make it instable. So we don't export + our asap method. +*/ +function endMicroTickScope() { + var callbacks, i, l; + do { + while (microtickQueue.length > 0) { + callbacks = microtickQueue; + microtickQueue = []; + l = callbacks.length; + for (i = 0; i < l; ++i) { + var item = callbacks[i]; + item[0].apply(null, item[1]); + } + } + } while (microtickQueue.length > 0); + isOutsideMicroTick = true; + needsNewPhysicalTick = true; +} + +function finalizePhysicalTick() { + var unhandledErrs = unhandledErrors; + unhandledErrors = []; + unhandledErrs.forEach(p => { + p._PSD.onunhandled.call(null, p._value, p); + }); + var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. + var i = finalizers.length; + while (i) finalizers[--i](); +} + +function run_at_end_of_this_or_next_physical_tick (fn) { + function finalizer() { + fn(); + tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); + } + tickFinalizers.push(finalizer); + ++numScheduledCalls; + asap$1(()=>{ + if (--numScheduledCalls === 0) finalizePhysicalTick(); + }, []); +} + +function addPossiblyUnhandledError(promise) { + // Only add to unhandledErrors if not already there. The first one to add to this list + // will be upon the first rejection so that the root cause (first promise in the + // rejection chain) is the one listed. + if (!unhandledErrors.some(p => p._value === promise._value)) + unhandledErrors.push(promise); +} + +function markErrorAsHandled(promise) { + // Called when a reject handled is actually being called. + // Search in unhandledErrors for any promise whos _value is this promise_value (list + // contains only rejected promises, and only one item per error) + var i = unhandledErrors.length; + while (i) if (unhandledErrors[--i]._value === promise._value) { + // Found a promise that failed with this same error object pointer, + // Remove that since there is a listener that actually takes care of it. + unhandledErrors.splice(i, 1); + return; + } +} + +// By default, log uncaught errors to the console +function defaultErrorHandler(e) { + console.warn(`Unhandled rejection: ${e.stack || e}`); +} + +function PromiseReject (reason) { + return new Promise(INTERNAL, false, reason); +} + +function wrap (fn, errorCatcher) { + var psd = PSD; + return function() { + var wasRootExec = beginMicroTickScope(), + outerScope = PSD; + + try { + if (outerScope !== psd) { + // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment + PSD = psd; + // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. + } + return fn.apply(this, arguments); + } catch (e) { + errorCatcher && errorCatcher(e); + } finally { + if (outerScope !== psd) { + PSD = outerScope; + // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment + } + if (wasRootExec) endMicroTickScope(); + } + }; +} + +function newScope (fn, a1, a2, a3) { + var parent = PSD, + psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + // **KEEP** psd.env = wrappers.wrap(psd); + + // unhandleds and onunhandled should not be specifically set here. + // Leave them on parent prototype. + // unhandleds.push(err) will push to parent's prototype + // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) + ++parent.ref; + psd.finalize = function () { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD (psd, fn, a1, a2, a3); + if (psd.ref === 0) psd.finalize(); + return rv; +} + +function usePSD (psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + if (psd !== outerScope) { + // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment. + PSD = psd; + // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. + } + return fn(a1, a2, a3); + } finally { + if (psd !== outerScope) { + PSD = outerScope; + // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment. + } + } +} + +const UNHANDLEDREJECTION = "unhandledrejection"; + +function globalError(err, promise) { + var rv; + try { + rv = promise.onuncatched(err); + } catch (e) {} + if (rv !== false) try { + var event, eventData = {promise: promise, reason: err}; + if (_global.document && document.createEvent) { + event = document.createEvent('Event'); + event.initEvent(UNHANDLEDREJECTION, true, true); + extend(event, eventData); + } else if (_global.CustomEvent) { + event = new CustomEvent(UNHANDLEDREJECTION, {detail: eventData}); + extend(event, eventData); + } + if (event && _global.dispatchEvent) { + dispatchEvent(event); + if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) + // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. + try {_global.onunhandledrejection(event);} catch (_) {} + } + if (!event.defaultPrevented) { + // Backward compatibility: fire to events registered at Promise.on.error + Promise.on.error.fire(err, promise); + } + } catch (e) {} +} + + +/* **KEEP** + +export function wrapPromise(PromiseClass) { + var proto = PromiseClass.prototype; + var origThen = proto.then; + + wrappers.add({ + snapshot: () => proto.then, + restore: value => {proto.then = value;}, + wrap: () => patchedThen + }); + + function patchedThen (onFulfilled, onRejected) { + var promise = this; + var onFulfilledProxy = wrap(function(value){ + var rv = value; + if (onFulfilled) { + rv = onFulfilled(rv); + if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. + } + --PSD.ref || PSD.finalize(); + return rv; + }); + var onRejectedProxy = wrap(function(err){ + promise._$err = err; + var unhandleds = PSD.unhandleds; + var idx = unhandleds.length, + rv; + while (idx--) if (unhandleds[idx]._$err === err) break; + if (onRejected) { + if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled. + rv = onRejected(err); + if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. + } else { + if (idx === -1) unhandleds.push(promise); + rv = PromiseClass.reject(err); + rv._$nointercept = true; // Prohibit eternal loop. + } + --PSD.ref || PSD.finalize(); + return rv; + }); + + if (this._$nointercept) return origThen.apply(this, arguments); + ++PSD.ref; + return origThen.call(this, onFulfilledProxy, onRejectedProxy); + } +} + +// Global Promise wrapper +if (_global.Promise) wrapPromise(_global.Promise); + +*/ + +doFakeAutoComplete(() => { + // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie. + asap$1 = (fn, args) => { + setTimeout(()=>{fn.apply(null, args);}, 0); + }; +}); + +function rejection (err, uncaughtHandler) { + // Get the call stack and return a rejected promise. + var rv = Promise.reject(err); + return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv; +} + +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 1.5.0, Thu Oct 13 2016 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + +var DEXIE_VERSION = '1.5.0'; +var maxString = String.fromCharCode(65535); +var maxKey = (function(){try {IDBKeyRange.only([[]]);return [[]];}catch(e){return maxString;}})(); +var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; +var STRING_EXPECTED = "String expected."; +var connections = []; +var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); +var hasIEDeleteObjectStoreBug = isIEOrEdge; +var hangsOnDeleteLargeKeyRange = isIEOrEdge; +var dexieStackFrameFilter = frame => !/(dexie\.js|dexie\.min\.js)/.test(frame); + +setDebug(debug, dexieStackFrameFilter); + +function Dexie(dbName, options) { + /// Specify only if you wich to control which addons that should run on this instance + var deps = Dexie.dependencies; + var opts = extend({ + // Default Options + addons: Dexie.addons, // Pick statically registered addons by default + autoOpen: true, // Don't require db.open() explicitely. + indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env. + IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env. + }, options); + var addons = opts.addons, + autoOpen = opts.autoOpen, + indexedDB = opts.indexedDB, + IDBKeyRange = opts.IDBKeyRange; + + var globalSchema = this._dbSchema = {}; + var versions = []; + var dbStoreNames = []; + var allTables = {}; + /// + var idbdb = null; // Instance of IDBDatabase + var dbOpenError = null; + var isBeingOpened = false; + var openComplete = false; + var READONLY = "readonly", READWRITE = "readwrite"; + var db = this; + var dbReadyResolve, + dbReadyPromise = new Promise(resolve => { + dbReadyResolve = resolve; + }), + cancelOpen, + openCanceller = new Promise((_, reject) => { + cancelOpen = reject; + }); + var autoSchema = true; + var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB), + hasGetAll; + + function init() { + // Default subscribers to "versionchange" and "blocked". + // Can be overridden by custom handlers. If custom handlers return false, these default + // behaviours will be prevented. + db.on("versionchange", function (ev) { + // Default behavior for versionchange event is to close database connection. + // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); + // Let's not block the other window from making it's delete() or open() call. + // NOTE! This event is never fired in IE,Edge or Safari. + if (ev.newVersion > 0) + console.warn(`Another connection wants to upgrade database '${db.name}'. Closing db now to resume the upgrade.`); + else + console.warn(`Another connection wants to delete database '${db.name}'. Closing db now to resume the delete request.`); + db.close(); + // In many web applications, it would be recommended to force window.reload() + // when this event occurs. To do that, subscribe to the versionchange event + // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) + // The reason for this is that your current web app obviously has old schema code that needs + // to be updated. Another window got a newer version of the app and needs to upgrade DB but + // your window is blocking it unless we close it here. + }); + db.on("blocked", ev => { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn(`Dexie.delete('${db.name}') was blocked`); + else + console.warn(`Upgrade '${db.name}' blocked by other connection holding version ${ev.oldVersion/10}`); + }); + } + + // + // + // + // ------------------------- Versioning Framework--------------------------- + // + // + // + + this.version = function (versionNumber) { + /// + /// + if (idbdb || isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; + if (versionInstance) return versionInstance; + versionInstance = new Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + return versionInstance; + }; + + function Version(versionNumber) { + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + this.stores({}); // Derive earlier schemas by default. + } + + extend(Version.prototype, { + stores: function (stores) { + /// + /// Defines the schema for a particular version + /// + /// + /// Example:
+ /// {users: "id++,first,last,&username,*email",
+ /// passwords: "id++,&username"}
+ ///
+ /// Syntax: {Table: "[primaryKey][++],[&][*]index1,[&][*]index2,..."}

+ /// Special characters:
+ /// "&" means unique key,
+ /// "*" means value is multiEntry,
+ /// "++" means auto-increment and only applicable for primary key
+ /// + this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; + + // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax. + var storesSpec = {}; + versions.forEach(function (version) { // 'versions' is always sorted by lowest version first. + extend(storesSpec, version._cfg.storesSource); + }); + + var dbschema = (this._cfg.dbschema = {}); + this._parseStoresSpec(storesSpec, dbschema); + // Update the latest schema to this version + // Update API + globalSchema = db._dbSchema = dbschema; + removeTablesApi([allTables, db, Transaction.prototype]); + setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema); + dbStoreNames = keys(dbschema); + return this; + }, + upgrade: function (upgradeFunction) { + /// Function that performs upgrading actions. + var self = this; + fakeAutoComplete(function () { + upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema));// BUGBUG: No code completion for prev version's tables wont appear. + }); + this._cfg.contentUpgrade = upgradeFunction; + return this; + }, + _parseStoresSpec: function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var instanceTemplate = {}; + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) throw new exceptions.Schema("Primary key cannot be multi-valued"); + if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath); + indexes.forEach(function (idx) { + if (idx.auto) throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); + if (!idx.keyPath) throw new exceptions.Schema("Index must have a name and cannot be an empty string"); + setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return ""; }) : ""); + }); + outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate); + } + }); + } + }); + + function runUpgraders (oldVersion, idbtrans, reject) { + var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema); + trans.create(idbtrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + newScope(function () { + PSD.trans = trans; + if (oldVersion === 0) { + // Create tables: + keys(globalSchema).forEach(function (tableName) { + createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + Promise.follow(()=>db.on.populate.fire(trans)).catch(rejectTransaction); + } else + updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction); + }); + } + + function updateTablesAndIndexes (oldVersion, trans, idbtrans) { + // Upgrade version to version, step-by-step from oldest to newest version. + // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version) + var queue = []; + var oldVersionStruct = versions.filter(version => version._cfg.version === oldVersion)[0]; + if (!oldVersionStruct) throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing"); + globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema; + var anyContentUpgraderHasRun = false; + + var versToRun = versions.filter(v => v._cfg.version > oldVersion); + versToRun.forEach(function (version) { + /// + queue.push(()=>{ + var oldSchema = globalSchema; + var newSchema = version._cfg.dbschema; + adjustToExistingIndexNames(oldSchema, idbtrans); + adjustToExistingIndexNames(newSchema, idbtrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + // Add tables + diff.add.forEach(function (tuple) { + createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + // Change tables + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } else { + var store = idbtrans.objectStore(change.name); + // Add indexes + change.add.forEach(function (idx) { + addIndex(store, idx); + }); + // Update indexes + change.change.forEach(function (idx) { + store.deleteIndex(idx.name); + addIndex(store, idx); + }); + // Delete indexes + change.del.forEach(function (idxName) { + store.deleteIndex(idxName); + }); + } + }); + if (version._cfg.contentUpgrade) { + anyContentUpgraderHasRun = true; + return Promise.follow(()=>{ + version._cfg.contentUpgrade(trans); + }); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of. + var newSchema = version._cfg.dbschema; + // Delete old tables + deleteRemovedTables(newSchema, idbtrans); + } + }); + }); + + // Now, create a queue execution engine + function runQueue () { + return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + Promise.resolve(); + } + + return runQueue().then(()=>{ + createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version) + }); + } + + function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], // Array of table names + add: [], // Array of [tableName, newDefinition] + change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs} + }; + for (var table in oldSchema) { + if (!newSchema[table]) diff.del.push(table); + } + for (table in newSchema) { + var oldDef = oldSchema[table], + newDef = newSchema[table]; + if (!oldDef) { + diff.add.push([table, newDef]); + } else { + var change = { + name: table, + def: newDef, + recreate: false, + del: [], + add: [], + change: [] + }; + if (oldDef.primKey.src !== newDef.primKey.src) { + // Primary key has changed. Remove and re-add table. + change.recreate = true; + diff.change.push(change); + } else { + // Same primary key. Just find out what differs: + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + for (var idxName in oldIndexes) { + if (!newIndexes[idxName]) change.del.push(idxName); + } + for (idxName in newIndexes) { + var oldIdx = oldIndexes[idxName], + newIdx = newIndexes[idxName]; + if (!oldIdx) change.add.push(newIdx); + else if (oldIdx.src !== newIdx.src) change.change.push(newIdx); + } + if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { + diff.change.push(change); + } + } + } + } + return diff; + } + + function createTable(idbtrans, tableName, primKey, indexes) { + /// + var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); + indexes.forEach(function (idx) { addIndex(store, idx); }); + return store; + } + + function createMissingTables(newSchema, idbtrans) { + keys(newSchema).forEach(function (tableName) { + if (!idbtrans.db.objectStoreNames.contains(tableName)) { + createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); + } + }); + } + + function deleteRemovedTables(newSchema, idbtrans) { + for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) { + var storeName = idbtrans.db.objectStoreNames[i]; + if (newSchema[storeName] == null) { + idbtrans.db.deleteObjectStore(storeName); + } + } + } + + function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); + } + + function dbUncaught(err) { + return db.on.error.fire(err); + } + + // + // + // Dexie Protected API + // + // + + this._allTables = allTables; + + this._tableFactory = function createTable(mode, tableSchema) { + /// + if (mode === READONLY) + return new Table(tableSchema.name, tableSchema, Collection); + else + return new WriteableTable(tableSchema.name, tableSchema); + }; + + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { + return new Transaction(mode, storeNames, dbschema, parentTransaction); + }; + + /* Generate a temporary transaction when db operations are done outside a transactino scope. + */ + function tempTransaction(mode, storeNames, fn) { // Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it. + if (!openComplete && (!PSD.letThrough)) { + if (!isBeingOpened) { + if (!autoOpen) + return rejection(new exceptions.DatabaseClosed(), dbUncaught); + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + return dbReadyPromise.then(()=>tempTransaction(mode, storeNames, fn)); + } else { + var trans = db._createTransaction(mode, storeNames, globalSchema); + return trans._promise(mode, function (resolve, reject) { + newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise. + PSD.trans = trans; + fn(resolve, reject, trans); + }); + }).then(result => { + // Instead of resolving value directly, wait with resolving it until transaction has completed. + // Otherwise the data would not be in the DB if requesting it in the then() operation. + // Specifically, to ensure that the following expression will work: + // + // db.friends.put({name: "Arne"}).then(function () { + // db.friends.where("name").equals("Arne").count(function(count) { + // assert (count === 1); + // }); + // }); + // + return trans._completion.then(()=>result); + });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major. + trans._reject(err); + return rejection(err); + });*/ + } + } + + this._whenReady = function (fn) { + return new Promise (fake || openComplete || PSD.letThrough ? fn : (resolve, reject) => { + if (!isBeingOpened) { + if (!autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + dbReadyPromise.then(()=>{ + fn(resolve, reject); + }); + }).uncaught(dbUncaught); + }; + + // + // + // + // + // Dexie API + // + // + // + + this.verno = 0; + + this.open = function () { + if (isBeingOpened || idbdb) + return dbReadyPromise.then(()=> dbOpenError ? rejection(dbOpenError, dbUncaught) : db); + debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called. + isBeingOpened = true; + dbOpenError = null; + openComplete = false; + + // Function pointers to call when the core opening process completes. + var resolveDbReady = dbReadyResolve, + // upgradeTransaction to abort on failure. + upgradeTransaction = null; + + return Promise.race([openCanceller, new Promise((resolve, reject) => { + doFakeAutoComplete(()=>resolve()); + + // Make sure caller has specified at least one version + if (versions.length > 0) autoSchema = false; + + // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE: + // IE fails when deleting objectStore after reading from it. + // A future version of Dexie.js will stopover an intermediate version to workaround this. + // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number. + + // If no API, throw! + if (!indexedDB) throw new exceptions.MissingAPI( + "indexedDB API not found. If using IE10+, make sure to run your code on a server URL "+ + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill."); + + var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134 + req.onerror = wrap(eventRejectHandler(reject)); + req.onblocked = wrap(fireOnBlocked); + req.onupgradeneeded = wrap (function (e) { + upgradeTransaction = req.transaction; + if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail. + // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases. + // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we + // do not create a new database by accident here. + req.onerror = preventDefault; // Prohibit onabort error from firing before we're done! + upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.) + // Close database and delete it. + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here! + delreq.onsuccess = delreq.onerror = wrap(function () { + reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`)); + }); + } else { + upgradeTransaction.onerror = wrap(eventRejectHandler(reject)); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix. + runUpgraders(oldVer / 10, upgradeTransaction, reject, req); + } + }, reject); + + req.onsuccess = wrap (function () { + // Core opening procedure complete. Now let's just record some stuff. + upgradeTransaction = null; + idbdb = req.result; + connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari. + + if (autoSchema) readGlobalSchema(); + else if (idbdb.objectStoreNames.length > 0) { + try { + adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY)); + } catch (e) { + // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120. + } + } + + idbdb.onversionchange = wrap(ev => { + db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari) + db.on("versionchange").fire(ev); + }); + + if (!hasNativeGetDatabaseNames) { + // Update localStorage with list of database names + globalDatabaseList(function (databaseNames) { + if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName); + }); + } + + resolve(); + + }, reject); + })]).then(()=>{ + // Before finally resolving the dbReadyPromise and this promise, + // call and await all on('ready') subscribers: + // Dexie.vip() makes subscribers able to use the database while being opened. + // This is a must since these subscribers take part of the opening procedure. + return Dexie.vip(db.on.ready.fire); + }).then(()=>{ + // Resolve the db.open() with the db instance. + isBeingOpened = false; + return db; + }).catch(err => { + try { + // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit. + upgradeTransaction && upgradeTransaction.abort(); + } catch (e) { } + isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event). + db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh. + // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that. + dbOpenError = err; // Record the error. It will be used to reject further promises of db operations. + return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught(). + }).finally(()=>{ + openComplete = true; + resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters. + }); + }; + + this.close = function () { + var idx = connections.indexOf(db); + if (idx >= 0) connections.splice(idx, 1); + if (idbdb) { + try {idbdb.close();} catch(e){} + idbdb = null; + } + autoOpen = false; + dbOpenError = new exceptions.DatabaseClosed(); + if (isBeingOpened) + cancelOpen(dbOpenError); + // Reset dbReadyPromise promise: + dbReadyPromise = new Promise(resolve => { + dbReadyResolve = resolve; + }); + openCanceller = new Promise((_, reject) => { + cancelOpen = reject; + }); + }; + + this.delete = function () { + var hasArguments = arguments.length > 0; + return new Promise(function (resolve, reject) { + if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (isBeingOpened) { + dbReadyPromise.then(doDelete); + } else { + doDelete(); + } + function doDelete() { + db.close(); + var req = indexedDB.deleteDatabase(dbName); + req.onsuccess = wrap(function () { + if (!hasNativeGetDatabaseNames) { + globalDatabaseList(function(databaseNames) { + var pos = databaseNames.indexOf(dbName); + if (pos >= 0) return databaseNames.splice(pos, 1); + }); + } + resolve(); + }); + req.onerror = wrap(eventRejectHandler(reject)); + req.onblocked = fireOnBlocked; + } + }).uncaught(dbUncaught); + }; + + this.backendDB = function () { + return idbdb; + }; + + this.isOpen = function () { + return idbdb !== null; + }; + this.hasFailed = function () { + return dbOpenError !== null; + }; + this.dynamicallyOpened = function() { + return autoSchema; + }; + + // + // Properties + // + this.name = dbName; + + // db.tables - an array of all Table instances. + setProp(this, "tables", { + get: function () { + /// + return keys(allTables).map(function (name) { return allTables[name]; }); + } + }); + + // + // Events + // + this.on = Events(this, "error", "populate", "blocked", "versionchange", {ready: [promisableChain, nop]}); + this.on.error.subscribe = deprecated("Dexie.on.error", this.on.error.subscribe); + this.on.error.unsubscribe = deprecated("Dexie.on.error.unsubscribe", this.on.error.unsubscribe); + + this.on.ready.subscribe = override (this.on.ready.subscribe, function (subscribe) { + return (subscriber, bSticky) => { + Dexie.vip(()=>{ + if (openComplete) { + // Database already open. Call subscriber asap. + if (!dbOpenError) Promise.resolve().then(subscriber); + // bSticky: Also subscribe to future open sucesses (after close / reopen) + if (bSticky) subscribe(subscriber); + } else { + // Database not yet open. Subscribe to it. + subscribe(subscriber); + // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. + if (!bSticky) subscribe(function unsubscribe() { + db.on.ready.unsubscribe(subscriber); + db.on.ready.unsubscribe(unsubscribe); + }); + } + }); + } + }); + + fakeAutoComplete(function () { + db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema)); + db.on("error").fire(new Error()); + }); + + this.transaction = function (mode, tableInstances, scopeFunc) { + /// + /// + /// + /// "r" for readonly, or "rw" for readwrite + /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction + /// Function to execute with transaction + + // Let table arguments be all arguments between mode and last argument. + var i = arguments.length; + if (i < 2) throw new exceptions.InvalidArgument("Too few arguments"); + // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments) + // and clone arguments except the first one into local var 'args'. + var args = new Array(i - 1); + while (--i) args[i-1] = arguments[i]; + // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments. + scopeFunc = args.pop(); + var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays. + var parentTransaction = PSD.trans; + // Check if parent transactions is bound to this db instance, and if caller wants to reuse it + if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. + + try { + // + // Get storeNames from arguments. Either through given table instances, or through given table names. + // + var storeNames = tables.map(table => { + var storeName = table instanceof Table ? table.name : table; + if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); + return storeName; + }); + + // + // Resolve mode. Allow shortcuts "r" and "rw". + // + if (mode == "r" || mode == READONLY) + mode = READONLY; + else if (mode == "rw" || mode == READWRITE) + mode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + + if (parentTransaction) { + // Basic checks + if (parentTransaction.mode === READONLY && mode === READWRITE) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } + else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); + } + if (parentTransaction) { + storeNames.forEach(function (storeName) { + if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } + else throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + } + } catch (e) { + return parentTransaction ? + parentTransaction._promise(null, (_, reject) => {reject(e);}) : + rejection (e, dbUncaught); + } + // If this is a sub-transaction, lock the parent and then launch the sub-transaction. + return (parentTransaction ? + parentTransaction._promise(mode, enterTransactionScope, "lock") : + db._whenReady (enterTransactionScope)); + + function enterTransactionScope(resolve) { + var parentPSD = PSD; + resolve(Promise.resolve().then(()=>newScope(()=>{ + // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction(). + PSD.transless = PSD.transless || parentPSD; + // Our transaction. + //return new Promise((resolve, reject) => { + var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction); + // Let the transaction instance be part of a Promise-specific data (PSD) value. + PSD.trans = trans; + + + if (parentTransaction) { + // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing) + trans.idbtrans = parentTransaction.idbtrans; + } else { + trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it. + } + + // Provide arguments to the scope function (for backward compatibility) + var tableArgs = storeNames.map(function (name) { return allTables[name]; }); + tableArgs.push(trans); + + var returnValue; + return Promise.follow(()=>{ + // Finally, call the scope function with our table and transaction arguments. + returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func. + if (returnValue) { + if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + // scopeFunc returned an iterator with throw-support. Handle yield as await. + returnValue = awaitIterator(returnValue); + } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) { + throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: " + scopeFunc.toString()); + } + } + }).uncaught(dbUncaught).then(()=>{ + if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion. + return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well. + }).then(()=>{ + return returnValue; + }).catch (e => { + //reject(e); + trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc! + return rejection(e); + }); + //}); + }))); + } + }; + + this.table = function (tableName) { + /// + if (fake && autoSchema) return new WriteableTable(tableName); + if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); } + return allTables[tableName]; + }; + + // + // + // + // Table Class + // + // + // + function Table(name, tableSchema, collClass) { + /// + this.name = name; + this.schema = tableSchema; + this.hook = allTables[name] ? allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + this._collClass = collClass || Collection; + } + + props(Table.prototype, { + + // + // Table Protected Methods + // + + _trans: function getTransaction(mode, fn, writeLocked) { + var trans = PSD.trans; + return trans && trans.db === db ? + trans._promise (mode, fn, writeLocked) : + tempTransaction (mode, [this.name], fn); + }, + _idbstore: function getIDBObjectStore(mode, fn, writeLocked) { + if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion. + var trans = PSD.trans, + tableName = this.name; + function supplyIdbStore (resolve, reject, trans) { + fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans); + } + return trans && trans.db === db ? + trans._promise (mode, supplyIdbStore, writeLocked) : + tempTransaction (mode, [this.name], supplyIdbStore); + }, + + // + // Table Public Methods + // + get: function (key, cb) { + var self = this; + return this._idbstore(READONLY, function (resolve, reject, idbstore) { + fake && resolve(self.schema.instanceTemplate); + var req = idbstore.get(key); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(self.hook.reading.fire(req.result)); + }, reject); + }).then(cb); + }, + where: function (indexName) { + return new WhereClause(this, indexName); + }, + count: function (cb) { + return this.toCollection().count(cb); + }, + offset: function (offset) { + return this.toCollection().offset(offset); + }, + limit: function (numRows) { + return this.toCollection().limit(numRows); + }, + reverse: function () { + return this.toCollection().reverse(); + }, + filter: function (filterFunction) { + return this.toCollection().and(filterFunction); + }, + each: function (fn) { + return this.toCollection().each(fn); + }, + toArray: function (cb) { + return this.toCollection().toArray(cb); + }, + orderBy: function (index) { + return new this._collClass(new WhereClause(this, index)); + }, + + toCollection: function () { + return new this._collClass(new WhereClause(this)); + }, + + mapToClass: function (constructor, structure) { + /// + /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making + /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}. + /// + /// Constructor function representing the class. + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], password} + this.schema.mappedClass = constructor; + var instanceTemplate = Object.create(constructor.prototype); + if (structure) { + // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance. + applyStructure(instanceTemplate, structure); + } + this.schema.instanceTemplate = instanceTemplate; + + // Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class + // no matter which method to use for reading (Table.get() or Table.where(...)... ) + var readHook = function (obj) { + if (!obj) return obj; // No valid object. (Value is null). Return as is. + // Create a new object that derives from constructor: + var res = Object.create(constructor.prototype); + // Clone members: + for (var m in obj) if (hasOwn(obj, m)) try {res[m] = obj[m];} catch(_){} + return res; + }; + + if (this.schema.readHook) { + this.hook.reading.unsubscribe(this.schema.readHook); + } + this.schema.readHook = readHook; + this.hook("reading", readHook); + return constructor; + }, + defineClass: function (structure) { + /// + /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database + /// as well as making it possible to extend the prototype of the returned constructor function. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + return this.mapToClass(Dexie.defineClass(structure), structure); + } + }); + + // + // + // + // WriteableTable Class (extends Table) + // + // + // + function WriteableTable(name, tableSchema, collClass) { + Table.call(this, name, tableSchema, collClass || WriteableCollection); + } + + function BulkErrorHandlerCatchAll(errorList, done, supportHooks) { + return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => { + errorList.push(e); + done && done(); + }); + } + + function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) { + // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...], + // else keysOrTuples must be just an array of keys: [key1, key2, ...]. + return new Promise((resolve, reject)=>{ + var len = keysOrTuples.length, + lastItem = len - 1; + if (len === 0) return resolve(); + if (!hasDeleteHook) { + for (var i=0; i < len; ++i) { + var req = idbstore.delete(keysOrTuples[i]); + req.onerror = wrap(eventRejectHandler(reject)); + if (i === lastItem) req.onsuccess = wrap(()=>resolve()); + } + } else { + var hookCtx, + errorHandler = hookedEventRejectHandler(reject), + successHandler = hookedEventSuccessHandler(null); + tryCatch(()=> { + for (var i = 0; i < len; ++i) { + hookCtx = {onsuccess: null, onerror: null}; + var tuple = keysOrTuples[i]; + deletingHook.call(hookCtx, tuple[0], tuple[1], trans); + var req = idbstore.delete(tuple[0]); + req._hookCtx = hookCtx; + req.onerror = errorHandler; + if (i === lastItem) + req.onsuccess = hookedEventSuccessHandler(resolve); + else + req.onsuccess = successHandler; + } + }, err=>{ + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + } + }).uncaught(dbUncaught); + } + + derive(WriteableTable).from(Table).extend({ + bulkDelete: function (keys$$1) { + if (this.hook.deleting.fire === nop) { + return this._idbstore(READWRITE, (resolve, reject, idbstore, trans) => { + resolve (bulkDelete(idbstore, trans, keys$$1, false, nop)); + }); + } else { + return this + .where(':id') + .anyOf(keys$$1) + .delete() + .then(()=>{}); // Resolve with undefined. + } + }, + bulkPut: function(objects, keys$$1) { + return this._idbstore(READWRITE, (resolve, reject, idbstore) => { + if (!idbstore.keyPath && !this.schema.primKey.auto && !keys$$1) + throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) return resolve(); // Caller provided empty list. + const done = result => { + if (errorList.length === 0) resolve(result); + else reject(new BulkError(`${this.name}.bulkPut(): ${errorList.length} of ${numObjs} operations failed`, errorList)); + }; + var req, + errorList = [], + errorHandler, + numObjs = objects.length, + table = this; + if (this.hook.creating.fire === nop && this.hook.updating.fire === nop) { + // + // Standard Bulk (no 'creating' or 'updating' hooks to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } else { + var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(o=>getByKeyPath(o, idbstore.keyPath)); + // Generate map of {[key]: object} + var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, (key, i) => key != null && [key, objects[i]]); + var promise = !effectiveKeys ? + + // Auto-incremented key-less objects only without any keys argument. + table.bulkAdd(objects) : + + // Keys provided. Either as inbound in provided objects, or as a keys argument. + // Begin with updating those that exists in DB: + table.where(':id').anyOf(effectiveKeys.filter(key => key != null)).modify(function () { + this.value = objectLookup[this.primKey]; + objectLookup[this.primKey] = null; // Mark as "don't add this" + }).catch(ModifyError, e => { + errorList = e.failures; // No need to concat here. These are the first errors added. + }).then(()=> { + // Now, let's examine which items didnt exist so we can add them: + var objsToAdd = [], + keysToAdd = keys$$1 && []; + // Iterate backwards. Why? Because if same key was used twice, just add the last one. + for (var i=effectiveKeys.length-1; i>=0; --i) { + var key = effectiveKeys[i]; + if (key == null || objectLookup[key]) { + objsToAdd.push(objects[i]); + keys$$1 && keysToAdd.push(key); + if (key != null) objectLookup[key] = null; // Mark as "dont add again" + } + } + // The items are in reverse order so reverse them before adding. + // Could be important in order to get auto-incremented keys the way the caller + // would expect. Could have used unshift instead of push()/reverse(), + // but: http://jsperf.com/unshift-vs-reverse + objsToAdd.reverse(); + keys$$1 && keysToAdd.reverse(); + return table.bulkAdd(objsToAdd, keysToAdd); + }).then(lastAddedKey => { + // Resolve with key of the last object in given arguments to bulkPut(): + var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided. + return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey; + }); + + promise.then(done).catch(BulkError, e => { + // Concat failure from ModifyError and reject using our 'done' method. + errorList = errorList.concat(e.failures); + done(); + }).catch(reject); + } + }, "locked"); // If called from transaction scope, lock transaction til all steps are done. + }, + bulkAdd: function(objects, keys$$1) { + var self = this, + creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) + throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) return resolve(); // Caller provided empty list. + function done(result) { + if (errorList.length === 0) resolve(result); + else reject(new BulkError(`${self.name}.bulkAdd(): ${errorList.length} of ${numObjs} operations failed`, errorList)); + } + var req, + errorList = [], + errorHandler, + successHandler, + numObjs = objects.length; + if (creatingHook !== nop) { + // + // There are subscribers to hook('creating') + // Must behave as documented. + // + var keyPath = idbstore.keyPath, + hookCtx; + errorHandler = BulkErrorHandlerCatchAll(errorList, null, true); + successHandler = hookedEventSuccessHandler(null); + + tryCatch(() => { + for (var i=0, l = objects.length; i < l; ++i) { + hookCtx = { onerror: null, onsuccess: null }; + var key = keys$$1 && keys$$1[i]; + var obj = objects[i], + effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined, + keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); + if (effectiveKey == null && keyToUse != null) { + if (keyPath) { + obj = deepClone(obj); + setByKeyPath(obj, keyPath, keyToUse); + } else { + key = keyToUse; + } + } + req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + if (i < l - 1) { + req.onerror = errorHandler; + if (hookCtx.onsuccess) + req.onsuccess = successHandler; + } + } + }, err => { + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + + req.onerror = BulkErrorHandlerCatchAll(errorList, done, true); + req.onsuccess = hookedEventSuccessHandler(done); + } else { + // + // Standard Bulk (no 'creating' hook to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } + }); + }, + add: function (obj, key) { + /// + /// Add an object to the database. In case an object with same primary key already exists, the object will not be added. + /// + /// A javascript object to insert + /// Primary key + var creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + var hookCtx = {onsuccess: null, onerror: null}; + if (creatingHook !== nop) { + var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined); + var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key. + if (effectiveKey == null && keyToUse != null) { // Using "==" and "!=" to check for either null or undefined! + if (idbstore.keyPath) + setByKeyPath(obj, idbstore.keyPath, keyToUse); + else + key = keyToUse; + } + } + try { + var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + req.onerror = hookedEventRejectHandler(reject); + req.onsuccess = hookedEventSuccessHandler(function (result) { + // TODO: Remove these two lines in next major release (2.0?) + // It's no good practice to have side effects on provided parameters + var keyPath = idbstore.keyPath; + if (keyPath) setByKeyPath(obj, keyPath, result); + resolve(result); + }); + } catch (e) { + if (hookCtx.onerror) hookCtx.onerror(e); + throw e; + } + }); + }, + + put: function (obj, key) { + /// + /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated. + /// + /// A javascript object to insert or update + /// Primary key + var self = this, + creatingHook = this.hook.creating.fire, + updatingHook = this.hook.updating.fire; + if (creatingHook !== nop || updatingHook !== nop) { + // + // People listens to when("creating") or when("updating") events! + // We must know whether the put operation results in an CREATE or UPDATE. + // + return this._trans(READWRITE, function (resolve, reject, trans) { + // Since key is optional, make sure we get it from obj if not provided + var effectiveKey = (key !== undefined) ? key : (self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath)); + if (effectiveKey == null) { // "== null" means checking for either null or undefined. + // No primary key. Must use add(). + self.add(obj).then(resolve, reject); + } else { + // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add(). + trans._lock(); // Needed because operation is splitted into modify() and add(). + // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation. + obj = deepClone(obj); + self.where(":id").equals(effectiveKey).modify(function () { + // Replace extisting value with our object + // CRUD event firing handled in WriteableCollection.modify() + this.value = obj; + }).then(function (count) { + if (count === 0) { + // Object's key was not found. Add the object instead. + // CRUD event firing will be done in add() + return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key. + } else { + return effectiveKey; // Resolve with the provided key. + } + }).finally(function () { + trans._unlock(); + }).then(resolve, reject); + } + }); + } else { + // Use the standard IDB put() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function (ev) { + var keyPath = idbstore.keyPath; + if (keyPath) setByKeyPath(obj, keyPath, ev.target.result); + resolve(req.result); + }; + }); + } + }, + + 'delete': function (key) { + /// Primary key of the object to delete + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will + // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted. + return this.where(":id").equals(key).delete(); + } else { + // No one listens. Use standard IDB delete() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.delete(key); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function () { + resolve(req.result); + }; + }); + } + }, + + clear: function () { + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will + // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted. + return this.toCollection().delete(); + } else { + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.clear(); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function () { + resolve(req.result); + }; + }); + } + }, + + update: function (keyOrObject, modifications) { + if (typeof modifications !== 'object' || isArray(modifications)) + throw new exceptions.InvalidArgument("Modifications must be an object."); + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + // object to modify. Also modify given object with the modifications: + keys(modifications).forEach(function (keyPath) { + setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); + }); + var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === undefined) return rejection(new exceptions.InvalidArgument( + "Given object does not contain its primary key"), dbUncaught); + return this.where(":id").equals(key).modify(modifications); + } else { + // key to modify + return this.where(":id").equals(keyOrObject).modify(modifications); + } + } + }); + + // + // + // + // Transaction Class + // + // + // + function Transaction(mode, storeNames, dbschema, parent) { + /// + /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction. + /// + /// Any of "readwrite" or "readonly" + /// Array of table names to operate on + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.idbtrans = null; + this.on = Events(this, "complete", "error", "abort"); + this.parent = parent || null; + this.active = true; + this._tables = null; + this._reculock = 0; + this._blockedFuncs = []; + this._psd = null; + this._dbschema = dbschema; + this._resolve = null; + this._reject = null; + this._completion = new Promise ((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }).uncaught(dbUncaught); + + this._completion.then( + ()=> {this.on.complete.fire();}, + e => { + this.on.error.fire(e); + this.parent ? + this.parent._reject(e) : + this.active && this.idbtrans && this.idbtrans.abort(); + this.active = false; + return rejection(e); // Indicate we actually DO NOT catch this error. + }); + } + + props(Transaction.prototype, { + // + // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions) + // + _lock: function () { + assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + // Temporary set all requests into a pending queue if they are called before database is ready. + ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage) + if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this; + return this; + }, + _unlock: function () { + assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + if (--this._reculock === 0) { + if (!PSD.global) PSD.lockOwnerFor = null; + while (this._blockedFuncs.length > 0 && !this._locked()) { + var fn = this._blockedFuncs.shift(); + try { fn(); } catch (e) { } + } + } + return this; + }, + _locked: function () { + // Checks if any write-lock is applied on this transaction. + // To simplify the Dexie API for extension implementations, we support recursive locks. + // This is accomplished by using "Promise Specific Data" (PSD). + // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ). + // PSD is local to code executing on top of the call stacks of any of any code executed by Promise(): + // * callback given to the Promise() constructor (function (resolve, reject){...}) + // * callbacks given to then()/catch()/finally() methods (function (value){...}) + // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise. + // Derivation is done so that the inner PSD __proto__ points to the outer PSD. + // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock. + return this._reculock && PSD.lockOwnerFor !== this; + }, + create: function (idbtrans) { + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()! + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + + idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode); + idbtrans.onerror = wrap(ev => { + preventDefault(ev);// Prohibit default bubbling to window.error + this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(ev => { + preventDefault(ev); + this.active && this._reject(new exceptions.Abort()); + this.active = false; + this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(() => { + this.active = false; + this._resolve(); + }); + return this; + }, + _promise: function (mode, fn, bWriteLock) { + var self = this; + return newScope(function() { + var p; + // Read lock always + if (!self._locked()) { + p = self.active ? new Promise(function (resolve, reject) { + if (mode === READWRITE && self.mode !== READWRITE) + throw new exceptions.ReadOnly("Transaction is readonly"); + if (!self.idbtrans && mode) self.create(); + if (bWriteLock) self._lock(); // Write lock if write operation is requested + fn(resolve, reject, self); + }) : rejection(new exceptions.TransactionInactive()); + if (self.active && bWriteLock) p.finally(function () { + self._unlock(); + }); + } else { + // Transaction is write-locked. Wait for mutex. + p = new Promise(function (resolve, reject) { + self._blockedFuncs.push(function () { + self._promise(mode, fn, bWriteLock).then(resolve, reject); + }); + }); + } + p._lib = true; + return p.uncaught(dbUncaught); + }); + }, + + // + // Transaction Public Properties and Methods + // + abort: function () { + this.active && this._reject(new exceptions.Abort()); + this.active = false; + }, + + tables: { + get: deprecated ("Transaction.tables", function () { + return arrayToObject(this.storeNames, name => [name, allTables[name]]); + }, "Use db.tables()") + }, + + complete: deprecated ("Transaction.complete()", function (cb) { + return this.on("complete", cb); + }), + + error: deprecated ("Transaction.error()", function (cb) { + return this.on("error", cb); + }), + + table: deprecated ("Transaction.table()", function (name) { + if (this.storeNames.indexOf(name) === -1) + throw new exceptions.InvalidTable("Table " + name + " not in transaction"); + return allTables[name]; + }) + + }); + + // + // + // + // WhereClause + // + // + // + function WhereClause(table, index, orCollection) { + /// + /// + /// + this._ctx = { + table: table, + index: index === ":id" ? null : index, + collClass: table._collClass, + or: orCollection + }; + } + + props(WhereClause.prototype, function () { + + // WhereClause private methods + + function fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : + collectionOrWhereClause; + + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; + } + + function emptyCollection(whereClause) { + return new whereClause._ctx.collClass(whereClause, function() { return IDBKeyRange.only(""); }).limit(0); + } + + function upperFactory(dir) { + return dir === "next" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); }; + } + function lowerFactory(dir) { + return dir === "next" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); }; + } + function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { + var length = Math.min(key.length, lowerNeedle.length); + var llp = -1; + for (var i = 0; i < length; ++i) { + var lwrKeyChar = lowerKey[i]; + if (lwrKeyChar !== lowerNeedle[i]) { + if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); + if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); + if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); + return null; + } + if (cmp(key[i], lwrKeyChar) < 0) llp = i; + } + if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length); + if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length); + return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1)); + } + + function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { + /// + var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, + needlesLen = needles.length; + if (!needles.every(s => typeof s === 'string')) { + return fail(whereClause, STRING_EXPECTED); + } + function initDirection(dir) { + upper = upperFactory(dir); + lower = lowerFactory(dir); + compare = (dir === "next" ? simpleCompare : simpleCompareReverse); + var needleBounds = needles.map(function (needle){ + return {lower: lower(needle), upper: upper(needle)}; + }).sort(function(a,b) { + return compare(a.lower, b.lower); + }); + upperNeedles = needleBounds.map(function (nb){ return nb.upper; }); + lowerNeedles = needleBounds.map(function (nb){ return nb.lower; }); + direction = dir; + nextKeySuffix = (dir === "next" ? "" : suffix); + } + initDirection("next"); + + var c = new whereClause._ctx.collClass(whereClause, function() { + return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix); + }); + + c._ondirectionchange = function (direction) { + // This event onlys occur before filter is called the first time. + initDirection(direction); + }; + + var firstPossibleNeedle = 0; + + c._addAlgorithm(function (cursor, advance, resolve) { + /// + /// + /// + var key = cursor.key; + if (typeof key !== 'string') return false; + var lowerKey = lower(key); + if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { + return true; + } else { + var lowestPossibleCasing = null; + for (var i=firstPossibleNeedle; i 0) { + lowestPossibleCasing = casing; + } + } + if (lowestPossibleCasing !== null) { + advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); + } else { + advance(resolve); + } + return false; + } + }); + return c; + } + + // + // WhereClause public methods + // + return { + between: function (lower, upper, includeLower, includeUpper) { + /// + /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates. + /// + /// + /// + /// Whether items that equals lower should be included. Default true. + /// Whether items that equals upper should be included. Default false. + /// + includeLower = includeLower !== false; // Default to true + includeUpper = includeUpper === true; // Default to false + try { + if ((cmp(lower, upper) > 0) || + (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection. + return new this._ctx.collClass(this, function() { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); }); + } catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }, + equals: function (value) { + return new this._ctx.collClass(this, function() { return IDBKeyRange.only(value); }); + }, + above: function (value) { + return new this._ctx.collClass(this, function() { return IDBKeyRange.lowerBound(value, true); }); + }, + aboveOrEqual: function (value) { + return new this._ctx.collClass(this, function() { return IDBKeyRange.lowerBound(value); }); + }, + below: function (value) { + return new this._ctx.collClass(this, function() { return IDBKeyRange.upperBound(value, true); }); + }, + belowOrEqual: function (value) { + return new this._ctx.collClass(this, function() { return IDBKeyRange.upperBound(value); }); + }, + startsWith: function (str) { + /// + if (typeof str !== 'string') return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }, + startsWithIgnoreCase: function (str) { + /// + if (str === "") return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); + }, + equalsIgnoreCase: function (str) { + /// + return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); + }, + anyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); + }, + startsWithAnyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { + return a.some(function(n){ + return x.indexOf(n) === 0; + });}, set, maxString); + }, + anyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = ascending; + try { set.sort(compare); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT); } + if (set.length === 0) return emptyCollection(this); + var c = new this._ctx.collClass(this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); }); + + c._ondirectionchange = function (direction) { + compare = (direction === "next" ? ascending : descending); + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function () { cursor.continue(set[i]); }); + return false; + } + }); + return c; + }, + + notEqual: function(value) { + return this.inAnyRange([[-Infinity, value],[value, maxKey]], {includeLowers: false, includeUppers: false}); + }, + + noneOf: function() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection. + try { set.sort(ascending); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT);} + // Transform ["a","b","c"] to a set of ranges for between/above/below: [[-Infinity,"a"], ["a","b"], ["b","c"], ["c",maxKey]] + var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]]; }, null); + ranges.push([set[set.length - 1], maxKey]); + return this.inAnyRange(ranges, {includeLowers: false, includeUppers: false}); + }, + + /** Filter out values withing given set of ranges. + * Example, give children and elders a rebate of 50%: + * + * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2}); + * + * @param {(string|number|Date|Array)[][]} ranges + * @param {{includeLowers: boolean, includeUppers: boolean}} options + */ + inAnyRange: function (ranges, options) { + var ctx = this._ctx; + if (ranges.length === 0) return emptyCollection(this); + if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;})) { + return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); + } + var includeLowers = !options || options.includeLowers !== false; // Default to true + var includeUppers = options && options.includeUppers === true; // Default to false + + function addRange (ranges, newRange) { + for (var i=0,l=ranges.length;i 0) { + range[0] = min(range[0], newRange[0]); + range[1] = max(range[1], newRange[1]); + break; + } + } + if (i === l) + ranges.push(newRange); + return ranges; + } + + var sortDirection = ascending; + function rangeSorter(a,b) { return sortDirection(a[0], b[0]);} + + // Join overlapping ranges + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } catch(ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + + var i = 0; + var keyIsBeyondCurrentEntry = includeUppers ? + function(key) { return ascending(key, set[i][1]) > 0; } : + function(key) { return ascending(key, set[i][1]) >= 0; }; + + var keyIsBeforeCurrentEntry = includeLowers ? + function(key) { return descending(key, set[i][0]) > 0; } : + function(key) { return descending(key, set[i][0]) >= 0; }; + + function keyWithinCurrentRange (key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + + var checkKey = keyIsBeyondCurrentEntry; + + var c = new ctx.collClass(this, function () { + return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); + }); + + c._ondirectionchange = function (direction) { + if (direction === "next") { + checkKey = keyIsBeyondCurrentEntry; + sortDirection = ascending; + } else { + checkKey = keyIsBeforeCurrentEntry; + sortDirection = descending; + } + set.sort(rangeSorter); + }; + + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (checkKey(key)) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } else if (cmp(key,set[i][1]) === 0 || cmp(key,set[i][0]) === 0) { + // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border. + // Continue to next key but don't include this one. + return false; + } else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function() { + if (sortDirection === ascending) cursor.continue(set[i][0]); + else cursor.continue(set[i][1]); + }); + return false; + } + }); + return c; + }, + startsWithAnyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + + if (!set.every(function (s) { return typeof s === 'string'; })) { + return fail(this, "startsWithAnyOf() only works with strings"); + } + if (set.length === 0) return emptyCollection(this); + + return this.inAnyRange(set.map(function(str) { + return [str, str + maxString]; + })); + } + }; + }); + + + + + // + // + // + // Collection Class + // + // + // + function Collection(whereClause, keyRangeGenerator) { + /// + /// + /// + /// Where clause instance + /// + var keyRange = null, error = null; + if (keyRangeGenerator) try { + keyRange = keyRangeGenerator(); + } catch (ex) { + error = ex; + } + + var whereCtx = whereClause._ctx, + table = whereCtx.table; + this._ctx = { + table: table, + index: whereCtx.index, + isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)), + range: keyRange, + keysOnly: false, + dir: "next", + unique: "", + algorithm: null, + filter: null, + replayFilter: null, + justLimit: true, // True if a replayFilter is just a filter that performs a "limit" operation (or none at all) + isMatch: null, + offset: 0, + limit: Infinity, + error: error, // If set, any promise must be rejected with this error + or: whereCtx.or, + valueMapper: table.hook.reading.fire + }; + } + + function isPlainKeyRange (ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); + } + + props(Collection.prototype, function () { + + // + // Collection Private Functions + // + + function addFilter(ctx, fn) { + ctx.filter = combine(ctx.filter, fn); + } + + function addReplayFilter (ctx, factory, isLimitFilter) { + var curr = ctx.replayFilter; + ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory; + ctx.justLimit = isLimitFilter && !curr; + } + + function addMatchFilter(ctx, fn) { + ctx.isMatch = combine(ctx.isMatch, fn); + } + + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string + * } + * @param store IDBObjectStore + **/ + function getIndexOrStore(ctx, store) { + if (ctx.isPrimKey) return store; + var indexSpec = ctx.table.schema.idxByName[ctx.index]; + if (!indexSpec) throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed"); + return store.index(indexSpec.name); + } + + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string, + * keysOnly: boolean, + * range?: IDBKeyRange, + * dir: "next" | "prev" + * } + */ + function openCursor(ctx, store) { + var idxOrStore = getIndexOrStore(ctx, store); + return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? + idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : + idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique); + } + + function iter(ctx, fn, resolve, reject, idbstore) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper); + } else (()=>{ + var set = {}; + var resolved = 0; + + function resolveboth() { + if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion. + } + + function union(item, cursor, advance) { + if (!filter || filter(cursor, advance, resolveboth, reject)) { + var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string + if (!hasOwn(set, key)) { + set[key] = true; + fn(item, cursor, advance); + } + } + } + + ctx.or._iterate(union, resolveboth, reject, idbstore); + iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper); + })(); + } + function getInstanceTemplate(ctx) { + return ctx.table.schema.instanceTemplate; + } + + return { + + // + // Collection Protected Functions + // + + _read: function (fn, cb) { + var ctx = this._ctx; + if (ctx.error) + return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); }); + else + return ctx.table._idbstore(READONLY, fn).then(cb); + }, + _write: function (fn) { + var ctx = this._ctx; + if (ctx.error) + return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); }); + else + return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued. + }, + _addAlgorithm: function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }, + + _iterate: function (fn, resolve, reject, idbstore) { + return iter(this._ctx, fn, resolve, reject, idbstore); + }, + + clone: function (props$$1) { + var rv = Object.create(this.constructor.prototype), + ctx = Object.create(this._ctx); + if (props$$1) extend(ctx, props$$1); + rv._ctx = ctx; + return rv; + }, + + raw: function () { + this._ctx.valueMapper = null; + return this; + }, + + // + // Collection Public methods + // + + each: function (fn) { + var ctx = this._ctx; + + if (fake) { + var item = getInstanceTemplate(ctx), + primKeyPath = ctx.table.schema.primKey.keyPath, + key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath), + primaryKey = getByKeyPath(item, primKeyPath); + fn(item, {key: key, primaryKey: primaryKey}); + } + + return this._read(function (resolve, reject, idbstore) { + iter(ctx, fn, resolve, reject, idbstore); + }); + }, + + count: function (cb) { + if (fake) return Promise.resolve(0).then(cb); + var ctx = this._ctx; + + if (isPlainKeyRange(ctx, true)) { + // This is a plain key range. We can use the count() method if the index. + return this._read(function (resolve, reject, idbstore) { + var idx = getIndexOrStore(ctx, idbstore); + var req = (ctx.range ? idx.count(ctx.range) : idx.count()); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function (e) { + resolve(Math.min(e.target.result, ctx.limit)); + }; + }, cb); + } else { + // Algorithms, filters or expressions are applied. Need to count manually. + var count = 0; + return this._read(function (resolve, reject, idbstore) { + iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore); + }, cb); + } + }, + + sortBy: function (keyPath, cb) { + /// + var parts = keyPath.split('.').reverse(), + lastPart = parts[0], + lastIndex = parts.length - 1; + function getval(obj, i) { + if (i) return getval(obj[parts[i]], i - 1); + return obj[lastPart]; + } + var order = this._ctx.dir === "next" ? 1 : -1; + + function sorter(a, b) { + var aVal = getval(a, lastIndex), + bVal = getval(b, lastIndex); + return aVal < bVal ? -order : aVal > bVal ? order : 0; + } + return this.toArray(function (a) { + return a.sort(sorter); + }).then(cb); + }, + + toArray: function (cb) { + var ctx = this._ctx; + return this._read(function (resolve, reject, idbstore) { + fake && resolve([getInstanceTemplate(ctx)]); + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAll() or + // IDBKeyRange.getAll(): + var readingHook = ctx.table.hook.reading.fire; + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? + idxOrStore.getAll(ctx.range, ctx.limit) : + idxOrStore.getAll(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = readingHook === mirror ? + eventSuccessHandler(resolve) : + wrap(eventSuccessHandler(res => { + try {resolve (res.map(readingHook));} catch(e) {reject(e);} + })); + } else { + // Getting array through a cursor. + var a = []; + iter(ctx, function (item) { a.push(item); }, function arrayComplete() { + resolve(a); + }, reject, idbstore); + } + }, cb); + }, + + offset: function (offset) { + var ctx = this._ctx; + if (offset <= 0) return this; + ctx.offset += offset; // For count() + if (isPlainKeyRange(ctx)) { + addReplayFilter(ctx, ()=> { + var offsetLeft = offset; + return (cursor, advance) => { + if (offsetLeft === 0) return true; + if (offsetLeft === 1) { --offsetLeft; return false; } + advance(()=> { + cursor.advance(offsetLeft); + offsetLeft = 0; + }); + return false; + }; + }); + } else { + addReplayFilter(ctx, ()=> { + var offsetLeft = offset; + return () => (--offsetLeft < 0); + }); + } + return this; + }, + + limit: function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count() + addReplayFilter(this._ctx, ()=> { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included + return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here. + }; + }, true); + return this; + }, + + until: function (filterFunction, bIncludeStopEntry) { + var ctx = this._ctx; + fake && filterFunction(getInstanceTemplate(ctx)); + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } else { + return true; + } + }); + return this; + }, + + first: function (cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + }, + + last: function (cb) { + return this.reverse().first(cb); + }, + + filter: function (filterFunction) { + /// function(val){return true/false} + fake && filterFunction(getInstanceTemplate(this._ctx)); + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + // match filters not used in Dexie.js but can be used by 3rd part libraries to test a + // collection for a match without querying DB. Used by Dexie.Observable. + addMatchFilter(this._ctx, filterFunction); + return this; + }, + + and: function (filterFunction) { + return this.filter(filterFunction); + }, + + or: function (indexName) { + return new WhereClause(this._ctx.table, indexName, this); + }, + + reverse: function () { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir); + return this; + }, + + desc: function () { + return this.reverse(); + }, + + eachKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + }, + + eachUniqueKey: function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }, + + eachPrimaryKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + }, + + keys: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.key); + }).then(function () { + return a; + }).then(cb); + }, + + primaryKeys: function (cb) { + var ctx = this._ctx; + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAllKeys() or + // IDBKeyRange.getAllKeys(): + return this._read((resolve, reject, idbstore) =>{ + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? + idxOrStore.getAllKeys(ctx.range, ctx.limit) : + idxOrStore.getAllKeys(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = eventSuccessHandler(resolve); + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }, + + uniqueKeys: function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }, + + firstKey: function (cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + }, + + lastKey: function (cb) { + return this.reverse().firstKey(cb); + }, + + distinct: function () { + var ctx = this._ctx, + idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes. + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + } + }; + }); + + // + // + // WriteableCollection Class + // + // + function WriteableCollection() { + Collection.apply(this, arguments); + } + + derive(WriteableCollection).from(Collection).extend({ + + // + // WriteableCollection Public Methods + // + + modify: function (changes) { + var self = this, + ctx = this._ctx, + hook = ctx.table.hook, + updatingHook = hook.updating.fire, + deletingHook = hook.deleting.fire; + + fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate); + + return this._write(function (resolve, reject, idbstore, trans) { + var modifyer; + if (typeof changes === 'function') { + // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item) + if (updatingHook === nop && deletingHook === nop) { + // Noone cares about what is being changed. Just let the modifier function be the given argument as is. + modifyer = changes; + } else { + // People want to know exactly what is being modified or deleted. + // Let modifyer be a proxy function that finds out what changes the caller is actually doing + // and call the hooks accordingly! + modifyer = function (item) { + var origItem = deepClone(item); // Clone the item first so we can compare laters. + if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object) + if (!hasOwn(this, "value")) { + // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place. + deletingHook.call(this, this.primKey, item, trans); + } else { + // No deletion. Check what was changed + var objectDiff = getObjectDiff(origItem, this.value); + var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans); + if (additionalChanges) { + // Hook want to apply additional modifications. Make sure to fullfill the will of the hook. + item = this.value; + keys(additionalChanges).forEach(function (keyPath) { + setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + }); + } + } + }; + } + } else if (updatingHook === nop) { + // changes is a set of {keyPath: value} and no one is listening to the updating hook. + var keyPaths = keys(changes); + var numKeys = keyPaths.length; + modifyer = function (item) { + var anythingModified = false; + for (var i = 0; i < numKeys; ++i) { + var keyPath = keyPaths[i], val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + anythingModified = true; + } + } + return anythingModified; + }; + } else { + // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and + // allow it to add additional modifications to make. + var origChanges = changes; + changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it. + modifyer = function (item) { + var anythingModified = false; + var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans); + if (additionalChanges) extend(changes, additionalChanges); + keys(changes).forEach(function (keyPath) { + var val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); + anythingModified = true; + } + }); + if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration + return anythingModified; + }; + } + + var count = 0; + var successCount = 0; + var iterationComplete = false; + var failures = []; + var failKeys = []; + var currentKey = null; + + function modifyItem(item, cursor) { + currentKey = cursor.primaryKey; + var thisContext = { + primKey: cursor.primaryKey, + value: item, + onsuccess: null, + onerror: null + }; + + function onerror(e) { + failures.push(e); + failKeys.push(thisContext.primKey); + checkFinished(); + return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction + } + + if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update! + var bDelete = !hasOwn(thisContext, "value"); + ++count; + tryCatch(function () { + var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value)); + req._hookCtx = thisContext; + req.onerror = hookedEventRejectHandler(onerror); + req.onsuccess = hookedEventSuccessHandler(function () { + ++successCount; + checkFinished(); + }); + }, onerror); + } else if (thisContext.onsuccess) { + // Hook will expect either onerror or onsuccess to always be called! + thisContext.onsuccess(thisContext.value); + } + } + + function doReject(e) { + if (e) { + failures.push(e); + failKeys.push(currentKey); + } + return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys)); + } + + function checkFinished() { + if (iterationComplete && successCount + failures.length === count) { + if (failures.length > 0) + doReject(); + else + resolve(successCount); + } + } + self.clone().raw()._iterate(modifyItem, function () { + iterationComplete = true; + checkFinished(); + }, doReject, idbstore); + }); + }, + + 'delete': function () { + var ctx = this._ctx, + range = ctx.range, + deletingHook = ctx.table.hook.deleting.fire, + hasDeleteHook = deletingHook !== nop; + if (!hasDeleteHook && + isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) // if no range, we'll use clear(). + { + // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208) + // For chromium, this is the way most optimized version. + // For IE/Edge, this could hang the indexedDB engine and make operating system instable + // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7) + return this._write((resolve, reject, idbstore) => { + // Our API contract is to return a count of deleted items, so we have to count() before delete(). + var onerror = eventRejectHandler(reject), + countReq = (range ? idbstore.count(range) : idbstore.count()); + countReq.onerror = onerror; + countReq.onsuccess = () => { + var count = countReq.result; + tryCatch(()=> { + var delReq = (range ? idbstore.delete(range) : idbstore.clear()); + delReq.onerror = onerror; + delReq.onsuccess = () => resolve(count); + }, err => reject(err)); + }; + }); + } + + // Default version to use when collection is not a vanilla IDBKeyRange on the primary key. + // Divide into chunks to not starve RAM. + // If has delete hook, we will have to collect not just keys but also objects, so it will use + // more memory and need lower chunk size. + const CHUNKSIZE = hasDeleteHook ? 2000 : 10000; + + return this._write((resolve, reject, idbstore, trans) => { + var totalCount = 0; + // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance. + var collection = this + .clone({ + keysOnly: !ctx.isMatch && !hasDeleteHook}) // load just keys (unless filter() or and() or deleteHook has subscribers) + .distinct() // In case multiEntry is used, never delete same key twice because resulting count + // would become larger than actual delete count. + .limit(CHUNKSIZE) + .raw(); // Don't filter through reading-hooks (like mapped classes etc) + + var keysOrTuples = []; + + // We're gonna do things on as many chunks that are needed. + // Use recursion of nextChunk function: + const nextChunk = () => collection.each(hasDeleteHook ? (val, cursor) => { + // Somebody subscribes to hook('deleting'). Collect all primary keys and their values, + // so that the hook can be called with its values in bulkDelete(). + keysOrTuples.push([cursor.primaryKey, cursor.value]); + } : (val, cursor) => { + // No one subscribes to hook('deleting'). Collect only primary keys: + keysOrTuples.push(cursor.primaryKey); + }).then(() => { + // Chromium deletes faster when doing it in sort order. + hasDeleteHook ? + keysOrTuples.sort((a, b)=>ascending(a[0], b[0])) : + keysOrTuples.sort(ascending); + return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook); + + }).then(()=> { + var count = keysOrTuples.length; + totalCount += count; + keysOrTuples = []; + return count < CHUNKSIZE ? totalCount : nextChunk(); + }); + + resolve (nextChunk()); + }); + } + }); + + + // + // + // + // ------------------------- Help functions --------------------------- + // + // + // + + function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; + } + + function setApiOnPlace(objs, tableNames, mode, dbschema) { + tableNames.forEach(function (tableName) { + var tableInstance = db._tableFactory(mode, dbschema[tableName]); + objs.forEach(function (obj) { + tableName in obj || (obj[tableName] = tableInstance); + }); + }); + } + + function removeTablesApi(objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof Table) delete obj[key]; + } + }); + } + + function iterate(req, filter, fn, resolve, reject, valueMapper) { + + // Apply valueMapper (hook('reading') or mappped class) + var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn; + // Wrap fn with PSD and microtick stuff from Promise. + var wrappedFn = wrap(mappedFn, reject); + + if (!req.onerror) req.onerror = eventRejectHandler(reject); + if (filter) { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { cursor.continue(); }; + if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject)) + wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); + c(); + } else { + resolve(); + } + }, reject); + } else { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { cursor.continue(); }; + wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); + c(); + } else { + resolve(); + } + }, reject); + } + } + + function parseIndexSyntax(indexes) { + /// + /// + var rv = []; + indexes.split(',').forEach(function (index) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*" + // Let keyPath of "[a+b]" be ["a","b"]: + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + + rv.push(new IndexSpec( + name, + keyPath || null, + /\&/.test(index), + /\*/.test(index), + /\+\+/.test(index), + isArray(keyPath), + /\./.test(index) + )); + }); + return rv; + } + + function cmp(key1, key2) { + return indexedDB.cmp(key1, key2); + } + + function min(a, b) { + return cmp(a, b) < 0 ? a : b; + } + + function max(a, b) { + return cmp(a, b) > 0 ? a : b; + } + + function ascending(a,b) { + return indexedDB.cmp(a,b); + } + + function descending(a, b) { + return indexedDB.cmp(b,a); + } + + function simpleCompare(a, b) { + return a < b ? -1 : a === b ? 0 : 1; + } + + function simpleCompareReverse(a, b) { + return a > b ? -1 : a === b ? 0 : 1; + } + + function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; + } + + function readGlobalSchema() { + db.verno = idbdb.version / 10; + db._dbSchema = globalSchema = {}; + dbStoreNames = slice(idbdb.objectStoreNames, 0); + if (dbStoreNames.length === 0) return; // Database contains no stores. + var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly'); + dbStoreNames.forEach(function (storeName) { + var store = trans.objectStore(storeName), + keyPath = store.keyPath, + dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted); + indexes.push(index); + } + globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {}); + }); + setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema); + } + + function adjustToExistingIndexNames(schema, idbtrans) { + /// + /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db + /// + /// Map between name and TableSchema + /// + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + hasGetAll = 'getAll' in store; + for (var j = 0; j < store.indexNames.length; ++j) { + var indexName = store.indexNames[j]; + var keyPath = store.index(indexName).keyPath; + var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; + if (schema[storeName]) { + var indexSpec = schema[storeName].idxByName[dexieName]; + if (indexSpec) indexSpec.name = indexName; + } + } + } + } + + function fireOnBlocked(ev) { + db.on("blocked").fire(ev); + // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: + connections + .filter(c=>c.name === db.name && c !== db && !c._vcFired) + .map(c => c.on("versionchange").fire(ev)); + } + + extend(this, { + Collection: Collection, + Table: Table, + Transaction: Transaction, + Version: Version, + WhereClause: WhereClause, + WriteableCollection: WriteableCollection, + WriteableTable: WriteableTable + }); + + init(); + + addons.forEach(function (fn) { + fn(db); + }); +} + +var fakeAutoComplete = function () { };// Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) +var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) + +function parseType(type) { + if (typeof type === 'function') { + return new type(); + } else if (isArray(type)) { + return [parseType(type[0])]; + } else if (type && typeof type === 'object') { + var rv = {}; + applyStructure(rv, type); + return rv; + } else { + return type; + } +} + +function applyStructure(obj, structure) { + keys(structure).forEach(function (member) { + var value = parseType(structure[member]); + obj[member] = value; + }); + return obj; +} + +function eventSuccessHandler(done) { + return function (ev) { + done(ev.target.result); + } +} + +function hookedEventSuccessHandler(resolve) { + // wrap() is needed when calling hooks because the rare scenario of: + // * hook does a db operation that fails immediately (IDB throws exception) + // For calling db operations on correct transaction, wrap makes sure to set PSD correctly. + // wrap() will also execute in a virtual tick. + // * If not wrapped in a virtual tick, direct exception will launch a new physical tick. + // * If this was the last event in the bulk, the promise will resolve after a physical tick + // and the transaction will have committed already. + // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise, + // because it is always marked with _lib = true when created using Transaction._promise(). + return wrap(function(event) { + var req = event.target, + result = req.result, + ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance. + hookSuccessHandler = ctx && ctx.onsuccess; + hookSuccessHandler && hookSuccessHandler(result); + resolve && resolve(result); + }, resolve); +} + +function eventRejectHandler(reject) { + return function (event) { + preventDefault(event); + reject (event.target.error); + return false; + }; +} + +function hookedEventRejectHandler (reject) { + return wrap(function (event) { + // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks. + + var req = event.target, + err = req.error, + ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance. + hookErrorHandler = ctx && ctx.onerror; + hookErrorHandler && hookErrorHandler(err); + preventDefault(event); + reject (err); + return false; + }); +} + +function preventDefault(event) { + if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below. + event.stopPropagation(); + if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below. + event.preventDefault(); +} + +function globalDatabaseList(cb) { + var val, + localStorage = Dexie.dependencies.localStorage; + if (!localStorage) return cb([]); // Envs without localStorage support + try { + val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]"); + } catch (e) { + val = []; + } + if (cb(val)) { + localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val)); + } +} + +function awaitIterator (iterator) { + var callNext = result => iterator.next(result), + doThrow = error => iterator.throw(error), + onSuccess = step(callNext), + onError = step(doThrow); + + function step(getNext) { + return val => { + var next = getNext(val), + value = next.value; + + return next.done ? value : + (!value || typeof value.then !== 'function' ? + isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : + value.then(onSuccess, onError)); + }; + } + + return step(callNext)(); +} + +// +// IndexSpec struct +// +function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) { + /// + /// + /// + /// + /// + /// + /// + this.name = name; + this.keyPath = keyPath; + this.unique = unique; + this.multi = multi; + this.auto = auto; + this.compound = compound; + this.dotted = dotted; + var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']'); + this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc; +} + +// +// TableSchema struct +// +function TableSchema(name, primKey, indexes, instanceTemplate) { + /// + /// + /// + /// + this.name = name; + this.primKey = primKey || new IndexSpec(); + this.indexes = indexes || [new IndexSpec()]; + this.instanceTemplate = instanceTemplate; + this.mappedClass = null; + this.idxByName = arrayToObject(indexes, index => [index.name, index]); +} + +// Used in when defining dependencies later... +// (If IndexedDBShim is loaded, prefer it before standard indexedDB) +var idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {}; + +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} + +function getNativeGetDatabaseNamesFn(indexedDB) { + var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames); + return fn && fn.bind(indexedDB); +} + +// Export Error classes +props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...}; + +// +// Static methods and properties +// +props(Dexie, { + + // + // Static delete() method. + // + delete: function (databaseName) { + var db = new Dexie(databaseName), + promise = db.delete(); + promise.onblocked = function (fn) { + db.on("blocked", fn); + return this; + }; + return promise; + }, + + // + // Static exists() method. + // + exists: function(name) { + return new Dexie(name).open().then(db=>{ + db.close(); + return true; + }).catch(Dexie.NoSuchDatabaseError, () => false); + }, + + // + // Static method for retrieving a list of all existing databases at current host. + // + getDatabaseNames: function (cb) { + return new Promise(function (resolve, reject) { + var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB); + if (getDatabaseNames) { // In case getDatabaseNames() becomes standard, let's prepare to support it: + var req = getDatabaseNames(); + req.onsuccess = function (event) { + resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array + }; + req.onerror = eventRejectHandler(reject); + } else { + globalDatabaseList(function (val) { + resolve(val); + return false; + }); + } + }).then(cb); + }, + + defineClass: function (structure) { + /// + /// Create a javascript constructor based on given template for which properties to expect in the class. + /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + + // Default constructor able to copy given properties into this object. + function Class(properties) { + /// Properties to initialize object with. + /// + properties ? extend(this, properties) : fake && applyStructure(this, structure); + } + return Class; + }, + + applyStructure: applyStructure, + + ignoreTransaction: function (scopeFunc) { + // In case caller is within a transaction but needs to create a separate transaction. + // Example of usage: + // + // Let's say we have a logger function in our app. Other application-logic should be unaware of the + // logger function and not need to include the 'logentries' table in all transaction it performs. + // The logging should always be done in a separate transaction and not be dependant on the current + // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction. + // + // Dexie.ignoreTransaction(function() { + // db.logentries.add(newLogEntry); + // }); + // + // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction + // in current Promise-scope. + // + // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an + // API for this because + // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout(). + // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate(). + // 3) setImmediate() is not supported in the ES standard. + // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough. + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional. + scopeFunc(); // No need to change scope because there is no ongoing transaction. + }, + + vip: function (fn) { + // To be used by subscribers to the on('ready') event. + // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing. + // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD + // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since + // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that. + // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip() + // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by + // the caller will not resolve until database is opened. + return newScope(function () { + PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing. + return fn(); + }); + }, + + async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return Promise.resolve(rv); + return rv; + } catch (e) { + return rejection (e); + } + }; + }, + + spawn: function (generatorFn, args, thiz) { + try { + var rv = awaitIterator(generatorFn.apply(thiz, args || [])); + if (!rv || typeof rv.then !== 'function') + return Promise.resolve(rv); + return rv; + } catch (e) { + return rejection(e); + } + }, + + // Dexie.currentTransaction property + currentTransaction: { + get: () => PSD.trans || null + }, + + // Export our Promise implementation since it can be handy as a standalone Promise implementation + Promise: Promise, + + // Dexie.debug proptery: + // Dexie.debug = false + // Dexie.debug = true + // Dexie.debug = "dexie" - don't hide dexie's stack frames. + debug: { + get: () => debug, + set: value => { + setDebug(value, value === 'dexie' ? ()=>true : dexieStackFrameFilter); + } + }, + + // Export our derive/extend/override methodology + derive: derive, + extend: extend, + props: props, + override: override, + // Export our Events() function - can be handy as a toolkit + Events: Events, + events: { get: deprecated(()=>Events) }, // Backward compatible lowercase version. + // Utilities + getByKeyPath: getByKeyPath, + setByKeyPath: setByKeyPath, + delByKeyPath: delByKeyPath, + shallowClone: shallowClone, + deepClone: deepClone, + getObjectDiff: getObjectDiff, + asap: asap, + maxKey: maxKey, + // Addon registry + addons: [], + // Global DB connection list + connections: connections, + + MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate. + errnames: errnames, + + // Export other static classes + IndexSpec: IndexSpec, + TableSchema: TableSchema, + + // + // Dependencies + // + // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included. + // + // In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). + // For node.js, you need to require indexeddb-js or similar and then set these deps. + // + dependencies: { + // Required: + indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange + }, + + // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc. + semVer: DEXIE_VERSION, + version: DEXIE_VERSION.split('.') + .map(n => parseInt(n)) + .reduce((p,c,i) => p + (c/Math.pow(10,i*2))), + fakeAutoComplete: fakeAutoComplete, + + // https://github.com/dfahlander/Dexie.js/issues/186 + // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return + // x.default. Workaround: Set Dexie.default = Dexie. + default: Dexie +}); + +tryCatch(()=>{ + // Optional dependencies + // localStorage + Dexie.dependencies.localStorage = + ((typeof chrome !== "undefined" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage); +}); + +// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0. +Promise.rejectionMapper = mapError; + +// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015. +doFakeAutoComplete(function() { + Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete; + Dexie.fake = fake = true; +}); + +export default Dexie; +//# sourceMappingURL=dexie.es6.js.map diff --git a/dist/dexie.es6.js.map b/dist/dexie.es6.js.map new file mode 100644 index 000000000..34a32f255 --- /dev/null +++ b/dist/dexie.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.es6.js","sources":["../src/utils.js","../src/chaining-functions.js","../src/debug.js","../src/errors.js","../src/Events.js","../src/Promise.js","../src/promise-utils.js","../src/Dexie.js"],"sourcesContent":["/*\r\n * Dexie.js - a minimalistic wrapper for IndexedDB\r\n * ===============================================\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com\r\n *\r\n * Version {version}, {date}\r\n * www.dexie.com\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n */\r\nexport var keys = Object.keys;\r\nexport var isArray = Array.isArray;\r\nexport var _global =\r\n typeof self !== 'undefined' ? self :\r\n typeof window !== 'undefined' ? window :\r\n global;\r\n\r\nexport function extend(obj, extension) {\r\n if (typeof extension !== 'object') return obj;\r\n keys(extension).forEach(function (key) {\r\n obj[key] = extension[key];\r\n });\r\n return obj;\r\n}\r\n\r\nexport const getProto = Object.getPrototypeOf;\r\nexport const _hasOwn = {}.hasOwnProperty;\r\nexport function hasOwn(obj, prop) {\r\n return _hasOwn.call(obj, prop);\r\n}\r\n\r\nexport function props (proto, extension) {\r\n if (typeof extension === 'function') extension = extension(getProto(proto));\r\n keys(extension).forEach(key => {\r\n setProp(proto, key, extension[key]);\r\n });\r\n}\r\n\r\nexport function setProp(obj, prop, functionOrGetSet, options) {\r\n Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\r\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\r\n {value: functionOrGetSet, configurable: true, writable: true}, options));\r\n}\r\n\r\nexport function derive(Child) {\r\n return {\r\n from: function (Parent) {\r\n Child.prototype = Object.create(Parent.prototype);\r\n setProp(Child.prototype, \"constructor\", Child);\r\n return {\r\n extend: props.bind(null, Child.prototype)\r\n };\r\n }\r\n };\r\n}\r\n\r\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\r\n\r\nexport function getPropertyDescriptor(obj, prop) {\r\n var pd = getOwnPropertyDescriptor(obj, prop),\r\n proto;\r\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\r\n}\r\n\r\nvar _slice = [].slice;\r\nexport function slice(args, start, end) {\r\n return _slice.call(args, start, end);\r\n}\r\n\r\nexport function override(origFunc, overridedFactory) {\r\n return overridedFactory(origFunc);\r\n}\r\n\r\nexport function doFakeAutoComplete(fn) {\r\n var to = setTimeout(fn, 1000);\r\n clearTimeout(to);\r\n}\r\n\r\nexport function assert (b) {\r\n if (!b) throw new Error(\"Assertion Failed\");\r\n}\r\n\r\nexport function asap(fn) {\r\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\r\n}\r\n\r\nexport function getUniqueArray(a) {\r\n return a.filter((value, index, self) => self.indexOf(value) === index);\r\n}\r\n\r\n/** Generate an object (hash map) based on given array.\r\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\r\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\r\n * current item wont affect the resulting object.\r\n */\r\nexport function arrayToObject (array, extractor) {\r\n return array.reduce((result, item, i) => {\r\n var nameAndValue = extractor(item, i);\r\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\r\n return result;\r\n }, {});\r\n}\r\n\r\nexport function trycatcher(fn, reject) {\r\n return function () {\r\n try {\r\n fn.apply(this, arguments);\r\n } catch (e) {\r\n reject(e);\r\n }\r\n };\r\n}\r\n\r\nexport function tryCatch(fn, onerror, args) {\r\n try {\r\n fn.apply(null, args);\r\n } catch (ex) {\r\n onerror && onerror(ex);\r\n }\r\n}\r\n\r\nexport function getByKeyPath(obj, keyPath) {\r\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\r\n if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\r\n if (!keyPath) return obj;\r\n if (typeof keyPath !== 'string') {\r\n var rv = [];\r\n for (var i = 0, l = keyPath.length; i < l; ++i) {\r\n var val = getByKeyPath(obj, keyPath[i]);\r\n rv.push(val);\r\n }\r\n return rv;\r\n }\r\n var period = keyPath.indexOf('.');\r\n if (period !== -1) {\r\n var innerObj = obj[keyPath.substr(0, period)];\r\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function setByKeyPath(obj, keyPath, value) {\r\n if (!obj || keyPath === undefined) return;\r\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\r\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\r\n assert(typeof value !== 'string' && 'length' in value);\r\n for (var i = 0, l = keyPath.length; i < l; ++i) {\r\n setByKeyPath(obj, keyPath[i], value[i]);\r\n }\r\n } else {\r\n var period = keyPath.indexOf('.');\r\n if (period !== -1) {\r\n var currentKeyPath = keyPath.substr(0, period);\r\n var remainingKeyPath = keyPath.substr(period + 1);\r\n if (remainingKeyPath === \"\")\r\n if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value;\r\n else {\r\n var innerObj = obj[currentKeyPath];\r\n if (!innerObj) innerObj = (obj[currentKeyPath] = {});\r\n setByKeyPath(innerObj, remainingKeyPath, value);\r\n }\r\n } else {\r\n if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value;\r\n }\r\n }\r\n}\r\n\r\nexport function delByKeyPath(obj, keyPath) {\r\n if (typeof keyPath === 'string')\r\n setByKeyPath(obj, keyPath, undefined);\r\n else if ('length' in keyPath)\r\n [].map.call(keyPath, function(kp) {\r\n setByKeyPath(obj, kp, undefined);\r\n });\r\n}\r\n\r\nexport function shallowClone(obj) {\r\n var rv = {};\r\n for (var m in obj) {\r\n if (hasOwn(obj, m)) rv[m] = obj[m];\r\n }\r\n return rv;\r\n}\r\n\r\nexport function deepClone(any) {\r\n if (!any || typeof any !== 'object') return any;\r\n var rv;\r\n if (isArray(any)) {\r\n rv = [];\r\n for (var i = 0, l = any.length; i < l; ++i) {\r\n rv.push(deepClone(any[i]));\r\n }\r\n } else if (any instanceof Date) {\r\n rv = new Date();\r\n rv.setTime(any.getTime());\r\n } else {\r\n rv = any.constructor ? Object.create(any.constructor.prototype) : {};\r\n for (var prop in any) {\r\n if (hasOwn(any, prop)) {\r\n rv[prop] = deepClone(any[prop]);\r\n }\r\n }\r\n }\r\n return rv;\r\n}\r\n\r\nexport function getObjectDiff(a, b, rv, prfx) {\r\n // Compares objects a and b and produces a diff object.\r\n rv = rv || {};\r\n prfx = prfx || '';\r\n keys(a).forEach(prop => {\r\n if (!hasOwn(b, prop))\r\n rv[prfx+prop] = undefined; // Property removed\r\n else {\r\n var ap = a[prop],\r\n bp = b[prop];\r\n if (typeof ap === 'object' && typeof bp === 'object' &&\r\n ap && bp &&\r\n ap.constructor === bp.constructor)\r\n // Same type of object but its properties may have changed\r\n getObjectDiff (ap, bp, rv, prfx + prop + \".\");\r\n else if (ap !== bp)\r\n rv[prfx + prop] = b[prop];// Primitive value changed\r\n }\r\n });\r\n keys(b).forEach(prop => {\r\n if (!hasOwn(a, prop)) {\r\n rv[prfx+prop] = b[prop]; // Property added\r\n }\r\n });\r\n return rv;\r\n}\r\n\r\n// If first argument is iterable or array-like, return it as an array\r\nexport const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\r\nexport const getIteratorOf = iteratorSymbol ? function(x) {\r\n var i;\r\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\r\n} : function () { return null; };\r\n\r\nexport const NO_CHAR_ARRAY = {};\r\n// Takes one or several arguments and returns an array based on the following criteras:\r\n// * If several arguments provided, return arguments converted to an array in a way that\r\n// still allows javascript engine to optimize the code.\r\n// * If single argument is an array, return a clone of it.\r\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\r\n// case to the two bullets below.\r\n// * If single argument is an iterable, convert it to an array and return the resulting array.\r\n// * If single argument is array-like (has length of type number), convert it to an array.\r\nexport function getArrayOf (arrayLike) {\r\n var i, a, x, it;\r\n if (arguments.length === 1) {\r\n if (isArray(arrayLike)) return arrayLike.slice();\r\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\r\n if ((it = getIteratorOf(arrayLike))) {\r\n a = [];\r\n while ((x = it.next()), !x.done) a.push(x.value);\r\n return a;\r\n }\r\n if (arrayLike == null) return [arrayLike];\r\n i = arrayLike.length;\r\n if (typeof i === 'number') {\r\n a = new Array(i);\r\n while (i--) a[i] = arrayLike[i];\r\n return a;\r\n }\r\n return [arrayLike];\r\n }\r\n i = arguments.length;\r\n a = new Array(i);\r\n while (i--) a[i] = arguments[i];\r\n return a;\r\n}\r\n\r\nconst concat = [].concat;\r\nexport function flatten (a) {\r\n return concat.apply([], a);\r\n}\r\n","import {extend} from './utils';\r\n\r\nexport function nop() { }\r\nexport function mirror(val) { return val; }\r\nexport function pureFunctionChain(f1, f2) {\r\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\r\n // This pattern is used in the hook(\"reading\") event.\r\n if (f1 == null || f1 === mirror) return f2;\r\n return function (val) {\r\n return f2(f1(val));\r\n };\r\n}\r\n\r\nexport function callBoth(on1, on2) {\r\n return function () {\r\n on1.apply(this, arguments);\r\n on2.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function hookCreatingChain(f1, f2) {\r\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\r\n // This pattern is used in the hook(\"creating\") event.\r\n if (f1 === nop) return f2;\r\n return function () {\r\n var res = f1.apply(this, arguments);\r\n if (res !== undefined) arguments[0] = res;\r\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\r\n onerror = this.onerror; // In case event listener has set this.onerror\r\n this.onsuccess = null;\r\n this.onerror = null;\r\n var res2 = f2.apply(this, arguments);\r\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\r\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\r\n return res2 !== undefined ? res2 : res;\r\n };\r\n}\r\n\r\nexport function hookDeletingChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n f1.apply(this, arguments);\r\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\r\n onerror = this.onerror; // In case event listener has set this.onerror\r\n this.onsuccess = this.onerror = null;\r\n f2.apply(this, arguments);\r\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\r\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\r\n };\r\n}\r\n\r\nexport function hookUpdatingChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function (modifications) {\r\n var res = f1.apply(this, arguments);\r\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\r\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\r\n onerror = this.onerror; // In case event listener has set this.onerror\r\n this.onsuccess = null;\r\n this.onerror = null;\r\n var res2 = f2.apply(this, arguments);\r\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\r\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\r\n return res === undefined ?\r\n (res2 === undefined ? undefined : res2) :\r\n (extend(res, res2));\r\n };\r\n}\r\n\r\nexport function reverseStoppableEventChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n if (f2.apply(this, arguments) === false) return false;\r\n return f1.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function nonStoppableEventChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n f1.apply(this, arguments);\r\n f2.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function promisableChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n var res = f1.apply(this, arguments);\r\n if (res && typeof res.then === 'function') {\r\n var thiz = this,\r\n i = arguments.length,\r\n args = new Array(i);\r\n while (i--) args[i] = arguments[i];\r\n return res.then(function () {\r\n return f2.apply(thiz, args);\r\n });\r\n }\r\n return f2.apply(this, arguments);\r\n };\r\n}\r\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\r\n// When debug = true, error's stacks will contain asyncronic long stacks.\r\nexport var debug = typeof location !== 'undefined' &&\r\n // By default, use debug mode if served from localhost.\r\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\r\n\r\nexport function setDebug(value, filter) {\r\n debug = value;\r\n libraryFilter = filter;\r\n}\r\n\r\nexport var libraryFilter = () => true;\r\n\r\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\r\n\r\nexport function getErrorWithStack() {\r\n \"use strict\";\r\n if (NEEDS_THROW_FOR_STACK) try {\r\n // Doing something naughty in strict mode here to trigger a specific error\r\n // that can be explicitely ignored in debugger's exception settings.\r\n // If we'd just throw new Error() here, IE's debugger's exception settings\r\n // will just consider it as \"exception thrown by javascript code\" which is\r\n // something you wouldn't want it to ignore.\r\n getErrorWithStack.arguments;\r\n throw new Error(); // Fallback if above line don't throw.\r\n } catch(e) {\r\n return e;\r\n }\r\n return new Error();\r\n}\r\n\r\nexport function prettyStack(exception, numIgnoredFrames) {\r\n var stack = exception.stack;\r\n if (!stack) return \"\";\r\n numIgnoredFrames = (numIgnoredFrames || 0);\r\n if (stack.indexOf(exception.name) === 0)\r\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\r\n return stack.split('\\n')\r\n .slice(numIgnoredFrames)\r\n .filter(libraryFilter)\r\n .map(frame => \"\\n\" + frame)\r\n .join('');\r\n}\r\n\r\nexport function deprecated (what, fn) {\r\n return function () {\r\n console.warn(`${what} is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\r\n return fn.apply(this, arguments);\r\n }\r\n}\r\n","import { derive, setProp } from './utils';\r\nimport { getErrorWithStack, prettyStack } from './debug';\r\n\r\nvar dexieErrorNames = [\r\n 'Modify',\r\n 'Bulk',\r\n 'OpenFailed',\r\n 'VersionChange',\r\n 'Schema',\r\n 'Upgrade',\r\n 'InvalidTable',\r\n 'MissingAPI',\r\n 'NoSuchDatabase',\r\n 'InvalidArgument',\r\n 'SubTransaction',\r\n 'Unsupported',\r\n 'Internal',\r\n 'DatabaseClosed',\r\n 'IncompatiblePromise'\r\n];\r\n\r\nvar idbDomErrorNames = [\r\n 'Unknown',\r\n 'Constraint',\r\n 'Data',\r\n 'TransactionInactive',\r\n 'ReadOnly',\r\n 'Version',\r\n 'NotFound',\r\n 'InvalidState',\r\n 'InvalidAccess',\r\n 'Abort',\r\n 'Timeout',\r\n 'QuotaExceeded',\r\n 'Syntax',\r\n 'DataClone'\r\n];\r\n\r\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\r\n\r\nvar defaultTexts = {\r\n VersionChanged: \"Database version changed by other database connection\",\r\n DatabaseClosed: \"Database has been closed\",\r\n Abort: \"Transaction aborted\",\r\n TransactionInactive: \"Transaction has already completed or failed\"\r\n};\r\n\r\n//\r\n// DexieError - base class of all out exceptions.\r\n//\r\nexport function DexieError (name, msg) {\r\n // Reason we don't use ES6 classes is because:\r\n // 1. It bloats transpiled code and increases size of minified code.\r\n // 2. It doesn't give us much in this case.\r\n // 3. It would require sub classes to call super(), which\r\n // is not needed when deriving from Error.\r\n this._e = getErrorWithStack();\r\n this.name = name;\r\n this.message = msg;\r\n}\r\n\r\nderive(DexieError).from(Error).extend({\r\n stack: {\r\n get: function() {\r\n return this._stack ||\r\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\r\n }\r\n },\r\n toString: function(){ return this.name + \": \" + this.message; }\r\n});\r\n\r\nfunction getMultiErrorMessage (msg, failures) {\r\n return msg + \". Errors: \" + failures\r\n .map(f=>f.toString())\r\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\r\n .join('\\n');\r\n}\r\n\r\n//\r\n// ModifyError - thrown in WriteableCollection.modify()\r\n// Specific constructor because it contains members failures and failedKeys.\r\n//\r\nexport function ModifyError (msg, failures, successCount, failedKeys) {\r\n this._e = getErrorWithStack();\r\n this.failures = failures;\r\n this.failedKeys = failedKeys;\r\n this.successCount = successCount;\r\n}\r\nderive(ModifyError).from(DexieError);\r\n\r\nexport function BulkError (msg, failures) {\r\n this._e = getErrorWithStack();\r\n this.name = \"BulkError\";\r\n this.failures = failures;\r\n this.message = getMultiErrorMessage(msg, failures);\r\n}\r\nderive(BulkError).from(DexieError);\r\n\r\n//\r\n//\r\n// Dynamically generate error names and exception classes based\r\n// on the names in errorList.\r\n//\r\n//\r\n\r\n// Map of {ErrorName -> ErrorName + \"Error\"}\r\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\r\n\r\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\r\nconst BaseException = DexieError;\r\n// Map of {ErrorName -> exception constructor}\r\nexport var exceptions = errorList.reduce((obj,name)=>{\r\n // Let the name be \"DexieError\" because this name may\r\n // be shown in call stack and when debugging. DexieError is\r\n // the most true name because it derives from DexieError,\r\n // and we cannot change Function.name programatically without\r\n // dynamically create a Function object, which would be considered\r\n // 'eval-evil'.\r\n var fullName = name + \"Error\";\r\n function DexieError (msgOrInner, inner){\r\n this._e = getErrorWithStack();\r\n this.name = fullName;\r\n if (!msgOrInner) {\r\n this.message = defaultTexts[name] || fullName;\r\n this.inner = null;\r\n } else if (typeof msgOrInner === 'string') {\r\n this.message = msgOrInner;\r\n this.inner = inner || null;\r\n } else if (typeof msgOrInner === 'object') {\r\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\r\n this.inner = msgOrInner;\r\n }\r\n }\r\n derive(DexieError).from(BaseException);\r\n obj[name]=DexieError;\r\n return obj;\r\n},{});\r\n\r\n// Use ECMASCRIPT standard exceptions where applicable:\r\nexceptions.Syntax = SyntaxError;\r\nexceptions.Type = TypeError;\r\nexceptions.Range = RangeError;\r\n\r\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\r\n obj[name + \"Error\"] = exceptions[name];\r\n return obj;\r\n}, {});\r\n\r\nexport function mapError (domError, message) {\r\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\r\n return domError;\r\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\r\n if (\"stack\" in domError) {\r\n // Derive stack from inner exception if it has a stack\r\n setProp(rv, \"stack\", {get: function(){\r\n return this.inner.stack;\r\n }});\r\n }\r\n return rv;\r\n}\r\n\r\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\r\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\r\n obj[name + \"Error\"] = exceptions[name];\r\n return obj;\r\n}, {});\r\n\r\nfullNameExceptions.ModifyError = ModifyError;\r\nfullNameExceptions.DexieError = DexieError;\r\nfullNameExceptions.BulkError = BulkError;\r\n","import {keys, isArray, asap} from './utils';\r\nimport {nop, mirror, reverseStoppableEventChain} from './chaining-functions';\r\nimport {exceptions} from './errors';\r\n\r\nexport default function Events(ctx) {\r\n var evs = {};\r\n var rv = function (eventName, subscriber) {\r\n if (subscriber) {\r\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\r\n var i = arguments.length, args = new Array(i - 1);\r\n while (--i) args[i - 1] = arguments[i];\r\n evs[eventName].subscribe.apply(null, args);\r\n return ctx;\r\n } else if (typeof (eventName) === 'string') {\r\n // Return interface allowing to fire or unsubscribe from event\r\n return evs[eventName];\r\n }\r\n };\r\n rv.addEventType = add;\r\n \r\n for (var i = 1, l = arguments.length; i < l; ++i) {\r\n add(arguments[i]);\r\n }\r\n \r\n return rv;\r\n\r\n function add(eventName, chainFunction, defaultFunction) {\r\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\r\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\r\n if (!defaultFunction) defaultFunction = nop;\r\n\r\n var context = {\r\n subscribers: [],\r\n fire: defaultFunction,\r\n subscribe: function (cb) {\r\n if (context.subscribers.indexOf(cb) === -1) {\r\n context.subscribers.push(cb);\r\n context.fire = chainFunction(context.fire, cb);\r\n }\r\n },\r\n unsubscribe: function (cb) {\r\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\r\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\r\n }\r\n };\r\n evs[eventName] = rv[eventName] = context;\r\n return context;\r\n }\r\n\r\n function addConfiguredEvents(cfg) {\r\n // events(this, {reading: [functionChain, nop]});\r\n keys(cfg).forEach(function (eventName) {\r\n var args = cfg[eventName];\r\n if (isArray(args)) {\r\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\r\n } else if (args === 'asap') {\r\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\r\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\r\n var context = add(eventName, mirror, function fire() {\r\n // Optimazation-safe cloning of arguments into args.\r\n var i = arguments.length, args = new Array(i);\r\n while (i--) args[i] = arguments[i];\r\n // All each subscriber:\r\n context.subscribers.forEach(function (fn) {\r\n asap(function fireEvent() {\r\n fn.apply(null, args);\r\n });\r\n });\r\n });\r\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\r\n });\r\n }\r\n}\r\n","import {doFakeAutoComplete, tryCatch, props,\r\n setProp, _global, getPropertyDescriptor, getArrayOf, extend} from './utils';\r\nimport {reverseStoppableEventChain, nop, callBoth, mirror} from './chaining-functions';\r\nimport Events from './Events';\r\nimport {debug, prettyStack, getErrorWithStack, deprecated} from './debug';\r\n\r\n//\r\n// Promise Class for Dexie library\r\n//\r\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\r\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\r\n//\r\n// Modifications needed to be done to support indexedDB because it wont accept setTimeout()\r\n// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) .\r\n// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45\r\n//\r\n// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since\r\n// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise.\r\n//\r\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\r\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\r\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick\r\n// engine that is used instead of setImmediate() or setTimeout().\r\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\r\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\r\n//\r\n// Specific non-standard features of this Promise class:\r\n// * Async static context support (Promise.PSD)\r\n// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame\r\n// and below + all promises that those promises creates or awaits.\r\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \r\n//\r\n// David Fahlander, https://github.com/dfahlander\r\n//\r\n\r\n// Just a pointer that only this module knows about.\r\n// Used in Promise constructor to emulate a private constructor.\r\nvar INTERNAL = {};\r\n\r\n// Async stacks (long stacks) must not grow infinitely.\r\nvar LONG_STACKS_CLIP_LIMIT = 100,\r\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \r\n MAX_LONG_STACKS = 20,\r\n stack_being_generated = false;\r\n\r\n/* The default \"nextTick\" function used only for the very first promise in a promise chain.\r\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\r\n emulated in this module. For indexedDB compatibility, this means that every method needs to \r\n execute at least one promise before doing an indexedDB operation. Dexie will always call \r\n db.ready().then() for every operation to make sure the indexedDB event is started in an\r\n emulated micro tick.\r\n*/\r\nvar schedulePhysicalTick = (_global.setImmediate ? \r\n // setImmediate supported. Those modern platforms also supports Function.bind().\r\n setImmediate.bind(null, physicalTick) :\r\n _global.MutationObserver ?\r\n // MutationObserver supported\r\n () => {\r\n var hiddenDiv = document.createElement(\"div\");\r\n (new MutationObserver(() => {\r\n physicalTick();\r\n hiddenDiv = null;\r\n })).observe(hiddenDiv, { attributes: true });\r\n hiddenDiv.setAttribute('i', '1');\r\n } :\r\n // No support for setImmediate or MutationObserver. No worry, setTimeout is only called\r\n // once time. Every tick that follows will be our emulated micro tick.\r\n // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug \r\n ()=>{setTimeout(physicalTick,0);}\r\n);\r\n\r\n// Confifurable through Promise.scheduler.\r\n// Don't export because it would be unsafe to let unknown\r\n// code call it unless they do try..catch within their callback.\r\n// This function can be retrieved through getter of Promise.scheduler though,\r\n// but users must not do Promise.scheduler (myFuncThatThrows exception)!\r\nvar asap = function (callback, args) {\r\n microtickQueue.push([callback, args]);\r\n if (needsNewPhysicalTick) {\r\n schedulePhysicalTick();\r\n needsNewPhysicalTick = false;\r\n }\r\n}\r\n\r\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\r\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\r\n unhandledErrors = [], // Rejected promises that has occured. Used for firing unhandledrejection.\r\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\r\n currentFulfiller = null,\r\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\r\n \r\nexport var globalPSD = {\r\n global: true,\r\n ref: 0,\r\n unhandleds: [],\r\n onunhandled: globalError,\r\n //env: null, // Will be set whenever leaving a scope using wrappers.snapshot()\r\n finalize: function () {\r\n this.unhandleds.forEach(uh => {\r\n try {\r\n globalError(uh[0], uh[1]);\r\n } catch (e) {}\r\n });\r\n }\r\n};\r\n\r\nexport var PSD = globalPSD;\r\n\r\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\r\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\r\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\r\n\r\n// Wrappers are not being used yet. Their framework is functioning and can be used\r\n// to replace environment during a PSD scope (a.k.a. 'zone').\r\n/* **KEEP** export var wrappers = (() => {\r\n var wrappers = [];\r\n\r\n return {\r\n snapshot: () => {\r\n var i = wrappers.length,\r\n result = new Array(i);\r\n while (i--) result[i] = wrappers[i].snapshot();\r\n return result;\r\n },\r\n restore: values => {\r\n var i = wrappers.length;\r\n while (i--) wrappers[i].restore(values[i]);\r\n },\r\n wrap: () => wrappers.map(w => w.wrap()),\r\n add: wrapper => {\r\n wrappers.push(wrapper);\r\n }\r\n };\r\n})();\r\n*/\r\n\r\nexport default function Promise(fn) {\r\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \r\n this._listeners = [];\r\n this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.\r\n \r\n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\r\n // execute the microtask engine implicitely within the call to resolve() or reject().\r\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\r\n // only contains library code when calling resolve() or reject().\r\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\r\n // global scope (event handler, timer etc)!\r\n this._lib = false;\r\n // Current async scope\r\n var psd = (this._PSD = PSD);\r\n\r\n if (debug) {\r\n this._stackHolder = getErrorWithStack();\r\n this._prev = null;\r\n this._numPrev = 0; // Number of previous promises (for long stacks)\r\n linkToPreviousPromise(this, currentFulfiller);\r\n }\r\n \r\n if (typeof fn !== 'function') {\r\n if (fn !== INTERNAL) throw new TypeError('Not a function');\r\n // Private constructor (INTERNAL, state, value).\r\n // Used internally by Promise.resolve() and Promise.reject().\r\n this._state = arguments[1];\r\n this._value = arguments[2];\r\n if (this._state === false)\r\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\r\n return;\r\n }\r\n \r\n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\r\n this._value = null; // error or result\r\n ++psd.ref; // Refcounting current scope\r\n executePromiseTask(this, fn);\r\n}\r\n\r\nprops(Promise.prototype, {\r\n\r\n then: function (onFulfilled, onRejected) {\r\n var rv = new Promise((resolve, reject) => {\r\n propagateToListener(this, new Listener(onFulfilled, onRejected, resolve, reject));\r\n });\r\n debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this);\r\n return rv;\r\n },\r\n \r\n _then: function (onFulfilled, onRejected) {\r\n // A little tinier version of then() that don't have to create a resulting promise.\r\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected)); \r\n },\r\n\r\n catch: function (onRejected) {\r\n if (arguments.length === 1) return this.then(null, onRejected);\r\n // First argument is the Error type to catch\r\n var type = arguments[0],\r\n handler = arguments[1];\r\n return typeof type === 'function' ? this.then(null, err =>\r\n // Catching errors by its constructor type (similar to java / c++ / c#)\r\n // Sample: promise.catch(TypeError, function (e) { ... });\r\n err instanceof type ? handler(err) : PromiseReject(err))\r\n : this.then(null, err =>\r\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\r\n // is always DOMError but where e.name tells the actual error type.\r\n // Sample: promise.catch('ConstraintError', function (e) { ... });\r\n err && err.name === type ? handler(err) : PromiseReject(err));\r\n },\r\n\r\n finally: function (onFinally) {\r\n return this.then(value => {\r\n onFinally();\r\n return value;\r\n }, err => {\r\n onFinally();\r\n return PromiseReject(err);\r\n });\r\n },\r\n \r\n // Deprecate in next major. Needed only for db.on.error.\r\n uncaught: function (uncaughtHandler) {\r\n // Be backward compatible and use \"onuncatched\" as the event name on this.\r\n // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops.\r\n this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler);\r\n // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not\r\n // a previous promise. Reason: the prevous promise may lack onuncatched handler. \r\n if (this._state === false && unhandledErrors.indexOf(this) === -1) {\r\n // Replace unhandled error's destinaion promise with this one!\r\n unhandledErrors.some((p,i,l) => p._value === this._value && (l[i] = this));\r\n // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could\r\n // take away this piece of code as well as the onuncatched and uncaught() method.\r\n }\r\n return this;\r\n },\r\n \r\n stack: {\r\n get: function() {\r\n if (this._stack) return this._stack;\r\n try {\r\n stack_being_generated = true;\r\n var stacks = getStack (this, [], MAX_LONG_STACKS);\r\n var stack = stacks.join(\"\\nFrom previous: \");\r\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\r\n return stack;\r\n } finally {\r\n stack_being_generated = false;\r\n }\r\n }\r\n }\r\n});\r\n\r\nfunction Listener(onFulfilled, onRejected, resolve, reject) {\r\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\r\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n this.psd = PSD;\r\n}\r\n\r\n// Promise Static Properties\r\nprops (Promise, {\r\n all: function () {\r\n var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like.\r\n return new Promise(function (resolve, reject) {\r\n if (values.length === 0) resolve([]);\r\n var remaining = values.length;\r\n values.forEach((a,i) => Promise.resolve(a).then(x => {\r\n values[i] = x;\r\n if (!--remaining) resolve(values);\r\n }, reject));\r\n });\r\n },\r\n \r\n resolve: value => {\r\n if (value instanceof Promise) return value;\r\n if (value && typeof value.then === 'function') return new Promise((resolve, reject)=>{\r\n value.then(resolve, reject);\r\n });\r\n return new Promise(INTERNAL, true, value);\r\n },\r\n \r\n reject: PromiseReject,\r\n \r\n race: function () {\r\n var values = getArrayOf.apply(null, arguments);\r\n return new Promise((resolve, reject) => {\r\n values.map(value => Promise.resolve(value).then(resolve, reject));\r\n });\r\n },\r\n \r\n PSD: {\r\n get: ()=>PSD,\r\n set: value => PSD = value\r\n },\r\n \r\n newPSD: newScope,\r\n \r\n usePSD: usePSD,\r\n \r\n scheduler: {\r\n get: () => asap,\r\n set: value => {asap = value}\r\n },\r\n \r\n rejectionMapper: {\r\n get: () => rejectionMapper,\r\n set: value => {rejectionMapper = value;} // Map reject failures\r\n },\r\n \r\n follow: fn => {\r\n return new Promise((resolve, reject) => {\r\n return newScope((resolve, reject) => {\r\n var psd = PSD;\r\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\r\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\r\n psd.finalize = callBoth(function () {\r\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\r\n // examined upon scope completion while unhandled rejections in this Promise\r\n // will trigger directly through psd.onunhandled\r\n run_at_end_of_this_or_next_physical_tick(()=>{\r\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\r\n });\r\n }, psd.finalize);\r\n fn();\r\n }, resolve, reject);\r\n });\r\n },\r\n\r\n on: Events(null, {\"error\": [\r\n reverseStoppableEventChain,\r\n defaultErrorHandler] // Default to defaultErrorHandler\r\n })\r\n\r\n});\r\n\r\nvar PromiseOnError = Promise.on.error;\r\nPromiseOnError.subscribe = deprecated (\"Promise.on('error')\", PromiseOnError.subscribe);\r\nPromiseOnError.unsubscribe = deprecated (\"Promise.on('error').unsubscribe\", PromiseOnError.unsubscribe);\r\n\r\n/**\r\n* Take a potentially misbehaving resolver function and make sure\r\n* onFulfilled and onRejected are only called once.\r\n*\r\n* Makes no guarantees about asynchrony.\r\n*/\r\nfunction executePromiseTask (promise, fn) {\r\n // Promise Resolution Procedure:\r\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\r\n try {\r\n fn(value => {\r\n if (promise._state !== null) return;\r\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\r\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\r\n if (value && typeof value.then === 'function') {\r\n executePromiseTask(promise, (resolve, reject) => {\r\n value instanceof Promise ?\r\n value._then(resolve, reject) :\r\n value.then(resolve, reject);\r\n });\r\n } else {\r\n promise._state = true;\r\n promise._value = value;\r\n propagateAllListeners(promise);\r\n }\r\n if (shouldExecuteTick) endMicroTickScope();\r\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\r\n } catch (ex) {\r\n handleRejection(promise, ex);\r\n }\r\n}\r\n\r\nfunction handleRejection (promise, reason) {\r\n rejectingErrors.push(reason);\r\n if (promise._state !== null) return;\r\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\r\n reason = rejectionMapper(reason);\r\n promise._state = false;\r\n promise._value = reason;\r\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\r\n var origProp = getPropertyDescriptor(reason, \"stack\"); \r\n reason._promise = promise; \r\n setProp(reason, \"stack\", {\r\n get: () =>\r\n stack_being_generated ?\r\n origProp && (origProp.get ?\r\n origProp.get.apply(reason) :\r\n origProp.value) :\r\n promise.stack\r\n });\r\n });\r\n // Add the failure to a list of possibly uncaught errors\r\n addPossiblyUnhandledError(promise);\r\n propagateAllListeners(promise);\r\n if (shouldExecuteTick) endMicroTickScope();\r\n}\r\n\r\nfunction propagateAllListeners (promise) {\r\n //debug && linkToPreviousPromise(promise);\r\n var listeners = promise._listeners;\r\n promise._listeners = [];\r\n for (var i = 0, len = listeners.length; i < len; ++i) {\r\n propagateToListener(promise, listeners[i]);\r\n }\r\n var psd = promise._PSD;\r\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\r\n if (numScheduledCalls === 0) {\r\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\r\n // and that no deferreds where listening to this rejection or success.\r\n // Since there is a risk that our stack can contain application code that may\r\n // do stuff after this code is finished that may generate new calls, we cannot\r\n // call finalizers here.\r\n ++numScheduledCalls;\r\n asap(()=>{\r\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\r\n }, []);\r\n }\r\n}\r\n\r\nfunction propagateToListener(promise, listener) {\r\n if (promise._state === null) {\r\n promise._listeners.push(listener);\r\n return;\r\n }\r\n\r\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\r\n if (cb === null) {\r\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\r\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\r\n }\r\n var psd = listener.psd;\r\n ++psd.ref;\r\n ++numScheduledCalls;\r\n asap (callListener, [cb, promise, listener]);\r\n}\r\n\r\nfunction callListener (cb, promise, listener) {\r\n var outerScope = PSD;\r\n var psd = listener.psd;\r\n try {\r\n if (psd !== outerScope) {\r\n // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment.\r\n PSD = psd;\r\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\r\n }\r\n \r\n // Set static variable currentFulfiller to the promise that is being fullfilled,\r\n // so that we connect the chain of promises (for long stacks support)\r\n currentFulfiller = promise;\r\n \r\n // Call callback and resolve our listener with it's return value.\r\n var value = promise._value,\r\n ret;\r\n if (promise._state) {\r\n ret = cb (value);\r\n } else {\r\n if (rejectingErrors.length) rejectingErrors = [];\r\n ret = cb(value);\r\n if (rejectingErrors.indexOf(value) === -1)\r\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\r\n }\r\n listener.resolve(ret);\r\n } catch (e) {\r\n // Exception thrown in callback. Reject our listener.\r\n listener.reject(e);\r\n } finally {\r\n // Restore PSD, env and currentFulfiller.\r\n if (psd !== outerScope) {\r\n PSD = outerScope;\r\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment\r\n }\r\n currentFulfiller = null;\r\n if (--numScheduledCalls === 0) finalizePhysicalTick();\r\n --psd.ref || psd.finalize();\r\n }\r\n}\r\n\r\nfunction getStack (promise, stacks, limit) {\r\n if (stacks.length === limit) return stacks;\r\n var stack = \"\";\r\n if (promise._state === false) {\r\n var failure = promise._value,\r\n errorName,\r\n message;\r\n \r\n if (failure != null) {\r\n errorName = failure.name || \"Error\";\r\n message = failure.message || failure;\r\n stack = prettyStack(failure, 0);\r\n } else {\r\n errorName = failure; // If error is undefined or null, show that.\r\n message = \"\"\r\n }\r\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\r\n }\r\n if (debug) {\r\n stack = prettyStack(promise._stackHolder, 2);\r\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\r\n if (promise._prev) getStack(promise._prev, stacks, limit);\r\n }\r\n return stacks;\r\n}\r\n\r\nfunction linkToPreviousPromise(promise, prev) {\r\n // Support long stacks by linking to previous completed promise.\r\n var numPrev = prev ? prev._numPrev + 1 : 0;\r\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\r\n promise._prev = prev;\r\n promise._numPrev = numPrev;\r\n }\r\n}\r\n\r\n/* The callback to schedule with setImmediate() or setTimeout().\r\n It runs a virtual microtick and executes any callback registered in microtickQueue.\r\n */\r\nfunction physicalTick() {\r\n beginMicroTickScope() && endMicroTickScope();\r\n}\r\n\r\nfunction beginMicroTickScope() {\r\n var wasRootExec = isOutsideMicroTick;\r\n isOutsideMicroTick = false;\r\n needsNewPhysicalTick = false;\r\n return wasRootExec;\r\n}\r\n\r\n/* Executes micro-ticks without doing try..catch.\r\n This can be possible because we only use this internally and\r\n the registered functions are exception-safe (they do try..catch\r\n internally before calling any external method). If registering\r\n functions in the microtickQueue that are not exception-safe, this\r\n would destroy the framework and make it instable. So we don't export\r\n our asap method.\r\n*/\r\nfunction endMicroTickScope() {\r\n var callbacks, i, l;\r\n do {\r\n while (microtickQueue.length > 0) {\r\n callbacks = microtickQueue;\r\n microtickQueue = [];\r\n l = callbacks.length;\r\n for (i = 0; i < l; ++i) {\r\n var item = callbacks[i];\r\n item[0].apply(null, item[1]);\r\n }\r\n }\r\n } while (microtickQueue.length > 0);\r\n isOutsideMicroTick = true;\r\n needsNewPhysicalTick = true;\r\n}\r\n\r\nfunction finalizePhysicalTick() {\r\n var unhandledErrs = unhandledErrors;\r\n unhandledErrors = [];\r\n unhandledErrs.forEach(p => {\r\n p._PSD.onunhandled.call(null, p._value, p);\r\n });\r\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\r\n var i = finalizers.length;\r\n while (i) finalizers[--i](); \r\n}\r\n\r\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\r\n function finalizer() {\r\n fn();\r\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\r\n }\r\n tickFinalizers.push(finalizer);\r\n ++numScheduledCalls;\r\n asap(()=>{\r\n if (--numScheduledCalls === 0) finalizePhysicalTick();\r\n }, []);\r\n}\r\n\r\nfunction addPossiblyUnhandledError(promise) {\r\n // Only add to unhandledErrors if not already there. The first one to add to this list\r\n // will be upon the first rejection so that the root cause (first promise in the\r\n // rejection chain) is the one listed.\r\n if (!unhandledErrors.some(p => p._value === promise._value))\r\n unhandledErrors.push(promise);\r\n}\r\n\r\nfunction markErrorAsHandled(promise) {\r\n // Called when a reject handled is actually being called.\r\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\r\n // contains only rejected promises, and only one item per error)\r\n var i = unhandledErrors.length;\r\n while (i) if (unhandledErrors[--i]._value === promise._value) {\r\n // Found a promise that failed with this same error object pointer,\r\n // Remove that since there is a listener that actually takes care of it.\r\n unhandledErrors.splice(i, 1);\r\n return;\r\n }\r\n}\r\n\r\n// By default, log uncaught errors to the console\r\nfunction defaultErrorHandler(e) {\r\n console.warn(`Unhandled rejection: ${e.stack || e}`);\r\n}\r\n\r\nfunction PromiseReject (reason) {\r\n return new Promise(INTERNAL, false, reason);\r\n}\r\n\r\nexport function wrap (fn, errorCatcher) {\r\n var psd = PSD;\r\n return function() {\r\n var wasRootExec = beginMicroTickScope(),\r\n outerScope = PSD;\r\n\r\n try {\r\n if (outerScope !== psd) {\r\n // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment\r\n PSD = psd;\r\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\r\n }\r\n return fn.apply(this, arguments);\r\n } catch (e) {\r\n errorCatcher && errorCatcher(e);\r\n } finally {\r\n if (outerScope !== psd) {\r\n PSD = outerScope;\r\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment\r\n }\r\n if (wasRootExec) endMicroTickScope();\r\n }\r\n };\r\n}\r\n \r\nexport function newScope (fn, a1, a2, a3) {\r\n var parent = PSD,\r\n psd = Object.create(parent);\r\n psd.parent = parent;\r\n psd.ref = 0;\r\n psd.global = false;\r\n // **KEEP** psd.env = wrappers.wrap(psd);\r\n \r\n // unhandleds and onunhandled should not be specifically set here.\r\n // Leave them on parent prototype.\r\n // unhandleds.push(err) will push to parent's prototype\r\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\r\n ++parent.ref;\r\n psd.finalize = function () {\r\n --this.parent.ref || this.parent.finalize();\r\n }\r\n var rv = usePSD (psd, fn, a1, a2, a3);\r\n if (psd.ref === 0) psd.finalize();\r\n return rv;\r\n}\r\n\r\nexport function usePSD (psd, fn, a1, a2, a3) {\r\n var outerScope = PSD;\r\n try {\r\n if (psd !== outerScope) {\r\n // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment.\r\n PSD = psd;\r\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\r\n }\r\n return fn(a1, a2, a3);\r\n } finally {\r\n if (psd !== outerScope) {\r\n PSD = outerScope;\r\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment.\r\n }\r\n }\r\n}\r\n\r\nconst UNHANDLEDREJECTION = \"unhandledrejection\";\r\n\r\nfunction globalError(err, promise) {\r\n var rv;\r\n try {\r\n rv = promise.onuncatched(err);\r\n } catch (e) {}\r\n if (rv !== false) try {\r\n var event, eventData = {promise: promise, reason: err};\r\n if (_global.document && document.createEvent) {\r\n event = document.createEvent('Event');\r\n event.initEvent(UNHANDLEDREJECTION, true, true);\r\n extend(event, eventData);\r\n } else if (_global.CustomEvent) {\r\n event = new CustomEvent(UNHANDLEDREJECTION, {detail: eventData});\r\n extend(event, eventData);\r\n }\r\n if (event && _global.dispatchEvent) {\r\n dispatchEvent(event);\r\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\r\n // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.\r\n try {_global.onunhandledrejection(event);} catch (_) {}\r\n }\r\n if (!event.defaultPrevented) {\r\n // Backward compatibility: fire to events registered at Promise.on.error\r\n Promise.on.error.fire(err, promise);\r\n }\r\n } catch (e) {}\r\n}\r\n\r\n\r\n/* **KEEP** \r\n\r\nexport function wrapPromise(PromiseClass) {\r\n var proto = PromiseClass.prototype;\r\n var origThen = proto.then;\r\n \r\n wrappers.add({\r\n snapshot: () => proto.then,\r\n restore: value => {proto.then = value;},\r\n wrap: () => patchedThen\r\n });\r\n\r\n function patchedThen (onFulfilled, onRejected) {\r\n var promise = this;\r\n var onFulfilledProxy = wrap(function(value){\r\n var rv = value;\r\n if (onFulfilled) {\r\n rv = onFulfilled(rv);\r\n if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.\r\n }\r\n --PSD.ref || PSD.finalize();\r\n return rv;\r\n });\r\n var onRejectedProxy = wrap(function(err){\r\n promise._$err = err;\r\n var unhandleds = PSD.unhandleds;\r\n var idx = unhandleds.length,\r\n rv;\r\n while (idx--) if (unhandleds[idx]._$err === err) break;\r\n if (onRejected) {\r\n if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled.\r\n rv = onRejected(err);\r\n if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.\r\n } else {\r\n if (idx === -1) unhandleds.push(promise);\r\n rv = PromiseClass.reject(err);\r\n rv._$nointercept = true; // Prohibit eternal loop.\r\n }\r\n --PSD.ref || PSD.finalize();\r\n return rv;\r\n });\r\n \r\n if (this._$nointercept) return origThen.apply(this, arguments);\r\n ++PSD.ref;\r\n return origThen.call(this, onFulfilledProxy, onRejectedProxy);\r\n }\r\n}\r\n\r\n// Global Promise wrapper\r\nif (_global.Promise) wrapPromise(_global.Promise);\r\n\r\n*/\r\n\r\ndoFakeAutoComplete(() => {\r\n // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie.\r\n asap = (fn, args) => {\r\n setTimeout(()=>{fn.apply(null, args);}, 0);\r\n };\r\n});\r\n","import Promise from './Promise';\r\n\r\nexport function rejection (err, uncaughtHandler) {\r\n // Get the call stack and return a rejected promise.\r\n var rv = Promise.reject(err);\r\n return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv;\r\n}\r\n","/*\r\n * Dexie.js - a minimalistic wrapper for IndexedDB\r\n * ===============================================\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n */\r\n\r\nimport {\r\n keys,\r\n setProp,\r\n isArray,\r\n extend,\r\n props,\r\n derive,\r\n slice,\r\n override,\r\n _global,\r\n doFakeAutoComplete,\r\n asap,\r\n trycatcher,\r\n tryCatch,\r\n getByKeyPath,\r\n setByKeyPath,\r\n delByKeyPath,\r\n shallowClone,\r\n deepClone,\r\n getObjectDiff,\r\n assert,\r\n NO_CHAR_ARRAY,\r\n getArrayOf,\r\n arrayToObject,\r\n hasOwn,\r\n flatten\r\n\r\n} from './utils';\r\nimport { rejection } from './promise-utils';\r\nimport { ModifyError, BulkError, errnames, exceptions, fullNameExceptions, mapError } from './errors';\r\nimport Promise, {wrap, PSD, newScope, usePSD} from './Promise';\r\nimport Events from './Events';\r\nimport {\r\n nop,\r\n mirror,\r\n pureFunctionChain,\r\n hookCreatingChain,\r\n hookUpdatingChain,\r\n hookDeletingChain,\r\n promisableChain\r\n} from './chaining-functions';\r\nimport * as Debug from './debug';\r\n\r\nvar DEXIE_VERSION = '{version}',\r\n maxString = String.fromCharCode(65535),\r\n // maxKey is an Array if indexedDB implementations supports array keys (not supported by IE,Edge or Safari at the moment)\r\n // Otherwise maxKey is maxString. This is handy when needing an open upper border without limit.\r\n maxKey = (function(){try {IDBKeyRange.only([[]]);return [[]];}catch(e){return maxString;}})(),\r\n INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\",\r\n STRING_EXPECTED = \"String expected.\",\r\n connections = [],\r\n isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent),\r\n hasIEDeleteObjectStoreBug = isIEOrEdge,\r\n hangsOnDeleteLargeKeyRange = isIEOrEdge,\r\n dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\r\n\r\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\r\n\r\nexport default function Dexie(dbName, options) {\r\n /// Specify only if you wich to control which addons that should run on this instance\r\n var deps = Dexie.dependencies;\r\n var opts = extend({\r\n // Default Options\r\n addons: Dexie.addons, // Pick statically registered addons by default\r\n autoOpen: true, // Don't require db.open() explicitely.\r\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env.\r\n IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env.\r\n }, options);\r\n var addons = opts.addons,\r\n autoOpen = opts.autoOpen,\r\n indexedDB = opts.indexedDB,\r\n IDBKeyRange = opts.IDBKeyRange;\r\n\r\n var globalSchema = this._dbSchema = {};\r\n var versions = [];\r\n var dbStoreNames = [];\r\n var allTables = {};\r\n ///\r\n var idbdb = null; // Instance of IDBDatabase\r\n var dbOpenError = null;\r\n var isBeingOpened = false;\r\n var openComplete = false;\r\n var READONLY = \"readonly\", READWRITE = \"readwrite\";\r\n var db = this;\r\n var dbReadyResolve,\r\n dbReadyPromise = new Promise(resolve => {\r\n dbReadyResolve = resolve;\r\n }),\r\n cancelOpen,\r\n openCanceller = new Promise((_, reject) => {\r\n cancelOpen = reject;\r\n });\r\n var autoSchema = true;\r\n var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),\r\n hasGetAll;\r\n\r\n function init() {\r\n // Default subscribers to \"versionchange\" and \"blocked\".\r\n // Can be overridden by custom handlers. If custom handlers return false, these default\r\n // behaviours will be prevented.\r\n db.on(\"versionchange\", function (ev) {\r\n // Default behavior for versionchange event is to close database connection.\r\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\r\n // Let's not block the other window from making it's delete() or open() call.\r\n // NOTE! This event is never fired in IE,Edge or Safari.\r\n if (ev.newVersion > 0)\r\n console.warn(`Another connection wants to upgrade database '${db.name}'. Closing db now to resume the upgrade.`);\r\n else\r\n console.warn(`Another connection wants to delete database '${db.name}'. Closing db now to resume the delete request.`);\r\n db.close();\r\n // In many web applications, it would be recommended to force window.reload()\r\n // when this event occurs. To do that, subscribe to the versionchange event\r\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\r\n // The reason for this is that your current web app obviously has old schema code that needs\r\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\r\n // your window is blocking it unless we close it here.\r\n });\r\n db.on(\"blocked\", ev => {\r\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\r\n console.warn(`Dexie.delete('${db.name}') was blocked`);\r\n else\r\n console.warn(`Upgrade '${db.name}' blocked by other connection holding version ${ev.oldVersion/10}`);\r\n });\r\n }\r\n\r\n //\r\n //\r\n //\r\n // ------------------------- Versioning Framework---------------------------\r\n //\r\n //\r\n //\r\n\r\n this.version = function (versionNumber) {\r\n /// \r\n /// \r\n if (idbdb || isBeingOpened) throw new exceptions.Schema(\"Cannot add version when database is open\");\r\n this.verno = Math.max(this.verno, versionNumber);\r\n var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0];\r\n if (versionInstance) return versionInstance;\r\n versionInstance = new Version(versionNumber);\r\n versions.push(versionInstance);\r\n versions.sort(lowerVersionFirst);\r\n return versionInstance;\r\n };\r\n\r\n function Version(versionNumber) {\r\n this._cfg = {\r\n version: versionNumber,\r\n storesSource: null,\r\n dbschema: {},\r\n tables: {},\r\n contentUpgrade: null\r\n };\r\n this.stores({}); // Derive earlier schemas by default.\r\n }\r\n\r\n extend(Version.prototype, {\r\n stores: function (stores) {\r\n /// \r\n /// Defines the schema for a particular version\r\n /// \r\n /// \r\n /// Example:
\r\n /// {users: \"id++,first,last,&username,*email\",
\r\n /// passwords: \"id++,&username\"}
\r\n ///
\r\n /// Syntax: {Table: \"[primaryKey][++],[&][*]index1,[&][*]index2,...\"}

\r\n /// Special characters:
\r\n /// \"&\" means unique key,
\r\n /// \"*\" means value is multiEntry,
\r\n /// \"++\" means auto-increment and only applicable for primary key
\r\n /// \r\n this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;\r\n\r\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\r\n var storesSpec = {};\r\n versions.forEach(function (version) { // 'versions' is always sorted by lowest version first.\r\n extend(storesSpec, version._cfg.storesSource);\r\n });\r\n\r\n var dbschema = (this._cfg.dbschema = {});\r\n this._parseStoresSpec(storesSpec, dbschema);\r\n // Update the latest schema to this version\r\n // Update API\r\n globalSchema = db._dbSchema = dbschema;\r\n removeTablesApi([allTables, db, Transaction.prototype]);\r\n setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema);\r\n dbStoreNames = keys(dbschema);\r\n return this;\r\n },\r\n upgrade: function (upgradeFunction) {\r\n /// Function that performs upgrading actions.\r\n var self = this;\r\n fakeAutoComplete(function () {\r\n upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema));// BUGBUG: No code completion for prev version's tables wont appear.\r\n });\r\n this._cfg.contentUpgrade = upgradeFunction;\r\n return this;\r\n },\r\n _parseStoresSpec: function (stores, outSchema) {\r\n keys(stores).forEach(function (tableName) {\r\n if (stores[tableName] !== null) {\r\n var instanceTemplate = {};\r\n var indexes = parseIndexSyntax(stores[tableName]);\r\n var primKey = indexes.shift();\r\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\r\n if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);\r\n indexes.forEach(function (idx) {\r\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\r\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\r\n setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return \"\"; }) : \"\");\r\n });\r\n outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);\r\n }\r\n });\r\n }\r\n });\r\n \r\n function runUpgraders (oldVersion, idbtrans, reject) {\r\n var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);\r\n trans.create(idbtrans);\r\n trans._completion.catch(reject);\r\n var rejectTransaction = trans._reject.bind(trans);\r\n newScope(function () {\r\n PSD.trans = trans;\r\n if (oldVersion === 0) {\r\n // Create tables:\r\n keys(globalSchema).forEach(function (tableName) {\r\n createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\r\n });\r\n Promise.follow(()=>db.on.populate.fire(trans)).catch(rejectTransaction);\r\n } else\r\n updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);\r\n });\r\n }\r\n\r\n function updateTablesAndIndexes (oldVersion, trans, idbtrans) {\r\n // Upgrade version to version, step-by-step from oldest to newest version.\r\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\r\n var queue = [];\r\n var oldVersionStruct = versions.filter(version => version._cfg.version === oldVersion)[0];\r\n if (!oldVersionStruct) throw new exceptions.Upgrade(\"Dexie specification of currently installed DB version is missing\");\r\n globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;\r\n var anyContentUpgraderHasRun = false;\r\n\r\n var versToRun = versions.filter(v => v._cfg.version > oldVersion);\r\n versToRun.forEach(function (version) {\r\n /// \r\n queue.push(()=>{\r\n var oldSchema = globalSchema;\r\n var newSchema = version._cfg.dbschema;\r\n adjustToExistingIndexNames(oldSchema, idbtrans);\r\n adjustToExistingIndexNames(newSchema, idbtrans);\r\n globalSchema = db._dbSchema = newSchema;\r\n var diff = getSchemaDiff(oldSchema, newSchema); \r\n // Add tables \r\n diff.add.forEach(function (tuple) {\r\n createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\r\n });\r\n // Change tables\r\n diff.change.forEach(function (change) {\r\n if (change.recreate) {\r\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\r\n } else {\r\n var store = idbtrans.objectStore(change.name);\r\n // Add indexes\r\n change.add.forEach(function (idx) {\r\n addIndex(store, idx);\r\n });\r\n // Update indexes\r\n change.change.forEach(function (idx) {\r\n store.deleteIndex(idx.name);\r\n addIndex(store, idx);\r\n });\r\n // Delete indexes\r\n change.del.forEach(function (idxName) {\r\n store.deleteIndex(idxName);\r\n });\r\n }\r\n });\r\n if (version._cfg.contentUpgrade) {\r\n anyContentUpgraderHasRun = true;\r\n return Promise.follow(()=>{\r\n version._cfg.contentUpgrade(trans);\r\n });\r\n }\r\n });\r\n queue.push(function (idbtrans) {\r\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\r\n var newSchema = version._cfg.dbschema;\r\n // Delete old tables\r\n deleteRemovedTables(newSchema, idbtrans);\r\n }\r\n });\r\n });\r\n\r\n // Now, create a queue execution engine\r\n function runQueue () {\r\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\r\n Promise.resolve();\r\n }\r\n \r\n return runQueue().then(()=>{\r\n createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\r\n });\r\n }\r\n\r\n function getSchemaDiff(oldSchema, newSchema) {\r\n var diff = {\r\n del: [], // Array of table names\r\n add: [], // Array of [tableName, newDefinition]\r\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\r\n };\r\n for (var table in oldSchema) {\r\n if (!newSchema[table]) diff.del.push(table);\r\n }\r\n for (table in newSchema) {\r\n var oldDef = oldSchema[table],\r\n newDef = newSchema[table];\r\n if (!oldDef) {\r\n diff.add.push([table, newDef]);\r\n } else {\r\n var change = {\r\n name: table,\r\n def: newDef,\r\n recreate: false,\r\n del: [],\r\n add: [],\r\n change: []\r\n };\r\n if (oldDef.primKey.src !== newDef.primKey.src) {\r\n // Primary key has changed. Remove and re-add table.\r\n change.recreate = true;\r\n diff.change.push(change);\r\n } else {\r\n // Same primary key. Just find out what differs:\r\n var oldIndexes = oldDef.idxByName;\r\n var newIndexes = newDef.idxByName;\r\n for (var idxName in oldIndexes) {\r\n if (!newIndexes[idxName]) change.del.push(idxName);\r\n }\r\n for (idxName in newIndexes) {\r\n var oldIdx = oldIndexes[idxName],\r\n newIdx = newIndexes[idxName];\r\n if (!oldIdx) change.add.push(newIdx);\r\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\r\n }\r\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\r\n diff.change.push(change);\r\n }\r\n }\r\n }\r\n }\r\n return diff;\r\n }\r\n\r\n function createTable(idbtrans, tableName, primKey, indexes) {\r\n /// \r\n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });\r\n indexes.forEach(function (idx) { addIndex(store, idx); });\r\n return store;\r\n }\r\n\r\n function createMissingTables(newSchema, idbtrans) {\r\n keys(newSchema).forEach(function (tableName) {\r\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\r\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\r\n }\r\n });\r\n }\r\n\r\n function deleteRemovedTables(newSchema, idbtrans) {\r\n for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {\r\n var storeName = idbtrans.db.objectStoreNames[i];\r\n if (newSchema[storeName] == null) {\r\n idbtrans.db.deleteObjectStore(storeName);\r\n }\r\n }\r\n }\r\n\r\n function addIndex(store, idx) {\r\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\r\n }\r\n\r\n function dbUncaught(err) {\r\n return db.on.error.fire(err);\r\n }\r\n\r\n //\r\n //\r\n // Dexie Protected API\r\n //\r\n //\r\n\r\n this._allTables = allTables;\r\n\r\n this._tableFactory = function createTable(mode, tableSchema) {\r\n /// \r\n if (mode === READONLY)\r\n return new Table(tableSchema.name, tableSchema, Collection);\r\n else\r\n return new WriteableTable(tableSchema.name, tableSchema);\r\n };\r\n\r\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {\r\n return new Transaction(mode, storeNames, dbschema, parentTransaction);\r\n };\r\n\r\n /* Generate a temporary transaction when db operations are done outside a transactino scope.\r\n */\r\n function tempTransaction(mode, storeNames, fn) { // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\r\n if (!openComplete && (!PSD.letThrough)) {\r\n if (!isBeingOpened) {\r\n if (!autoOpen)\r\n return rejection(new exceptions.DatabaseClosed(), dbUncaught);\r\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\r\n }\r\n return dbReadyPromise.then(()=>tempTransaction(mode, storeNames, fn));\r\n } else {\r\n var trans = db._createTransaction(mode, storeNames, globalSchema);\r\n return trans._promise(mode, function (resolve, reject) {\r\n newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\r\n PSD.trans = trans;\r\n fn(resolve, reject, trans);\r\n });\r\n }).then(result => {\r\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\r\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\r\n // Specifically, to ensure that the following expression will work:\r\n //\r\n // db.friends.put({name: \"Arne\"}).then(function () {\r\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\r\n // assert (count === 1);\r\n // });\r\n // });\r\n //\r\n return trans._completion.then(()=>result);\r\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\r\n trans._reject(err);\r\n return rejection(err);\r\n });*/\r\n }\r\n }\r\n\r\n this._whenReady = function (fn) {\r\n return new Promise (fake || openComplete || PSD.letThrough ? fn : (resolve, reject) => {\r\n if (!isBeingOpened) {\r\n if (!autoOpen) {\r\n reject(new exceptions.DatabaseClosed());\r\n return;\r\n }\r\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\r\n }\r\n dbReadyPromise.then(()=>{\r\n fn(resolve, reject);\r\n });\r\n }).uncaught(dbUncaught);\r\n };\r\n \r\n //\r\n //\r\n //\r\n //\r\n // Dexie API\r\n //\r\n //\r\n //\r\n\r\n this.verno = 0;\r\n\r\n this.open = function () {\r\n if (isBeingOpened || idbdb)\r\n return dbReadyPromise.then(()=> dbOpenError ? rejection(dbOpenError, dbUncaught) : db);\r\n Debug.debug && (openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\r\n isBeingOpened = true;\r\n dbOpenError = null;\r\n openComplete = false;\r\n \r\n // Function pointers to call when the core opening process completes.\r\n var resolveDbReady = dbReadyResolve,\r\n // upgradeTransaction to abort on failure.\r\n upgradeTransaction = null;\r\n \r\n return Promise.race([openCanceller, new Promise((resolve, reject) => {\r\n doFakeAutoComplete(()=>resolve());\r\n \r\n // Make sure caller has specified at least one version\r\n if (versions.length > 0) autoSchema = false;\r\n \r\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\r\n // IE fails when deleting objectStore after reading from it.\r\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\r\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\r\n \r\n // If no API, throw!\r\n if (!indexedDB) throw new exceptions.MissingAPI(\r\n \"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \"+\r\n \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\r\n \r\n var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));\r\n if (!req) throw new exceptions.MissingAPI(\"IndexedDB API not available\"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\r\n req.onerror = wrap(eventRejectHandler(reject));\r\n req.onblocked = wrap(fireOnBlocked);\r\n req.onupgradeneeded = wrap (function (e) {\r\n upgradeTransaction = req.transaction;\r\n if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\r\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\r\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\r\n // do not create a new database by accident here.\r\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\r\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\r\n // Close database and delete it.\r\n req.result.close();\r\n var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\r\n delreq.onsuccess = delreq.onerror = wrap(function () {\r\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\r\n });\r\n } else {\r\n upgradeTransaction.onerror = wrap(eventRejectHandler(reject));\r\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\r\n runUpgraders(oldVer / 10, upgradeTransaction, reject, req);\r\n }\r\n }, reject);\r\n \r\n req.onsuccess = wrap (function () {\r\n // Core opening procedure complete. Now let's just record some stuff.\r\n upgradeTransaction = null;\r\n idbdb = req.result;\r\n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\r\n\r\n if (autoSchema) readGlobalSchema();\r\n else if (idbdb.objectStoreNames.length > 0) {\r\n try {\r\n adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));\r\n } catch (e) {\r\n // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\r\n }\r\n }\r\n \r\n idbdb.onversionchange = wrap(ev => {\r\n db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\r\n db.on(\"versionchange\").fire(ev);\r\n });\r\n \r\n if (!hasNativeGetDatabaseNames) {\r\n // Update localStorage with list of database names\r\n globalDatabaseList(function (databaseNames) {\r\n if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName);\r\n });\r\n }\r\n \r\n resolve();\r\n\r\n }, reject);\r\n })]).then(()=>{\r\n // Before finally resolving the dbReadyPromise and this promise,\r\n // call and await all on('ready') subscribers:\r\n // Dexie.vip() makes subscribers able to use the database while being opened.\r\n // This is a must since these subscribers take part of the opening procedure.\r\n return Dexie.vip(db.on.ready.fire);\r\n }).then(()=>{\r\n // Resolve the db.open() with the db instance.\r\n isBeingOpened = false;\r\n return db;\r\n }).catch(err => {\r\n try {\r\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\r\n upgradeTransaction && upgradeTransaction.abort();\r\n } catch (e) { }\r\n isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).\r\n db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\r\n // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.\r\n dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\r\n return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught().\r\n }).finally(()=>{\r\n openComplete = true;\r\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\r\n });\r\n };\r\n \r\n this.close = function () {\r\n var idx = connections.indexOf(db);\r\n if (idx >= 0) connections.splice(idx, 1); \r\n if (idbdb) {\r\n try {idbdb.close();} catch(e){}\r\n idbdb = null;\r\n }\r\n autoOpen = false;\r\n dbOpenError = new exceptions.DatabaseClosed();\r\n if (isBeingOpened)\r\n cancelOpen(dbOpenError);\r\n // Reset dbReadyPromise promise:\r\n dbReadyPromise = new Promise(resolve => {\r\n dbReadyResolve = resolve;\r\n });\r\n openCanceller = new Promise((_, reject) => {\r\n cancelOpen = reject;\r\n });\r\n };\r\n \r\n this.delete = function () {\r\n var hasArguments = arguments.length > 0;\r\n return new Promise(function (resolve, reject) {\r\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\r\n if (isBeingOpened) {\r\n dbReadyPromise.then(doDelete);\r\n } else {\r\n doDelete();\r\n }\r\n function doDelete() {\r\n db.close();\r\n var req = indexedDB.deleteDatabase(dbName);\r\n req.onsuccess = wrap(function () {\r\n if (!hasNativeGetDatabaseNames) {\r\n globalDatabaseList(function(databaseNames) {\r\n var pos = databaseNames.indexOf(dbName);\r\n if (pos >= 0) return databaseNames.splice(pos, 1);\r\n });\r\n }\r\n resolve();\r\n });\r\n req.onerror = wrap(eventRejectHandler(reject));\r\n req.onblocked = fireOnBlocked;\r\n }\r\n }).uncaught(dbUncaught);\r\n };\r\n\r\n this.backendDB = function () {\r\n return idbdb;\r\n };\r\n\r\n this.isOpen = function () {\r\n return idbdb !== null;\r\n };\r\n this.hasFailed = function () {\r\n return dbOpenError !== null;\r\n };\r\n this.dynamicallyOpened = function() {\r\n return autoSchema;\r\n };\r\n\r\n //\r\n // Properties\r\n //\r\n this.name = dbName;\r\n\r\n // db.tables - an array of all Table instances.\r\n setProp(this, \"tables\", {\r\n get: function () {\r\n /// \r\n return keys(allTables).map(function (name) { return allTables[name]; });\r\n }\r\n });\r\n\r\n //\r\n // Events\r\n //\r\n this.on = Events(this, \"error\", \"populate\", \"blocked\", \"versionchange\", {ready: [promisableChain, nop]});\r\n this.on.error.subscribe = Debug.deprecated(\"Dexie.on.error\", this.on.error.subscribe);\r\n this.on.error.unsubscribe = Debug.deprecated(\"Dexie.on.error.unsubscribe\", this.on.error.unsubscribe);\r\n\r\n this.on.ready.subscribe = override (this.on.ready.subscribe, function (subscribe) {\r\n return (subscriber, bSticky) => {\r\n Dexie.vip(()=>{\r\n if (openComplete) {\r\n // Database already open. Call subscriber asap.\r\n if (!dbOpenError) Promise.resolve().then(subscriber);\r\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \r\n if (bSticky) subscribe(subscriber); \r\n } else {\r\n // Database not yet open. Subscribe to it.\r\n subscribe(subscriber);\r\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\r\n if (!bSticky) subscribe(function unsubscribe() {\r\n db.on.ready.unsubscribe(subscriber);\r\n db.on.ready.unsubscribe(unsubscribe);\r\n });\r\n }\r\n });\r\n }\r\n });\r\n\r\n fakeAutoComplete(function () {\r\n db.on(\"populate\").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema));\r\n db.on(\"error\").fire(new Error());\r\n });\r\n\r\n this.transaction = function (mode, tableInstances, scopeFunc) {\r\n /// \r\n ///\r\n /// \r\n /// \"r\" for readonly, or \"rw\" for readwrite\r\n /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction\r\n /// Function to execute with transaction\r\n\r\n // Let table arguments be all arguments between mode and last argument.\r\n var i = arguments.length;\r\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\r\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\r\n // and clone arguments except the first one into local var 'args'.\r\n var args = new Array(i - 1);\r\n while (--i) args[i-1] = arguments[i];\r\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\r\n scopeFunc = args.pop();\r\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\r\n var parentTransaction = PSD.trans;\r\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\r\n if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;\r\n var onlyIfCompatible = mode.indexOf('?') !== -1;\r\n mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\r\n \r\n try {\r\n //\r\n // Get storeNames from arguments. Either through given table instances, or through given table names.\r\n //\r\n var storeNames = tables.map(table => {\r\n var storeName = table instanceof Table ? table.name : table;\r\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\r\n return storeName;\r\n });\r\n\r\n //\r\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\r\n //\r\n if (mode == \"r\" || mode == READONLY)\r\n mode = READONLY;\r\n else if (mode == \"rw\" || mode == READWRITE)\r\n mode = READWRITE;\r\n else\r\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\r\n\r\n if (parentTransaction) {\r\n // Basic checks\r\n if (parentTransaction.mode === READONLY && mode === READWRITE) {\r\n if (onlyIfCompatible) {\r\n // Spawn new transaction instead.\r\n parentTransaction = null; \r\n }\r\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\r\n }\r\n if (parentTransaction) {\r\n storeNames.forEach(function (storeName) {\r\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\r\n if (onlyIfCompatible) {\r\n // Spawn new transaction instead.\r\n parentTransaction = null; \r\n }\r\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\r\n \" not included in parent transaction.\");\r\n }\r\n });\r\n }\r\n }\r\n } catch (e) {\r\n return parentTransaction ?\r\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\r\n rejection (e, dbUncaught);\r\n }\r\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\r\n return (parentTransaction ?\r\n parentTransaction._promise(mode, enterTransactionScope, \"lock\") :\r\n db._whenReady (enterTransactionScope));\r\n \r\n function enterTransactionScope(resolve) {\r\n var parentPSD = PSD;\r\n resolve(Promise.resolve().then(()=>newScope(()=>{\r\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\r\n PSD.transless = PSD.transless || parentPSD;\r\n // Our transaction.\r\n //return new Promise((resolve, reject) => {\r\n var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);\r\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\r\n PSD.trans = trans;\r\n \r\n\r\n if (parentTransaction) {\r\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\r\n trans.idbtrans = parentTransaction.idbtrans;\r\n } else {\r\n trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.\r\n }\r\n \r\n // Provide arguments to the scope function (for backward compatibility)\r\n var tableArgs = storeNames.map(function (name) { return allTables[name]; });\r\n tableArgs.push(trans);\r\n\r\n var returnValue;\r\n return Promise.follow(()=>{\r\n // Finally, call the scope function with our table and transaction arguments.\r\n returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func.\r\n if (returnValue) {\r\n if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\r\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\r\n returnValue = awaitIterator(returnValue);\r\n } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) {\r\n throw new exceptions.IncompatiblePromise(\"Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: \" + scopeFunc.toString());\r\n }\r\n }\r\n }).uncaught(dbUncaught).then(()=>{\r\n if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion.\r\n return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well.\r\n }).then(()=>{\r\n return returnValue;\r\n }).catch (e => {\r\n //reject(e);\r\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\r\n return rejection(e);\r\n });\r\n //});\r\n })));\r\n }\r\n };\r\n\r\n this.table = function (tableName) {\r\n /// \r\n if (fake && autoSchema) return new WriteableTable(tableName);\r\n if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\r\n return allTables[tableName];\r\n };\r\n\r\n //\r\n //\r\n //\r\n // Table Class\r\n //\r\n //\r\n //\r\n function Table(name, tableSchema, collClass) {\r\n /// \r\n this.name = name;\r\n this.schema = tableSchema;\r\n this.hook = allTables[name] ? allTables[name].hook : Events(null, {\r\n \"creating\": [hookCreatingChain, nop],\r\n \"reading\": [pureFunctionChain, mirror],\r\n \"updating\": [hookUpdatingChain, nop],\r\n \"deleting\": [hookDeletingChain, nop]\r\n });\r\n this._collClass = collClass || Collection;\r\n }\r\n\r\n props(Table.prototype, {\r\n\r\n //\r\n // Table Protected Methods\r\n //\r\n\r\n _trans: function getTransaction(mode, fn, writeLocked) {\r\n var trans = PSD.trans;\r\n return trans && trans.db === db ?\r\n trans._promise (mode, fn, writeLocked) :\r\n tempTransaction (mode, [this.name], fn);\r\n },\r\n _idbstore: function getIDBObjectStore(mode, fn, writeLocked) {\r\n if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion.\r\n var trans = PSD.trans,\r\n tableName = this.name;\r\n function supplyIdbStore (resolve, reject, trans) {\r\n fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);\r\n }\r\n return trans && trans.db === db ?\r\n trans._promise (mode, supplyIdbStore, writeLocked) :\r\n tempTransaction (mode, [this.name], supplyIdbStore);\r\n },\r\n\r\n //\r\n // Table Public Methods\r\n //\r\n get: function (key, cb) {\r\n var self = this;\r\n return this._idbstore(READONLY, function (resolve, reject, idbstore) {\r\n fake && resolve(self.schema.instanceTemplate);\r\n var req = idbstore.get(key);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = wrap(function () {\r\n resolve(self.hook.reading.fire(req.result));\r\n }, reject);\r\n }).then(cb);\r\n },\r\n where: function (indexName) {\r\n return new WhereClause(this, indexName);\r\n },\r\n count: function (cb) {\r\n return this.toCollection().count(cb);\r\n },\r\n offset: function (offset) {\r\n return this.toCollection().offset(offset);\r\n },\r\n limit: function (numRows) {\r\n return this.toCollection().limit(numRows);\r\n },\r\n reverse: function () {\r\n return this.toCollection().reverse();\r\n },\r\n filter: function (filterFunction) {\r\n return this.toCollection().and(filterFunction);\r\n },\r\n each: function (fn) {\r\n return this.toCollection().each(fn);\r\n },\r\n toArray: function (cb) {\r\n return this.toCollection().toArray(cb);\r\n },\r\n orderBy: function (index) {\r\n return new this._collClass(new WhereClause(this, index));\r\n },\r\n\r\n toCollection: function () {\r\n return new this._collClass(new WhereClause(this));\r\n },\r\n\r\n mapToClass: function (constructor, structure) {\r\n /// \r\n /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making\r\n /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.\r\n /// \r\n /// Constructor function representing the class.\r\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\r\n /// know what type each member has. Example: {name: String, emailAddresses: [String], password}\r\n this.schema.mappedClass = constructor;\r\n var instanceTemplate = Object.create(constructor.prototype);\r\n if (structure) {\r\n // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.\r\n applyStructure(instanceTemplate, structure);\r\n }\r\n this.schema.instanceTemplate = instanceTemplate;\r\n\r\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\r\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\r\n var readHook = function (obj) {\r\n if (!obj) return obj; // No valid object. (Value is null). Return as is.\r\n // Create a new object that derives from constructor:\r\n var res = Object.create(constructor.prototype);\r\n // Clone members:\r\n for (var m in obj) if (hasOwn(obj, m)) try {res[m] = obj[m];} catch(_){}\r\n return res;\r\n };\r\n\r\n if (this.schema.readHook) {\r\n this.hook.reading.unsubscribe(this.schema.readHook);\r\n }\r\n this.schema.readHook = readHook;\r\n this.hook(\"reading\", readHook);\r\n return constructor;\r\n },\r\n defineClass: function (structure) {\r\n /// \r\n /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database\r\n /// as well as making it possible to extend the prototype of the returned constructor function.\r\n /// \r\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\r\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\r\n return this.mapToClass(Dexie.defineClass(structure), structure);\r\n }\r\n });\r\n\r\n //\r\n //\r\n //\r\n // WriteableTable Class (extends Table)\r\n //\r\n //\r\n //\r\n function WriteableTable(name, tableSchema, collClass) {\r\n Table.call(this, name, tableSchema, collClass || WriteableCollection);\r\n }\r\n\r\n function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {\r\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\r\n errorList.push(e);\r\n done && done();\r\n });\r\n }\r\n\r\n function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {\r\n // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],\r\n // else keysOrTuples must be just an array of keys: [key1, key2, ...].\r\n return new Promise((resolve, reject)=>{\r\n var len = keysOrTuples.length,\r\n lastItem = len - 1;\r\n if (len === 0) return resolve();\r\n if (!hasDeleteHook) {\r\n for (var i=0; i < len; ++i) {\r\n var req = idbstore.delete(keysOrTuples[i]);\r\n req.onerror = wrap(eventRejectHandler(reject));\r\n if (i === lastItem) req.onsuccess = wrap(()=>resolve());\r\n }\r\n } else {\r\n var hookCtx,\r\n errorHandler = hookedEventRejectHandler(reject),\r\n successHandler = hookedEventSuccessHandler(null);\r\n tryCatch(()=> {\r\n for (var i = 0; i < len; ++i) {\r\n hookCtx = {onsuccess: null, onerror: null};\r\n var tuple = keysOrTuples[i];\r\n deletingHook.call(hookCtx, tuple[0], tuple[1], trans);\r\n var req = idbstore.delete(tuple[0]);\r\n req._hookCtx = hookCtx;\r\n req.onerror = errorHandler;\r\n if (i === lastItem)\r\n req.onsuccess = hookedEventSuccessHandler(resolve);\r\n else\r\n req.onsuccess = successHandler;\r\n }\r\n }, err=>{\r\n hookCtx.onerror && hookCtx.onerror(err);\r\n throw err;\r\n });\r\n }\r\n }).uncaught(dbUncaught);\r\n }\r\n\r\n derive(WriteableTable).from(Table).extend({\r\n bulkDelete: function (keys) {\r\n if (this.hook.deleting.fire === nop) {\r\n return this._idbstore(READWRITE, (resolve, reject, idbstore, trans) => {\r\n resolve (bulkDelete(idbstore, trans, keys, false, nop));\r\n });\r\n } else {\r\n return this\r\n .where(':id')\r\n .anyOf(keys)\r\n .delete()\r\n .then(()=>{}); // Resolve with undefined.\r\n }\r\n },\r\n bulkPut: function(objects, keys) {\r\n return this._idbstore(READWRITE, (resolve, reject, idbstore) => {\r\n if (!idbstore.keyPath && !this.schema.primKey.auto && !keys)\r\n throw new exceptions.InvalidArgument(\"bulkPut() with non-inbound keys requires keys array in second argument\");\r\n if (idbstore.keyPath && keys)\r\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\r\n if (keys && keys.length !== objects.length)\r\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\r\n if (objects.length === 0) return resolve(); // Caller provided empty list.\r\n const done = result => {\r\n if (errorList.length === 0) resolve(result);\r\n else reject(new BulkError(`${this.name}.bulkPut(): ${errorList.length} of ${numObjs} operations failed`, errorList));\r\n };\r\n var req,\r\n errorList = [],\r\n errorHandler,\r\n numObjs = objects.length,\r\n table = this;\r\n if (this.hook.creating.fire === nop && this.hook.updating.fire === nop) {\r\n //\r\n // Standard Bulk (no 'creating' or 'updating' hooks to care about)\r\n //\r\n errorHandler = BulkErrorHandlerCatchAll(errorList);\r\n for (var i = 0, l = objects.length; i < l; ++i) {\r\n req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);\r\n req.onerror = errorHandler;\r\n }\r\n // Only need to catch success or error on the last operation\r\n // according to the IDB spec.\r\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\r\n req.onsuccess = eventSuccessHandler(done);\r\n } else {\r\n var effectiveKeys = keys || idbstore.keyPath && objects.map(o=>getByKeyPath(o, idbstore.keyPath));\r\n // Generate map of {[key]: object}\r\n var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, (key, i) => key != null && [key, objects[i]]); \r\n var promise = !effectiveKeys ?\r\n\r\n // Auto-incremented key-less objects only without any keys argument.\r\n table.bulkAdd(objects) :\r\n\r\n // Keys provided. Either as inbound in provided objects, or as a keys argument.\r\n // Begin with updating those that exists in DB:\r\n table.where(':id').anyOf(effectiveKeys.filter(key => key != null)).modify(function () {\r\n this.value = objectLookup[this.primKey];\r\n objectLookup[this.primKey] = null; // Mark as \"don't add this\"\r\n }).catch(ModifyError, e => {\r\n errorList = e.failures; // No need to concat here. These are the first errors added.\r\n }).then(()=> {\r\n // Now, let's examine which items didnt exist so we can add them:\r\n var objsToAdd = [],\r\n keysToAdd = keys && [];\r\n // Iterate backwards. Why? Because if same key was used twice, just add the last one.\r\n for (var i=effectiveKeys.length-1; i>=0; --i) {\r\n var key = effectiveKeys[i];\r\n if (key == null || objectLookup[key]) {\r\n objsToAdd.push(objects[i]);\r\n keys && keysToAdd.push(key);\r\n if (key != null) objectLookup[key] = null; // Mark as \"dont add again\"\r\n }\r\n }\r\n // The items are in reverse order so reverse them before adding.\r\n // Could be important in order to get auto-incremented keys the way the caller\r\n // would expect. Could have used unshift instead of push()/reverse(),\r\n // but: http://jsperf.com/unshift-vs-reverse\r\n objsToAdd.reverse();\r\n keys && keysToAdd.reverse();\r\n return table.bulkAdd(objsToAdd, keysToAdd);\r\n }).then(lastAddedKey => {\r\n // Resolve with key of the last object in given arguments to bulkPut():\r\n var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.\r\n return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;\r\n });\r\n\r\n promise.then(done).catch(BulkError, e => {\r\n // Concat failure from ModifyError and reject using our 'done' method.\r\n errorList = errorList.concat(e.failures);\r\n done();\r\n }).catch(reject);\r\n }\r\n }, \"locked\"); // If called from transaction scope, lock transaction til all steps are done.\r\n },\r\n bulkAdd: function(objects, keys) {\r\n var self = this,\r\n creatingHook = this.hook.creating.fire;\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\r\n if (!idbstore.keyPath && !self.schema.primKey.auto && !keys)\r\n throw new exceptions.InvalidArgument(\"bulkAdd() with non-inbound keys requires keys array in second argument\");\r\n if (idbstore.keyPath && keys)\r\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\r\n if (keys && keys.length !== objects.length)\r\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\r\n if (objects.length === 0) return resolve(); // Caller provided empty list.\r\n function done(result) {\r\n if (errorList.length === 0) resolve(result);\r\n else reject(new BulkError(`${self.name}.bulkAdd(): ${errorList.length} of ${numObjs} operations failed`, errorList));\r\n }\r\n var req,\r\n errorList = [],\r\n errorHandler,\r\n successHandler,\r\n numObjs = objects.length;\r\n if (creatingHook !== nop) {\r\n //\r\n // There are subscribers to hook('creating')\r\n // Must behave as documented.\r\n //\r\n var keyPath = idbstore.keyPath,\r\n hookCtx;\r\n errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);\r\n successHandler = hookedEventSuccessHandler(null);\r\n\r\n tryCatch(() => {\r\n for (var i=0, l = objects.length; i < l; ++i) {\r\n hookCtx = { onerror: null, onsuccess: null };\r\n var key = keys && keys[i];\r\n var obj = objects[i],\r\n effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,\r\n keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);\r\n if (effectiveKey == null && keyToUse != null) {\r\n if (keyPath) {\r\n obj = deepClone(obj);\r\n setByKeyPath(obj, keyPath, keyToUse);\r\n } else {\r\n key = keyToUse;\r\n }\r\n }\r\n req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\r\n req._hookCtx = hookCtx;\r\n if (i < l - 1) {\r\n req.onerror = errorHandler;\r\n if (hookCtx.onsuccess)\r\n req.onsuccess = successHandler;\r\n }\r\n }\r\n }, err => {\r\n hookCtx.onerror && hookCtx.onerror(err);\r\n throw err;\r\n });\r\n\r\n req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);\r\n req.onsuccess = hookedEventSuccessHandler(done);\r\n } else {\r\n //\r\n // Standard Bulk (no 'creating' hook to care about)\r\n //\r\n errorHandler = BulkErrorHandlerCatchAll(errorList);\r\n for (var i = 0, l = objects.length; i < l; ++i) {\r\n req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);\r\n req.onerror = errorHandler;\r\n }\r\n // Only need to catch success or error on the last operation\r\n // according to the IDB spec.\r\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\r\n req.onsuccess = eventSuccessHandler(done);\r\n }\r\n });\r\n },\r\n add: function (obj, key) {\r\n /// \r\n /// Add an object to the database. In case an object with same primary key already exists, the object will not be added.\r\n /// \r\n /// A javascript object to insert\r\n /// Primary key\r\n var creatingHook = this.hook.creating.fire;\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\r\n var hookCtx = {onsuccess: null, onerror: null};\r\n if (creatingHook !== nop) {\r\n var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined);\r\n var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when(\"creating\") to generate the key.\r\n if (effectiveKey == null && keyToUse != null) { // Using \"==\" and \"!=\" to check for either null or undefined!\r\n if (idbstore.keyPath)\r\n setByKeyPath(obj, idbstore.keyPath, keyToUse);\r\n else\r\n key = keyToUse;\r\n }\r\n }\r\n try {\r\n var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\r\n req._hookCtx = hookCtx;\r\n req.onerror = hookedEventRejectHandler(reject);\r\n req.onsuccess = hookedEventSuccessHandler(function (result) {\r\n // TODO: Remove these two lines in next major release (2.0?)\r\n // It's no good practice to have side effects on provided parameters\r\n var keyPath = idbstore.keyPath;\r\n if (keyPath) setByKeyPath(obj, keyPath, result);\r\n resolve(result);\r\n });\r\n } catch (e) {\r\n if (hookCtx.onerror) hookCtx.onerror(e);\r\n throw e;\r\n }\r\n });\r\n },\r\n\r\n put: function (obj, key) {\r\n /// \r\n /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.\r\n /// \r\n /// A javascript object to insert or update\r\n /// Primary key\r\n var self = this,\r\n creatingHook = this.hook.creating.fire,\r\n updatingHook = this.hook.updating.fire;\r\n if (creatingHook !== nop || updatingHook !== nop) {\r\n //\r\n // People listens to when(\"creating\") or when(\"updating\") events!\r\n // We must know whether the put operation results in an CREATE or UPDATE.\r\n //\r\n return this._trans(READWRITE, function (resolve, reject, trans) {\r\n // Since key is optional, make sure we get it from obj if not provided\r\n var effectiveKey = (key !== undefined) ? key : (self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath));\r\n if (effectiveKey == null) { // \"== null\" means checking for either null or undefined.\r\n // No primary key. Must use add().\r\n self.add(obj).then(resolve, reject);\r\n } else {\r\n // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().\r\n trans._lock(); // Needed because operation is splitted into modify() and add().\r\n // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.\r\n obj = deepClone(obj);\r\n self.where(\":id\").equals(effectiveKey).modify(function () {\r\n // Replace extisting value with our object\r\n // CRUD event firing handled in WriteableCollection.modify()\r\n this.value = obj;\r\n }).then(function (count) {\r\n if (count === 0) {\r\n // Object's key was not found. Add the object instead.\r\n // CRUD event firing will be done in add()\r\n return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key.\r\n } else {\r\n return effectiveKey; // Resolve with the provided key.\r\n }\r\n }).finally(function () {\r\n trans._unlock();\r\n }).then(resolve, reject);\r\n }\r\n });\r\n } else {\r\n // Use the standard IDB put() method.\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\r\n var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = function (ev) {\r\n var keyPath = idbstore.keyPath;\r\n if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);\r\n resolve(req.result);\r\n };\r\n });\r\n }\r\n },\r\n\r\n 'delete': function (key) {\r\n /// Primary key of the object to delete\r\n if (this.hook.deleting.subscribers.length) {\r\n // People listens to when(\"deleting\") event. Must implement delete using WriteableCollection.delete() that will\r\n // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted.\r\n return this.where(\":id\").equals(key).delete();\r\n } else {\r\n // No one listens. Use standard IDB delete() method.\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\r\n var req = idbstore.delete(key);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = function () {\r\n resolve(req.result);\r\n };\r\n });\r\n }\r\n },\r\n\r\n clear: function () {\r\n if (this.hook.deleting.subscribers.length) {\r\n // People listens to when(\"deleting\") event. Must implement delete using WriteableCollection.delete() that will\r\n // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted.\r\n return this.toCollection().delete();\r\n } else {\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\r\n var req = idbstore.clear();\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = function () {\r\n resolve(req.result);\r\n };\r\n });\r\n }\r\n },\r\n\r\n update: function (keyOrObject, modifications) {\r\n if (typeof modifications !== 'object' || isArray(modifications))\r\n throw new exceptions.InvalidArgument(\"Modifications must be an object.\");\r\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\r\n // object to modify. Also modify given object with the modifications:\r\n keys(modifications).forEach(function (keyPath) {\r\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\r\n });\r\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\r\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\r\n \"Given object does not contain its primary key\"), dbUncaught);\r\n return this.where(\":id\").equals(key).modify(modifications);\r\n } else {\r\n // key to modify\r\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\r\n }\r\n }\r\n });\r\n \r\n //\r\n //\r\n //\r\n // Transaction Class\r\n //\r\n //\r\n //\r\n function Transaction(mode, storeNames, dbschema, parent) {\r\n /// \r\n /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.\r\n /// \r\n /// Any of \"readwrite\" or \"readonly\"\r\n /// Array of table names to operate on\r\n this.db = db;\r\n this.mode = mode;\r\n this.storeNames = storeNames;\r\n this.idbtrans = null;\r\n this.on = Events(this, \"complete\", \"error\", \"abort\");\r\n this.parent = parent || null;\r\n this.active = true;\r\n this._tables = null;\r\n this._reculock = 0;\r\n this._blockedFuncs = [];\r\n this._psd = null;\r\n this._dbschema = dbschema;\r\n this._resolve = null;\r\n this._reject = null;\r\n this._completion = new Promise ((resolve, reject) => {\r\n this._resolve = resolve;\r\n this._reject = reject;\r\n }).uncaught(dbUncaught);\r\n \r\n this._completion.then(\r\n ()=> {this.on.complete.fire();},\r\n e => {\r\n this.on.error.fire(e);\r\n this.parent ?\r\n this.parent._reject(e) :\r\n this.active && this.idbtrans && this.idbtrans.abort();\r\n this.active = false;\r\n return rejection(e); // Indicate we actually DO NOT catch this error.\r\n });\r\n }\r\n\r\n props(Transaction.prototype, {\r\n //\r\n // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)\r\n //\r\n _lock: function () {\r\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\r\n // Temporary set all requests into a pending queue if they are called before database is ready.\r\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\r\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\r\n return this;\r\n },\r\n _unlock: function () {\r\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\r\n if (--this._reculock === 0) {\r\n if (!PSD.global) PSD.lockOwnerFor = null;\r\n while (this._blockedFuncs.length > 0 && !this._locked()) {\r\n var fn = this._blockedFuncs.shift();\r\n try { fn(); } catch (e) { }\r\n }\r\n }\r\n return this;\r\n },\r\n _locked: function () {\r\n // Checks if any write-lock is applied on this transaction.\r\n // To simplify the Dexie API for extension implementations, we support recursive locks.\r\n // This is accomplished by using \"Promise Specific Data\" (PSD).\r\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\r\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\r\n // * callback given to the Promise() constructor (function (resolve, reject){...})\r\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\r\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\r\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\r\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\r\n return this._reculock && PSD.lockOwnerFor !== this;\r\n },\r\n create: function (idbtrans) {\r\n assert(!this.idbtrans);\r\n if (!idbtrans && !idbdb) {\r\n switch (dbOpenError && dbOpenError.name) {\r\n case \"DatabaseClosedError\":\r\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\r\n throw new exceptions.DatabaseClosed(dbOpenError);\r\n case \"MissingAPIError\":\r\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\r\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\r\n default:\r\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\r\n throw new exceptions.OpenFailed(dbOpenError);\r\n }\r\n }\r\n if (!this.active) throw new exceptions.TransactionInactive();\r\n assert(this._completion._state === null);\r\n\r\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);\r\n idbtrans.onerror = wrap(ev => {\r\n preventDefault(ev);// Prohibit default bubbling to window.error\r\n this._reject(idbtrans.error);\r\n });\r\n idbtrans.onabort = wrap(ev => {\r\n preventDefault(ev);\r\n this.active && this._reject(new exceptions.Abort());\r\n this.active = false;\r\n this.on(\"abort\").fire(ev);\r\n });\r\n idbtrans.oncomplete = wrap(() => {\r\n this.active = false;\r\n this._resolve();\r\n });\r\n return this;\r\n },\r\n _promise: function (mode, fn, bWriteLock) {\r\n var self = this;\r\n return newScope(function() {\r\n var p;\r\n // Read lock always\r\n if (!self._locked()) {\r\n p = self.active ? new Promise(function (resolve, reject) {\r\n if (mode === READWRITE && self.mode !== READWRITE)\r\n throw new exceptions.ReadOnly(\"Transaction is readonly\");\r\n if (!self.idbtrans && mode) self.create();\r\n if (bWriteLock) self._lock(); // Write lock if write operation is requested\r\n fn(resolve, reject, self);\r\n }) : rejection(new exceptions.TransactionInactive());\r\n if (self.active && bWriteLock) p.finally(function () {\r\n self._unlock();\r\n });\r\n } else {\r\n // Transaction is write-locked. Wait for mutex.\r\n p = new Promise(function (resolve, reject) {\r\n self._blockedFuncs.push(function () {\r\n self._promise(mode, fn, bWriteLock).then(resolve, reject);\r\n });\r\n });\r\n }\r\n p._lib = true;\r\n return p.uncaught(dbUncaught);\r\n });\r\n },\r\n\r\n //\r\n // Transaction Public Properties and Methods\r\n //\r\n abort: function () {\r\n this.active && this._reject(new exceptions.Abort());\r\n this.active = false;\r\n },\r\n \r\n tables: {\r\n get: Debug.deprecated (\"Transaction.tables\", function () {\r\n return arrayToObject(this.storeNames, name => [name, allTables[name]]);\r\n }, \"Use db.tables()\")\r\n },\r\n\r\n complete: Debug.deprecated (\"Transaction.complete()\", function (cb) {\r\n return this.on(\"complete\", cb);\r\n }),\r\n \r\n error: Debug.deprecated (\"Transaction.error()\", function (cb) {\r\n return this.on(\"error\", cb);\r\n }),\r\n \r\n table: Debug.deprecated (\"Transaction.table()\", function (name) {\r\n if (this.storeNames.indexOf(name) === -1)\r\n throw new exceptions.InvalidTable(\"Table \" + name + \" not in transaction\");\r\n return allTables[name];\r\n })\r\n \r\n });\r\n\r\n //\r\n //\r\n //\r\n // WhereClause\r\n //\r\n //\r\n //\r\n function WhereClause(table, index, orCollection) {\r\n /// \r\n /// \r\n /// \r\n this._ctx = {\r\n table: table,\r\n index: index === \":id\" ? null : index,\r\n collClass: table._collClass,\r\n or: orCollection\r\n };\r\n }\r\n\r\n props(WhereClause.prototype, function () {\r\n\r\n // WhereClause private methods\r\n\r\n function fail(collectionOrWhereClause, err, T) {\r\n var collection = collectionOrWhereClause instanceof WhereClause ?\r\n new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) :\r\n collectionOrWhereClause;\r\n \r\n collection._ctx.error = T ? new T(err) : new TypeError(err);\r\n return collection;\r\n }\r\n\r\n function emptyCollection(whereClause) {\r\n return new whereClause._ctx.collClass(whereClause, function() { return IDBKeyRange.only(\"\"); }).limit(0);\r\n }\r\n\r\n function upperFactory(dir) {\r\n return dir === \"next\" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); };\r\n }\r\n function lowerFactory(dir) {\r\n return dir === \"next\" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); };\r\n }\r\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\r\n var length = Math.min(key.length, lowerNeedle.length);\r\n var llp = -1;\r\n for (var i = 0; i < length; ++i) {\r\n var lwrKeyChar = lowerKey[i];\r\n if (lwrKeyChar !== lowerNeedle[i]) {\r\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\r\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\r\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\r\n return null;\r\n }\r\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\r\n }\r\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\r\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\r\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\r\n }\r\n\r\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\r\n /// \r\n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\r\n needlesLen = needles.length;\r\n if (!needles.every(s => typeof s === 'string')) {\r\n return fail(whereClause, STRING_EXPECTED);\r\n }\r\n function initDirection(dir) {\r\n upper = upperFactory(dir);\r\n lower = lowerFactory(dir);\r\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\r\n var needleBounds = needles.map(function (needle){\r\n return {lower: lower(needle), upper: upper(needle)};\r\n }).sort(function(a,b) {\r\n return compare(a.lower, b.lower);\r\n });\r\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\r\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\r\n direction = dir;\r\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\r\n }\r\n initDirection(\"next\");\r\n\r\n var c = new whereClause._ctx.collClass(whereClause, function() {\r\n return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix);\r\n });\r\n\r\n c._ondirectionchange = function (direction) {\r\n // This event onlys occur before filter is called the first time.\r\n initDirection(direction);\r\n };\r\n\r\n var firstPossibleNeedle = 0;\r\n\r\n c._addAlgorithm(function (cursor, advance, resolve) {\r\n /// \r\n /// \r\n /// \r\n var key = cursor.key;\r\n if (typeof key !== 'string') return false;\r\n var lowerKey = lower(key);\r\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\r\n return true;\r\n } else {\r\n var lowestPossibleCasing = null;\r\n for (var i=firstPossibleNeedle; i 0) {\r\n lowestPossibleCasing = casing;\r\n }\r\n }\r\n if (lowestPossibleCasing !== null) {\r\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\r\n } else {\r\n advance(resolve);\r\n }\r\n return false;\r\n }\r\n });\r\n return c;\r\n }\r\n\r\n //\r\n // WhereClause public methods\r\n //\r\n return {\r\n between: function (lower, upper, includeLower, includeUpper) {\r\n /// \r\n /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.\r\n /// \r\n /// \r\n /// \r\n /// Whether items that equals lower should be included. Default true.\r\n /// Whether items that equals upper should be included. Default false.\r\n /// \r\n includeLower = includeLower !== false; // Default to true\r\n includeUpper = includeUpper === true; // Default to false\r\n try {\r\n if ((cmp(lower, upper) > 0) ||\r\n (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\r\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\r\n return new this._ctx.collClass(this, function() { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); });\r\n } catch (e) {\r\n return fail(this, INVALID_KEY_ARGUMENT);\r\n }\r\n },\r\n equals: function (value) {\r\n return new this._ctx.collClass(this, function() { return IDBKeyRange.only(value); });\r\n },\r\n above: function (value) {\r\n return new this._ctx.collClass(this, function() { return IDBKeyRange.lowerBound(value, true); });\r\n },\r\n aboveOrEqual: function (value) {\r\n return new this._ctx.collClass(this, function() { return IDBKeyRange.lowerBound(value); });\r\n },\r\n below: function (value) {\r\n return new this._ctx.collClass(this, function() { return IDBKeyRange.upperBound(value, true); });\r\n },\r\n belowOrEqual: function (value) {\r\n return new this._ctx.collClass(this, function() { return IDBKeyRange.upperBound(value); });\r\n },\r\n startsWith: function (str) {\r\n /// \r\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\r\n return this.between(str, str + maxString, true, true);\r\n },\r\n startsWithIgnoreCase: function (str) {\r\n /// \r\n if (str === \"\") return this.startsWith(str);\r\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString);\r\n },\r\n equalsIgnoreCase: function (str) {\r\n /// \r\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], \"\");\r\n },\r\n anyOfIgnoreCase: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n if (set.length === 0) return emptyCollection(this);\r\n return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, \"\");\r\n },\r\n startsWithAnyOfIgnoreCase: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n if (set.length === 0) return emptyCollection(this);\r\n return addIgnoreCaseAlgorithm(this, function (x, a) {\r\n return a.some(function(n){\r\n return x.indexOf(n) === 0;\r\n });}, set, maxString);\r\n },\r\n anyOf: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n var compare = ascending;\r\n try { set.sort(compare); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT); }\r\n if (set.length === 0) return emptyCollection(this);\r\n var c = new this._ctx.collClass(this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); });\r\n\r\n c._ondirectionchange = function (direction) {\r\n compare = (direction === \"next\" ? ascending : descending);\r\n set.sort(compare);\r\n };\r\n var i = 0;\r\n c._addAlgorithm(function (cursor, advance, resolve) {\r\n var key = cursor.key;\r\n while (compare(key, set[i]) > 0) {\r\n // The cursor has passed beyond this key. Check next.\r\n ++i;\r\n if (i === set.length) {\r\n // There is no next. Stop searching.\r\n advance(resolve);\r\n return false;\r\n }\r\n }\r\n if (compare(key, set[i]) === 0) {\r\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\r\n return true;\r\n } else {\r\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\r\n advance(function () { cursor.continue(set[i]); });\r\n return false;\r\n }\r\n });\r\n return c;\r\n },\r\n\r\n notEqual: function(value) {\r\n return this.inAnyRange([[-Infinity, value],[value, maxKey]], {includeLowers: false, includeUppers: false});\r\n },\r\n\r\n noneOf: function() {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection.\r\n try { set.sort(ascending); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT);}\r\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[-Infinity,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\r\n var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]]; }, null);\r\n ranges.push([set[set.length - 1], maxKey]);\r\n return this.inAnyRange(ranges, {includeLowers: false, includeUppers: false});\r\n },\r\n\r\n /** Filter out values withing given set of ranges.\r\n * Example, give children and elders a rebate of 50%:\r\n *\r\n * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});\r\n *\r\n * @param {(string|number|Date|Array)[][]} ranges\r\n * @param {{includeLowers: boolean, includeUppers: boolean}} options\r\n */\r\n inAnyRange: function (ranges, options) {\r\n var ctx = this._ctx;\r\n if (ranges.length === 0) return emptyCollection(this);\r\n if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;})) {\r\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\r\n }\r\n var includeLowers = !options || options.includeLowers !== false; // Default to true\r\n var includeUppers = options && options.includeUppers === true; // Default to false\r\n\r\n function addRange (ranges, newRange) {\r\n for (var i=0,l=ranges.length;i 0) {\r\n range[0] = min(range[0], newRange[0]);\r\n range[1] = max(range[1], newRange[1]);\r\n break;\r\n }\r\n }\r\n if (i === l)\r\n ranges.push(newRange);\r\n return ranges;\r\n }\r\n\r\n var sortDirection = ascending;\r\n function rangeSorter(a,b) { return sortDirection(a[0], b[0]);}\r\n\r\n // Join overlapping ranges\r\n var set;\r\n try {\r\n set = ranges.reduce(addRange, []);\r\n set.sort(rangeSorter);\r\n } catch(ex) {\r\n return fail(this, INVALID_KEY_ARGUMENT);\r\n }\r\n\r\n var i = 0;\r\n var keyIsBeyondCurrentEntry = includeUppers ?\r\n function(key) { return ascending(key, set[i][1]) > 0; } :\r\n function(key) { return ascending(key, set[i][1]) >= 0; };\r\n\r\n var keyIsBeforeCurrentEntry = includeLowers ?\r\n function(key) { return descending(key, set[i][0]) > 0; } :\r\n function(key) { return descending(key, set[i][0]) >= 0; };\r\n\r\n function keyWithinCurrentRange (key) {\r\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\r\n }\r\n\r\n var checkKey = keyIsBeyondCurrentEntry;\r\n\r\n var c = new ctx.collClass(this, function () {\r\n return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);\r\n });\r\n\r\n c._ondirectionchange = function (direction) {\r\n if (direction === \"next\") {\r\n checkKey = keyIsBeyondCurrentEntry;\r\n sortDirection = ascending;\r\n } else {\r\n checkKey = keyIsBeforeCurrentEntry;\r\n sortDirection = descending;\r\n }\r\n set.sort(rangeSorter);\r\n };\r\n\r\n c._addAlgorithm(function (cursor, advance, resolve) {\r\n var key = cursor.key;\r\n while (checkKey(key)) {\r\n // The cursor has passed beyond this key. Check next.\r\n ++i;\r\n if (i === set.length) {\r\n // There is no next. Stop searching.\r\n advance(resolve);\r\n return false;\r\n }\r\n }\r\n if (keyWithinCurrentRange(key)) {\r\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\r\n return true;\r\n } else if (cmp(key,set[i][1]) === 0 || cmp(key,set[i][0]) === 0) {\r\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\r\n // Continue to next key but don't include this one.\r\n return false;\r\n } else {\r\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\r\n advance(function() {\r\n if (sortDirection === ascending) cursor.continue(set[i][0]);\r\n else cursor.continue(set[i][1]);\r\n });\r\n return false;\r\n }\r\n });\r\n return c;\r\n },\r\n startsWithAnyOf: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n\r\n if (!set.every(function (s) { return typeof s === 'string'; })) {\r\n return fail(this, \"startsWithAnyOf() only works with strings\");\r\n }\r\n if (set.length === 0) return emptyCollection(this);\r\n\r\n return this.inAnyRange(set.map(function(str) {\r\n return [str, str + maxString];\r\n }));\r\n }\r\n };\r\n });\r\n\r\n\r\n\r\n\r\n //\r\n //\r\n //\r\n // Collection Class\r\n //\r\n //\r\n //\r\n function Collection(whereClause, keyRangeGenerator) {\r\n /// \r\n ///\r\n /// \r\n /// Where clause instance\r\n /// \r\n var keyRange = null, error = null;\r\n if (keyRangeGenerator) try {\r\n keyRange = keyRangeGenerator();\r\n } catch (ex) {\r\n error = ex;\r\n }\r\n\r\n var whereCtx = whereClause._ctx,\r\n table = whereCtx.table;\r\n this._ctx = {\r\n table: table,\r\n index: whereCtx.index,\r\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\r\n range: keyRange,\r\n keysOnly: false,\r\n dir: \"next\",\r\n unique: \"\",\r\n algorithm: null,\r\n filter: null,\r\n replayFilter: null,\r\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\r\n isMatch: null,\r\n offset: 0,\r\n limit: Infinity,\r\n error: error, // If set, any promise must be rejected with this error\r\n or: whereCtx.or,\r\n valueMapper: table.hook.reading.fire\r\n };\r\n }\r\n \r\n function isPlainKeyRange (ctx, ignoreLimitFilter) {\r\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\r\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\r\n } \r\n\r\n props(Collection.prototype, function () {\r\n\r\n //\r\n // Collection Private Functions\r\n //\r\n\r\n function addFilter(ctx, fn) {\r\n ctx.filter = combine(ctx.filter, fn);\r\n }\r\n\r\n function addReplayFilter (ctx, factory, isLimitFilter) {\r\n var curr = ctx.replayFilter;\r\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\r\n ctx.justLimit = isLimitFilter && !curr;\r\n }\r\n\r\n function addMatchFilter(ctx, fn) {\r\n ctx.isMatch = combine(ctx.isMatch, fn);\r\n }\r\n\r\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string\r\n * }\r\n * @param store IDBObjectStore\r\n **/\r\n function getIndexOrStore(ctx, store) {\r\n if (ctx.isPrimKey) return store;\r\n var indexSpec = ctx.table.schema.idxByName[ctx.index];\r\n if (!indexSpec) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + store.name + \" is not indexed\");\r\n return store.index(indexSpec.name);\r\n }\r\n\r\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string,\r\n * keysOnly: boolean,\r\n * range?: IDBKeyRange,\r\n * dir: \"next\" | \"prev\"\r\n * }\r\n */\r\n function openCursor(ctx, store) {\r\n var idxOrStore = getIndexOrStore(ctx, store);\r\n return ctx.keysOnly && 'openKeyCursor' in idxOrStore ?\r\n idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) :\r\n idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);\r\n }\r\n\r\n function iter(ctx, fn, resolve, reject, idbstore) {\r\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\r\n if (!ctx.or) {\r\n iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);\r\n } else (()=>{\r\n var set = {};\r\n var resolved = 0;\r\n\r\n function resolveboth() {\r\n if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.\r\n }\r\n\r\n function union(item, cursor, advance) {\r\n if (!filter || filter(cursor, advance, resolveboth, reject)) {\r\n var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\r\n if (!hasOwn(set, key)) {\r\n set[key] = true;\r\n fn(item, cursor, advance);\r\n }\r\n }\r\n }\r\n\r\n ctx.or._iterate(union, resolveboth, reject, idbstore);\r\n iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);\r\n })();\r\n }\r\n function getInstanceTemplate(ctx) {\r\n return ctx.table.schema.instanceTemplate;\r\n }\r\n \r\n return {\r\n\r\n //\r\n // Collection Protected Functions\r\n //\r\n\r\n _read: function (fn, cb) {\r\n var ctx = this._ctx;\r\n if (ctx.error)\r\n return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });\r\n else\r\n return ctx.table._idbstore(READONLY, fn).then(cb);\r\n },\r\n _write: function (fn) {\r\n var ctx = this._ctx;\r\n if (ctx.error)\r\n return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });\r\n else\r\n return ctx.table._idbstore(READWRITE, fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\r\n },\r\n _addAlgorithm: function (fn) {\r\n var ctx = this._ctx;\r\n ctx.algorithm = combine(ctx.algorithm, fn);\r\n },\r\n\r\n _iterate: function (fn, resolve, reject, idbstore) {\r\n return iter(this._ctx, fn, resolve, reject, idbstore);\r\n },\r\n\r\n clone: function (props) {\r\n var rv = Object.create(this.constructor.prototype),\r\n ctx = Object.create(this._ctx);\r\n if (props) extend(ctx, props);\r\n rv._ctx = ctx;\r\n return rv;\r\n },\r\n\r\n raw: function () {\r\n this._ctx.valueMapper = null;\r\n return this;\r\n },\r\n\r\n //\r\n // Collection Public methods\r\n //\r\n\r\n each: function (fn) {\r\n var ctx = this._ctx;\r\n\r\n if (fake) {\r\n var item = getInstanceTemplate(ctx),\r\n primKeyPath = ctx.table.schema.primKey.keyPath,\r\n key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath),\r\n primaryKey = getByKeyPath(item, primKeyPath);\r\n fn(item, {key: key, primaryKey: primaryKey});\r\n }\r\n \r\n return this._read(function (resolve, reject, idbstore) {\r\n iter(ctx, fn, resolve, reject, idbstore);\r\n });\r\n },\r\n\r\n count: function (cb) {\r\n if (fake) return Promise.resolve(0).then(cb);\r\n var ctx = this._ctx;\r\n\r\n if (isPlainKeyRange(ctx, true)) {\r\n // This is a plain key range. We can use the count() method if the index.\r\n return this._read(function (resolve, reject, idbstore) {\r\n var idx = getIndexOrStore(ctx, idbstore);\r\n var req = (ctx.range ? idx.count(ctx.range) : idx.count());\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = function (e) {\r\n resolve(Math.min(e.target.result, ctx.limit));\r\n };\r\n }, cb);\r\n } else {\r\n // Algorithms, filters or expressions are applied. Need to count manually.\r\n var count = 0;\r\n return this._read(function (resolve, reject, idbstore) {\r\n iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore);\r\n }, cb);\r\n }\r\n },\r\n\r\n sortBy: function (keyPath, cb) {\r\n /// \r\n var parts = keyPath.split('.').reverse(),\r\n lastPart = parts[0],\r\n lastIndex = parts.length - 1;\r\n function getval(obj, i) {\r\n if (i) return getval(obj[parts[i]], i - 1);\r\n return obj[lastPart];\r\n }\r\n var order = this._ctx.dir === \"next\" ? 1 : -1;\r\n\r\n function sorter(a, b) {\r\n var aVal = getval(a, lastIndex),\r\n bVal = getval(b, lastIndex);\r\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\r\n }\r\n return this.toArray(function (a) {\r\n return a.sort(sorter);\r\n }).then(cb);\r\n },\r\n\r\n toArray: function (cb) {\r\n var ctx = this._ctx;\r\n return this._read(function (resolve, reject, idbstore) {\r\n fake && resolve([getInstanceTemplate(ctx)]);\r\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\r\n // Special optimation if we could use IDBObjectStore.getAll() or\r\n // IDBKeyRange.getAll():\r\n var readingHook = ctx.table.hook.reading.fire;\r\n var idxOrStore = getIndexOrStore(ctx, idbstore);\r\n var req = ctx.limit < Infinity ?\r\n idxOrStore.getAll(ctx.range, ctx.limit) :\r\n idxOrStore.getAll(ctx.range);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = readingHook === mirror ?\r\n eventSuccessHandler(resolve) :\r\n wrap(eventSuccessHandler(res => {\r\n try {resolve (res.map(readingHook));} catch(e) {reject(e);}\r\n }));\r\n } else {\r\n // Getting array through a cursor.\r\n var a = [];\r\n iter(ctx, function (item) { a.push(item); }, function arrayComplete() {\r\n resolve(a);\r\n }, reject, idbstore);\r\n }\r\n }, cb);\r\n },\r\n\r\n offset: function (offset) {\r\n var ctx = this._ctx;\r\n if (offset <= 0) return this;\r\n ctx.offset += offset; // For count()\r\n if (isPlainKeyRange(ctx)) {\r\n addReplayFilter(ctx, ()=> {\r\n var offsetLeft = offset;\r\n return (cursor, advance) => {\r\n if (offsetLeft === 0) return true;\r\n if (offsetLeft === 1) { --offsetLeft; return false; }\r\n advance(()=> {\r\n cursor.advance(offsetLeft);\r\n offsetLeft = 0;\r\n });\r\n return false;\r\n };\r\n });\r\n } else {\r\n addReplayFilter(ctx, ()=> {\r\n var offsetLeft = offset;\r\n return () => (--offsetLeft < 0);\r\n });\r\n }\r\n return this;\r\n },\r\n\r\n limit: function (numRows) {\r\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\r\n addReplayFilter(this._ctx, ()=> {\r\n var rowsLeft = numRows;\r\n return function (cursor, advance, resolve) {\r\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\r\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\r\n };\r\n }, true);\r\n return this;\r\n },\r\n\r\n until: function (filterFunction, bIncludeStopEntry) {\r\n var ctx = this._ctx;\r\n fake && filterFunction(getInstanceTemplate(ctx));\r\n addFilter(this._ctx, function (cursor, advance, resolve) {\r\n if (filterFunction(cursor.value)) {\r\n advance(resolve);\r\n return bIncludeStopEntry;\r\n } else {\r\n return true;\r\n }\r\n });\r\n return this;\r\n },\r\n\r\n first: function (cb) {\r\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\r\n },\r\n\r\n last: function (cb) {\r\n return this.reverse().first(cb);\r\n },\r\n\r\n filter: function (filterFunction) {\r\n /// function(val){return true/false}\r\n fake && filterFunction(getInstanceTemplate(this._ctx));\r\n addFilter(this._ctx, function (cursor) {\r\n return filterFunction(cursor.value);\r\n });\r\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\r\n // collection for a match without querying DB. Used by Dexie.Observable.\r\n addMatchFilter(this._ctx, filterFunction); \r\n return this;\r\n },\r\n \r\n and: function (filterFunction) {\r\n return this.filter(filterFunction);\r\n },\r\n\r\n or: function (indexName) {\r\n return new WhereClause(this._ctx.table, indexName, this);\r\n },\r\n\r\n reverse: function () {\r\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\r\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\r\n return this;\r\n },\r\n\r\n desc: function () {\r\n return this.reverse();\r\n },\r\n\r\n eachKey: function (cb) {\r\n var ctx = this._ctx;\r\n ctx.keysOnly = !ctx.isMatch;\r\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\r\n },\r\n\r\n eachUniqueKey: function (cb) {\r\n this._ctx.unique = \"unique\";\r\n return this.eachKey(cb);\r\n },\r\n \r\n eachPrimaryKey: function (cb) {\r\n var ctx = this._ctx;\r\n ctx.keysOnly = !ctx.isMatch;\r\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\r\n },\r\n\r\n keys: function (cb) {\r\n var ctx = this._ctx;\r\n ctx.keysOnly = !ctx.isMatch;\r\n var a = [];\r\n return this.each(function (item, cursor) {\r\n a.push(cursor.key);\r\n }).then(function () {\r\n return a;\r\n }).then(cb);\r\n },\r\n \r\n primaryKeys: function (cb) {\r\n var ctx = this._ctx;\r\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\r\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\r\n // IDBKeyRange.getAllKeys():\r\n return this._read((resolve, reject, idbstore) =>{\r\n var idxOrStore = getIndexOrStore(ctx, idbstore);\r\n var req = ctx.limit < Infinity ?\r\n idxOrStore.getAllKeys(ctx.range, ctx.limit) :\r\n idxOrStore.getAllKeys(ctx.range);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = eventSuccessHandler(resolve);\r\n }).then(cb);\r\n }\r\n ctx.keysOnly = !ctx.isMatch;\r\n var a = [];\r\n return this.each(function (item, cursor) {\r\n a.push(cursor.primaryKey);\r\n }).then(function () {\r\n return a;\r\n }).then(cb);\r\n },\r\n\r\n uniqueKeys: function (cb) {\r\n this._ctx.unique = \"unique\";\r\n return this.keys(cb);\r\n },\r\n\r\n firstKey: function (cb) {\r\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\r\n },\r\n\r\n lastKey: function (cb) {\r\n return this.reverse().firstKey(cb);\r\n },\r\n\r\n distinct: function () {\r\n var ctx = this._ctx,\r\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\r\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\r\n var set = {};\r\n addFilter(this._ctx, function (cursor) {\r\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\r\n var found = hasOwn(set, strKey);\r\n set[strKey] = true;\r\n return !found;\r\n });\r\n return this;\r\n }\r\n };\r\n });\r\n\r\n //\r\n //\r\n // WriteableCollection Class\r\n //\r\n //\r\n function WriteableCollection() {\r\n Collection.apply(this, arguments);\r\n }\r\n\r\n derive(WriteableCollection).from(Collection).extend({\r\n\r\n //\r\n // WriteableCollection Public Methods\r\n //\r\n\r\n modify: function (changes) {\r\n var self = this,\r\n ctx = this._ctx,\r\n hook = ctx.table.hook,\r\n updatingHook = hook.updating.fire,\r\n deletingHook = hook.deleting.fire;\r\n\r\n fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate);\r\n\r\n return this._write(function (resolve, reject, idbstore, trans) {\r\n var modifyer;\r\n if (typeof changes === 'function') {\r\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\r\n if (updatingHook === nop && deletingHook === nop) {\r\n // Noone cares about what is being changed. Just let the modifier function be the given argument as is.\r\n modifyer = changes;\r\n } else {\r\n // People want to know exactly what is being modified or deleted.\r\n // Let modifyer be a proxy function that finds out what changes the caller is actually doing\r\n // and call the hooks accordingly!\r\n modifyer = function (item) {\r\n var origItem = deepClone(item); // Clone the item first so we can compare laters.\r\n if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)\r\n if (!hasOwn(this, \"value\")) {\r\n // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.\r\n deletingHook.call(this, this.primKey, item, trans);\r\n } else {\r\n // No deletion. Check what was changed\r\n var objectDiff = getObjectDiff(origItem, this.value);\r\n var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);\r\n if (additionalChanges) {\r\n // Hook want to apply additional modifications. Make sure to fullfill the will of the hook.\r\n item = this.value;\r\n keys(additionalChanges).forEach(function (keyPath) {\r\n setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\r\n });\r\n }\r\n }\r\n };\r\n }\r\n } else if (updatingHook === nop) {\r\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\r\n var keyPaths = keys(changes);\r\n var numKeys = keyPaths.length;\r\n modifyer = function (item) {\r\n var anythingModified = false;\r\n for (var i = 0; i < numKeys; ++i) {\r\n var keyPath = keyPaths[i], val = changes[keyPath];\r\n if (getByKeyPath(item, keyPath) !== val) {\r\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\r\n anythingModified = true;\r\n }\r\n }\r\n return anythingModified;\r\n };\r\n } else {\r\n // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and\r\n // allow it to add additional modifications to make.\r\n var origChanges = changes;\r\n changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.\r\n modifyer = function (item) {\r\n var anythingModified = false;\r\n var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);\r\n if (additionalChanges) extend(changes, additionalChanges);\r\n keys(changes).forEach(function (keyPath) {\r\n var val = changes[keyPath];\r\n if (getByKeyPath(item, keyPath) !== val) {\r\n setByKeyPath(item, keyPath, val);\r\n anythingModified = true;\r\n }\r\n });\r\n if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration\r\n return anythingModified;\r\n };\r\n }\r\n\r\n var count = 0;\r\n var successCount = 0;\r\n var iterationComplete = false;\r\n var failures = [];\r\n var failKeys = [];\r\n var currentKey = null;\r\n\r\n function modifyItem(item, cursor) {\r\n currentKey = cursor.primaryKey;\r\n var thisContext = {\r\n primKey: cursor.primaryKey,\r\n value: item,\r\n onsuccess: null,\r\n onerror: null\r\n };\r\n\r\n function onerror(e) {\r\n failures.push(e);\r\n failKeys.push(thisContext.primKey);\r\n checkFinished();\r\n return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction\r\n }\r\n\r\n if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update!\r\n var bDelete = !hasOwn(thisContext, \"value\");\r\n ++count;\r\n tryCatch(function () {\r\n var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value));\r\n req._hookCtx = thisContext;\r\n req.onerror = hookedEventRejectHandler(onerror);\r\n req.onsuccess = hookedEventSuccessHandler(function () {\r\n ++successCount;\r\n checkFinished();\r\n });\r\n }, onerror);\r\n } else if (thisContext.onsuccess) {\r\n // Hook will expect either onerror or onsuccess to always be called!\r\n thisContext.onsuccess(thisContext.value);\r\n }\r\n }\r\n\r\n function doReject(e) {\r\n if (e) {\r\n failures.push(e);\r\n failKeys.push(currentKey);\r\n }\r\n return reject(new ModifyError(\"Error modifying one or more objects\", failures, successCount, failKeys));\r\n }\r\n\r\n function checkFinished() {\r\n if (iterationComplete && successCount + failures.length === count) {\r\n if (failures.length > 0)\r\n doReject();\r\n else\r\n resolve(successCount);\r\n }\r\n }\r\n self.clone().raw()._iterate(modifyItem, function () {\r\n iterationComplete = true;\r\n checkFinished();\r\n }, doReject, idbstore);\r\n });\r\n },\r\n\r\n 'delete': function () {\r\n var ctx = this._ctx,\r\n range = ctx.range,\r\n deletingHook = ctx.table.hook.deleting.fire,\r\n hasDeleteHook = deletingHook !== nop;\r\n if (!hasDeleteHook &&\r\n isPlainKeyRange(ctx) &&\r\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) // if no range, we'll use clear().\r\n {\r\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\r\n // For chromium, this is the way most optimized version.\r\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\r\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\r\n return this._write((resolve, reject, idbstore) => {\r\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\r\n var onerror = eventRejectHandler(reject),\r\n countReq = (range ? idbstore.count(range) : idbstore.count());\r\n countReq.onerror = onerror;\r\n countReq.onsuccess = () => {\r\n var count = countReq.result;\r\n tryCatch(()=> {\r\n var delReq = (range ? idbstore.delete(range) : idbstore.clear());\r\n delReq.onerror = onerror;\r\n delReq.onsuccess = () => resolve(count);\r\n }, err => reject(err));\r\n };\r\n });\r\n }\r\n\r\n // Default version to use when collection is not a vanilla IDBKeyRange on the primary key.\r\n // Divide into chunks to not starve RAM.\r\n // If has delete hook, we will have to collect not just keys but also objects, so it will use\r\n // more memory and need lower chunk size.\r\n const CHUNKSIZE = hasDeleteHook ? 2000 : 10000;\r\n\r\n return this._write((resolve, reject, idbstore, trans) => {\r\n var totalCount = 0;\r\n // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.\r\n var collection = this\r\n .clone({\r\n keysOnly: !ctx.isMatch && !hasDeleteHook}) // load just keys (unless filter() or and() or deleteHook has subscribers)\r\n .distinct() // In case multiEntry is used, never delete same key twice because resulting count\r\n // would become larger than actual delete count.\r\n .limit(CHUNKSIZE)\r\n .raw(); // Don't filter through reading-hooks (like mapped classes etc)\r\n\r\n var keysOrTuples = [];\r\n\r\n // We're gonna do things on as many chunks that are needed.\r\n // Use recursion of nextChunk function:\r\n const nextChunk = () => collection.each(hasDeleteHook ? (val, cursor) => {\r\n // Somebody subscribes to hook('deleting'). Collect all primary keys and their values,\r\n // so that the hook can be called with its values in bulkDelete().\r\n keysOrTuples.push([cursor.primaryKey, cursor.value]);\r\n } : (val, cursor) => {\r\n // No one subscribes to hook('deleting'). Collect only primary keys:\r\n keysOrTuples.push(cursor.primaryKey);\r\n }).then(() => {\r\n // Chromium deletes faster when doing it in sort order.\r\n hasDeleteHook ?\r\n keysOrTuples.sort((a, b)=>ascending(a[0], b[0])) :\r\n keysOrTuples.sort(ascending);\r\n return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);\r\n\r\n }).then(()=> {\r\n var count = keysOrTuples.length;\r\n totalCount += count;\r\n keysOrTuples = [];\r\n return count < CHUNKSIZE ? totalCount : nextChunk();\r\n });\r\n\r\n resolve (nextChunk());\r\n });\r\n }\r\n });\r\n\r\n\r\n //\r\n //\r\n //\r\n // ------------------------- Help functions ---------------------------\r\n //\r\n //\r\n //\r\n\r\n function lowerVersionFirst(a, b) {\r\n return a._cfg.version - b._cfg.version;\r\n }\r\n\r\n function setApiOnPlace(objs, tableNames, mode, dbschema) {\r\n tableNames.forEach(function (tableName) {\r\n var tableInstance = db._tableFactory(mode, dbschema[tableName]);\r\n objs.forEach(function (obj) {\r\n tableName in obj || (obj[tableName] = tableInstance);\r\n });\r\n });\r\n }\r\n\r\n function removeTablesApi(objs) {\r\n objs.forEach(function (obj) {\r\n for (var key in obj) {\r\n if (obj[key] instanceof Table) delete obj[key];\r\n }\r\n });\r\n }\r\n\r\n function iterate(req, filter, fn, resolve, reject, valueMapper) {\r\n \r\n // Apply valueMapper (hook('reading') or mappped class)\r\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\r\n // Wrap fn with PSD and microtick stuff from Promise.\r\n var wrappedFn = wrap(mappedFn, reject);\r\n \r\n if (!req.onerror) req.onerror = eventRejectHandler(reject);\r\n if (filter) {\r\n req.onsuccess = trycatcher(function filter_record() {\r\n var cursor = req.result;\r\n if (cursor) {\r\n var c = function () { cursor.continue(); };\r\n if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject))\r\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\r\n c();\r\n } else {\r\n resolve();\r\n }\r\n }, reject);\r\n } else {\r\n req.onsuccess = trycatcher(function filter_record() {\r\n var cursor = req.result;\r\n if (cursor) {\r\n var c = function () { cursor.continue(); };\r\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\r\n c();\r\n } else {\r\n resolve();\r\n }\r\n }, reject);\r\n }\r\n }\r\n\r\n function parseIndexSyntax(indexes) {\r\n /// \r\n /// \r\n var rv = [];\r\n indexes.split(',').forEach(function (index) {\r\n index = index.trim();\r\n var name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\r\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\r\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\r\n\r\n rv.push(new IndexSpec(\r\n name,\r\n keyPath || null,\r\n /\\&/.test(index),\r\n /\\*/.test(index),\r\n /\\+\\+/.test(index),\r\n isArray(keyPath),\r\n /\\./.test(index)\r\n ));\r\n });\r\n return rv;\r\n }\r\n\r\n function cmp(key1, key2) {\r\n return indexedDB.cmp(key1, key2);\r\n }\r\n\r\n function min(a, b) {\r\n return cmp(a, b) < 0 ? a : b;\r\n }\r\n\r\n function max(a, b) {\r\n return cmp(a, b) > 0 ? a : b;\r\n }\r\n\r\n function ascending(a,b) {\r\n return indexedDB.cmp(a,b);\r\n }\r\n\r\n function descending(a, b) {\r\n return indexedDB.cmp(b,a);\r\n }\r\n\r\n function simpleCompare(a, b) {\r\n return a < b ? -1 : a === b ? 0 : 1;\r\n }\r\n\r\n function simpleCompareReverse(a, b) {\r\n return a > b ? -1 : a === b ? 0 : 1;\r\n }\r\n\r\n function combine(filter1, filter2) {\r\n return filter1 ?\r\n filter2 ?\r\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\r\n filter1 :\r\n filter2;\r\n }\r\n\r\n function readGlobalSchema() {\r\n db.verno = idbdb.version / 10;\r\n db._dbSchema = globalSchema = {};\r\n dbStoreNames = slice(idbdb.objectStoreNames, 0);\r\n if (dbStoreNames.length === 0) return; // Database contains no stores.\r\n var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');\r\n dbStoreNames.forEach(function (storeName) {\r\n var store = trans.objectStore(storeName),\r\n keyPath = store.keyPath,\r\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\r\n var primKey = new IndexSpec(keyPath, keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);\r\n var indexes = [];\r\n for (var j = 0; j < store.indexNames.length; ++j) {\r\n var idbindex = store.index(store.indexNames[j]);\r\n keyPath = idbindex.keyPath;\r\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\r\n var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);\r\n indexes.push(index);\r\n }\r\n globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});\r\n });\r\n setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema);\r\n }\r\n\r\n function adjustToExistingIndexNames(schema, idbtrans) {\r\n /// \r\n /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\r\n /// \r\n /// Map between name and TableSchema\r\n /// \r\n var storeNames = idbtrans.db.objectStoreNames;\r\n for (var i = 0; i < storeNames.length; ++i) {\r\n var storeName = storeNames[i];\r\n var store = idbtrans.objectStore(storeName);\r\n hasGetAll = 'getAll' in store;\r\n for (var j = 0; j < store.indexNames.length; ++j) {\r\n var indexName = store.indexNames[j];\r\n var keyPath = store.index(indexName).keyPath;\r\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\r\n if (schema[storeName]) {\r\n var indexSpec = schema[storeName].idxByName[dexieName];\r\n if (indexSpec) indexSpec.name = indexName;\r\n }\r\n }\r\n }\r\n }\r\n\r\n function fireOnBlocked(ev) {\r\n db.on(\"blocked\").fire(ev);\r\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\r\n connections\r\n .filter(c=>c.name === db.name && c !== db && !c._vcFired)\r\n .map(c => c.on(\"versionchange\").fire(ev));\r\n }\r\n\r\n extend(this, {\r\n Collection: Collection,\r\n Table: Table,\r\n Transaction: Transaction,\r\n Version: Version,\r\n WhereClause: WhereClause,\r\n WriteableCollection: WriteableCollection,\r\n WriteableTable: WriteableTable\r\n });\r\n\r\n init();\r\n\r\n addons.forEach(function (fn) {\r\n fn(db);\r\n });\r\n}\r\n\r\nvar fakeAutoComplete = function () { };// Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\r\nvar fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\r\n\r\nfunction parseType(type) {\r\n if (typeof type === 'function') {\r\n return new type();\r\n } else if (isArray(type)) {\r\n return [parseType(type[0])];\r\n } else if (type && typeof type === 'object') {\r\n var rv = {};\r\n applyStructure(rv, type);\r\n return rv;\r\n } else {\r\n return type;\r\n }\r\n}\r\n\r\nfunction applyStructure(obj, structure) {\r\n keys(structure).forEach(function (member) {\r\n var value = parseType(structure[member]);\r\n obj[member] = value;\r\n });\r\n return obj;\r\n}\r\n\r\nfunction eventSuccessHandler(done) {\r\n return function (ev) {\r\n done(ev.target.result);\r\n }\r\n}\r\n\r\nfunction hookedEventSuccessHandler(resolve) {\r\n // wrap() is needed when calling hooks because the rare scenario of:\r\n // * hook does a db operation that fails immediately (IDB throws exception)\r\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\r\n // wrap() will also execute in a virtual tick.\r\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\r\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\r\n // and the transaction will have committed already.\r\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\r\n // because it is always marked with _lib = true when created using Transaction._promise().\r\n return wrap(function(event) {\r\n var req = event.target,\r\n result = req.result,\r\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\r\n hookSuccessHandler = ctx && ctx.onsuccess;\r\n hookSuccessHandler && hookSuccessHandler(result);\r\n resolve && resolve(result);\r\n }, resolve);\r\n}\r\n\r\nfunction eventRejectHandler(reject) {\r\n return function (event) {\r\n preventDefault(event);\r\n reject (event.target.error);\r\n return false;\r\n };\r\n}\r\n\r\nfunction hookedEventRejectHandler (reject) {\r\n return wrap(function (event) {\r\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\r\n \r\n var req = event.target,\r\n err = req.error,\r\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\r\n hookErrorHandler = ctx && ctx.onerror;\r\n hookErrorHandler && hookErrorHandler(err);\r\n preventDefault(event);\r\n reject (err);\r\n return false;\r\n });\r\n}\r\n\r\nfunction preventDefault(event) {\r\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\r\n event.stopPropagation();\r\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\r\n event.preventDefault();\r\n}\r\n\r\nfunction globalDatabaseList(cb) {\r\n var val,\r\n localStorage = Dexie.dependencies.localStorage;\r\n if (!localStorage) return cb([]); // Envs without localStorage support\r\n try {\r\n val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || \"[]\");\r\n } catch (e) {\r\n val = [];\r\n }\r\n if (cb(val)) {\r\n localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val));\r\n }\r\n}\r\n\r\nfunction awaitIterator (iterator) {\r\n var callNext = result => iterator.next(result),\r\n doThrow = error => iterator.throw(error),\r\n onSuccess = step(callNext),\r\n onError = step(doThrow);\r\n\r\n function step(getNext) {\r\n return val => {\r\n var next = getNext(val),\r\n value = next.value;\r\n\r\n return next.done ? value :\r\n (!value || typeof value.then !== 'function' ?\r\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\r\n value.then(onSuccess, onError));\r\n };\r\n }\r\n\r\n return step(callNext)();\r\n}\r\n\r\n//\r\n// IndexSpec struct\r\n//\r\nfunction IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {\r\n /// \r\n /// \r\n /// \r\n /// \r\n /// \r\n /// \r\n /// \r\n this.name = name;\r\n this.keyPath = keyPath;\r\n this.unique = unique;\r\n this.multi = multi;\r\n this.auto = auto;\r\n this.compound = compound;\r\n this.dotted = dotted;\r\n var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']');\r\n this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + keyPathSrc;\r\n}\r\n\r\n//\r\n// TableSchema struct\r\n//\r\nfunction TableSchema(name, primKey, indexes, instanceTemplate) {\r\n /// \r\n /// \r\n /// \r\n /// \r\n this.name = name;\r\n this.primKey = primKey || new IndexSpec();\r\n this.indexes = indexes || [new IndexSpec()];\r\n this.instanceTemplate = instanceTemplate;\r\n this.mappedClass = null;\r\n this.idxByName = arrayToObject(indexes, index => [index.name, index]);\r\n}\r\n\r\n// Used in when defining dependencies later...\r\n// (If IndexedDBShim is loaded, prefer it before standard indexedDB)\r\nvar idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {};\r\n\r\nfunction safariMultiStoreFix(storeNames) {\r\n return storeNames.length === 1 ? storeNames[0] : storeNames;\r\n}\r\n\r\nfunction getNativeGetDatabaseNamesFn(indexedDB) {\r\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\r\n return fn && fn.bind(indexedDB);\r\n}\r\n\r\n// Export Error classes\r\nprops(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};\r\n\r\n//\r\n// Static methods and properties\r\n// \r\nprops(Dexie, {\r\n \r\n //\r\n // Static delete() method.\r\n //\r\n delete: function (databaseName) {\r\n var db = new Dexie(databaseName),\r\n promise = db.delete();\r\n promise.onblocked = function (fn) {\r\n db.on(\"blocked\", fn);\r\n return this;\r\n };\r\n return promise;\r\n },\r\n \r\n //\r\n // Static exists() method.\r\n //\r\n exists: function(name) {\r\n return new Dexie(name).open().then(db=>{\r\n db.close();\r\n return true;\r\n }).catch(Dexie.NoSuchDatabaseError, () => false);\r\n },\r\n \r\n //\r\n // Static method for retrieving a list of all existing databases at current host.\r\n //\r\n getDatabaseNames: function (cb) {\r\n return new Promise(function (resolve, reject) {\r\n var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB);\r\n if (getDatabaseNames) { // In case getDatabaseNames() becomes standard, let's prepare to support it:\r\n var req = getDatabaseNames();\r\n req.onsuccess = function (event) {\r\n resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array\r\n };\r\n req.onerror = eventRejectHandler(reject);\r\n } else {\r\n globalDatabaseList(function (val) {\r\n resolve(val);\r\n return false;\r\n });\r\n }\r\n }).then(cb);\r\n },\r\n \r\n defineClass: function (structure) {\r\n /// \r\n /// Create a javascript constructor based on given template for which properties to expect in the class.\r\n /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.\r\n /// \r\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\r\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\r\n\r\n // Default constructor able to copy given properties into this object.\r\n function Class(properties) {\r\n /// Properties to initialize object with.\r\n /// \r\n properties ? extend(this, properties) : fake && applyStructure(this, structure);\r\n }\r\n return Class;\r\n },\r\n \r\n applyStructure: applyStructure,\r\n \r\n ignoreTransaction: function (scopeFunc) {\r\n // In case caller is within a transaction but needs to create a separate transaction.\r\n // Example of usage:\r\n //\r\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\r\n // logger function and not need to include the 'logentries' table in all transaction it performs.\r\n // The logging should always be done in a separate transaction and not be dependant on the current\r\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\r\n //\r\n // Dexie.ignoreTransaction(function() {\r\n // db.logentries.add(newLogEntry);\r\n // });\r\n //\r\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\r\n // in current Promise-scope.\r\n //\r\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\r\n // API for this because\r\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\r\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\r\n // 3) setImmediate() is not supported in the ES standard.\r\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\r\n return PSD.trans ?\r\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\r\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\r\n },\r\n \r\n vip: function (fn) {\r\n // To be used by subscribers to the on('ready') event.\r\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\r\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\r\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\r\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\r\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\r\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\r\n // the caller will not resolve until database is opened.\r\n return newScope(function () {\r\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\r\n return fn();\r\n });\r\n },\r\n\r\n async: function (generatorFn) {\r\n return function () {\r\n try {\r\n var rv = awaitIterator(generatorFn.apply(this, arguments));\r\n if (!rv || typeof rv.then !== 'function')\r\n return Promise.resolve(rv);\r\n return rv;\r\n } catch (e) {\r\n return rejection (e);\r\n }\r\n };\r\n },\r\n\r\n spawn: function (generatorFn, args, thiz) {\r\n try {\r\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\r\n if (!rv || typeof rv.then !== 'function')\r\n return Promise.resolve(rv);\r\n return rv;\r\n } catch (e) {\r\n return rejection(e);\r\n }\r\n },\r\n \r\n // Dexie.currentTransaction property\r\n currentTransaction: {\r\n get: () => PSD.trans || null\r\n },\r\n \r\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\r\n Promise: Promise,\r\n \r\n // Dexie.debug proptery:\r\n // Dexie.debug = false\r\n // Dexie.debug = true\r\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\r\n debug: {\r\n get: () => Debug.debug,\r\n set: value => {\r\n Debug.setDebug(value, value === 'dexie' ? ()=>true : dexieStackFrameFilter);\r\n }\r\n },\r\n \r\n // Export our derive/extend/override methodology\r\n derive: derive,\r\n extend: extend,\r\n props: props,\r\n override: override,\r\n // Export our Events() function - can be handy as a toolkit\r\n Events: Events,\r\n events: { get: Debug.deprecated(()=>Events) }, // Backward compatible lowercase version.\r\n // Utilities\r\n getByKeyPath: getByKeyPath,\r\n setByKeyPath: setByKeyPath,\r\n delByKeyPath: delByKeyPath,\r\n shallowClone: shallowClone,\r\n deepClone: deepClone,\r\n getObjectDiff: getObjectDiff,\r\n asap: asap,\r\n maxKey: maxKey,\r\n // Addon registry\r\n addons: [],\r\n // Global DB connection list\r\n connections: connections,\r\n \r\n MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.\r\n errnames: errnames,\r\n \r\n // Export other static classes\r\n IndexSpec: IndexSpec,\r\n TableSchema: TableSchema,\r\n \r\n //\r\n // Dependencies\r\n //\r\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\r\n //\r\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\r\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\r\n //\r\n dependencies: {\r\n // Required:\r\n indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\r\n IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange\r\n },\r\n \r\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\r\n semVer: DEXIE_VERSION,\r\n version: DEXIE_VERSION.split('.')\r\n .map(n => parseInt(n))\r\n .reduce((p,c,i) => p + (c/Math.pow(10,i*2))),\r\n fakeAutoComplete: fakeAutoComplete,\r\n \r\n // https://github.com/dfahlander/Dexie.js/issues/186\r\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\r\n // x.default. Workaround: Set Dexie.default = Dexie.\r\n default: Dexie\r\n});\r\n\r\ntryCatch(()=>{\r\n // Optional dependencies\r\n // localStorage\r\n Dexie.dependencies.localStorage =\r\n ((typeof chrome !== \"undefined\" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage);\r\n});\r\n\r\n// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.\r\nPromise.rejectionMapper = mapError;\r\n\r\n// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015.\r\ndoFakeAutoComplete(function() {\r\n Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete;\r\n Dexie.fake = fake = true;\r\n});\r\n"],"names":["asap","Debug.setDebug","Debug.debug","Debug.getErrorWithStack","Debug.deprecated","keys","props"],"mappings":"AAAC;;;;;;;;;;AAUD,AAAO,IAAI,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;AAC9B,AA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C,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,gBAAgB,EAAE,gBAAgB;;;;;IAKlC,OAAO,EAAE,KAAK;CACjB,CAAC,CAAC;;AAEH,QAAQ,CAAC,IAAI;;;IAGT,KAAK,CAAC,YAAY,CAAC,YAAY;QAC3B,CAAC,CAAC,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,KAAK,IAAI,GAAG,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC,IAAI,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;CAC5H,CAAC,CAAC;;;AAGH,OAAO,CAAC,eAAe,GAAG,QAAQ,CAAC;;;AAGnC,kBAAkB,CAAC,WAAW;IAC1B,KAAK,CAAC,gBAAgB,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;IAC/D,KAAK,CAAC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;CAC5B,CAAC,CAAC,;;"} \ No newline at end of file diff --git a/dist/dexie.js b/dist/dexie.js new file mode 100644 index 000000000..f96d0e16e --- /dev/null +++ b/dist/dexie.js @@ -0,0 +1,4607 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Dexie = factory()); +}(this, (function () { 'use strict'; + +/* +* Dexie.js - a minimalistic wrapper for IndexedDB +* =============================================== +* +* By David Fahlander, david.fahlander@gmail.com +* +* Version 1.5.0, Thu Oct 13 2016 +* www.dexie.com +* Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ +*/ +var keys = Object.keys; +var isArray = Array.isArray; +var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global; + +function extend(obj, extension) { + if (typeof extension !== 'object') return obj; + keys(extension).forEach(function (key) { + obj[key] = extension[key]; + }); + return obj; +} + +var getProto = Object.getPrototypeOf; +var _hasOwn = {}.hasOwnProperty; +function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); +} + +function props(proto, extension) { + if (typeof extension === 'function') extension = extension(getProto(proto)); + keys(extension).forEach(function (key) { + setProp(proto, key, extension[key]); + }); +} + +function setProp(obj, prop, functionOrGetSet, options) { + Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options)); +} + +function derive(Child) { + return { + from: function (Parent) { + Child.prototype = Object.create(Parent.prototype); + setProp(Child.prototype, "constructor", Child); + return { + extend: props.bind(null, Child.prototype) + }; + } + }; +} + +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +function getPropertyDescriptor(obj, prop) { + var pd = getOwnPropertyDescriptor(obj, prop), + proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); +} + +var _slice = [].slice; +function slice(args, start, end) { + return _slice.call(args, start, end); +} + +function override(origFunc, overridedFactory) { + return overridedFactory(origFunc); +} + +function doFakeAutoComplete(fn) { + var to = setTimeout(fn, 1000); + clearTimeout(to); +} + +function assert(b) { + if (!b) throw new Error("Assertion Failed"); +} + +function asap(fn) { + if (_global.setImmediate) setImmediate(fn);else setTimeout(fn, 0); +} + + + +/** Generate an object (hash map) based on given array. + * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to + * instert on the resulting object for each item in the array. If this function returns a falsy value, the + * current item wont affect the resulting object. + */ +function arrayToObject(array, extractor) { + return array.reduce(function (result, item, i) { + var nameAndValue = extractor(item, i); + if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1]; + return result; + }, {}); +} + +function trycatcher(fn, reject) { + return function () { + try { + fn.apply(this, arguments); + } catch (e) { + reject(e); + } + }; +} + +function tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } catch (ex) { + onerror && onerror(ex); + } +} + +function getByKeyPath(obj, keyPath) { + // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path + if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose. + if (!keyPath) return obj; + if (typeof keyPath !== 'string') { + var rv = []; + for (var i = 0, l = keyPath.length; i < l; ++i) { + var val = getByKeyPath(obj, keyPath[i]); + rv.push(val); + } + return rv; + } + var period = keyPath.indexOf('.'); + if (period !== -1) { + var innerObj = obj[keyPath.substr(0, period)]; + return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); + } + return undefined; +} + +function setByKeyPath(obj, keyPath, value) { + if (!obj || keyPath === undefined) return; + if ('isFrozen' in Object && Object.isFrozen(obj)) return; + if (typeof keyPath !== 'string' && 'length' in keyPath) { + assert(typeof value !== 'string' && 'length' in value); + for (var i = 0, l = keyPath.length; i < l; ++i) { + setByKeyPath(obj, keyPath[i], value[i]); + } + } else { + var period = keyPath.indexOf('.'); + if (period !== -1) { + var currentKeyPath = keyPath.substr(0, period); + var remainingKeyPath = keyPath.substr(period + 1); + if (remainingKeyPath === "") { + if (value === undefined) delete obj[currentKeyPath];else obj[currentKeyPath] = value; + } else { + var innerObj = obj[currentKeyPath]; + if (!innerObj) innerObj = obj[currentKeyPath] = {}; + setByKeyPath(innerObj, remainingKeyPath, value); + } + } else { + if (value === undefined) delete obj[keyPath];else obj[keyPath] = value; + } + } +} + +function delByKeyPath(obj, keyPath) { + if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);else if ('length' in keyPath) [].map.call(keyPath, function (kp) { + setByKeyPath(obj, kp, undefined); + }); +} + +function shallowClone(obj) { + var rv = {}; + for (var m in obj) { + if (hasOwn(obj, m)) rv[m] = obj[m]; + } + return rv; +} + +function deepClone(any) { + if (!any || typeof any !== 'object') return any; + var rv; + if (isArray(any)) { + rv = []; + for (var i = 0, l = any.length; i < l; ++i) { + rv.push(deepClone(any[i])); + } + } else if (any instanceof Date) { + rv = new Date(); + rv.setTime(any.getTime()); + } else { + rv = any.constructor ? Object.create(any.constructor.prototype) : {}; + for (var prop in any) { + if (hasOwn(any, prop)) { + rv[prop] = deepClone(any[prop]); + } + } + } + return rv; +} + +function getObjectDiff(a, b, rv, prfx) { + // Compares objects a and b and produces a diff object. + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(function (prop) { + if (!hasOwn(b, prop)) rv[prfx + prop] = undefined; // Property removed + else { + var ap = a[prop], + bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && ap && bp && ap.constructor === bp.constructor) + // Same type of object but its properties may have changed + getObjectDiff(ap, bp, rv, prfx + prop + ".");else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed + } + }); + keys(b).forEach(function (prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; // Property added + } + }); + return rv; +} + +// If first argument is iterable or array-like, return it as an array +var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; +var getIteratorOf = iteratorSymbol ? function (x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); +} : function () { + return null; +}; + +var NO_CHAR_ARRAY = {}; +// Takes one or several arguments and returns an array based on the following criteras: +// * If several arguments provided, return arguments converted to an array in a way that +// still allows javascript engine to optimize the code. +// * If single argument is an array, return a clone of it. +// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special +// case to the two bullets below. +// * If single argument is an iterable, convert it to an array and return the resulting array. +// * If single argument is array-like (has length of type number), convert it to an array. +function getArrayOf(arrayLike) { + var i, a, x, it; + if (arguments.length === 1) { + if (isArray(arrayLike)) return arrayLike.slice(); + if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike]; + if (it = getIteratorOf(arrayLike)) { + a = []; + while (x = it.next(), !x.done) { + a.push(x.value); + }return a; + } + if (arrayLike == null) return [arrayLike]; + i = arrayLike.length; + if (typeof i === 'number') { + a = new Array(i); + while (i--) { + a[i] = arrayLike[i]; + }return a; + } + return [arrayLike]; + } + i = arguments.length; + a = new Array(i); + while (i--) { + a[i] = arguments[i]; + }return a; +} + +var concat = [].concat; +function flatten(a) { + return concat.apply([], a); +} + +function nop() {} +function mirror(val) { + return val; +} +function pureFunctionChain(f1, f2) { + // Enables chained events that takes ONE argument and returns it to the next function in chain. + // This pattern is used in the hook("reading") event. + if (f1 == null || f1 === mirror) return f2; + return function (val) { + return f2(f1(val)); + }; +} + +function callBoth(on1, on2) { + return function () { + on1.apply(this, arguments); + on2.apply(this, arguments); + }; +} + +function hookCreatingChain(f1, f2) { + // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance. + // This pattern is used in the hook("creating") event. + if (f1 === nop) return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) arguments[0] = res; + var onsuccess = this.onsuccess, + // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res2 !== undefined ? res2 : res; + }; +} + +function hookDeletingChain(f1, f2) { + if (f1 === nop) return f2; + return function () { + f1.apply(this, arguments); + var onsuccess = this.onsuccess, + // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = this.onerror = null; + f2.apply(this, arguments); + if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + }; +} + +function hookUpdatingChain(f1, f2) { + if (f1 === nop) return f2; + return function (modifications) { + var res = f1.apply(this, arguments); + extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain. + var onsuccess = this.onsuccess, + // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res === undefined ? res2 === undefined ? undefined : res2 : extend(res, res2); + }; +} + +function reverseStoppableEventChain(f1, f2) { + if (f1 === nop) return f2; + return function () { + if (f2.apply(this, arguments) === false) return false; + return f1.apply(this, arguments); + }; +} + + + +function promisableChain(f1, f2) { + if (f1 === nop) return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, + i = arguments.length, + args = new Array(i); + while (i--) { + args[i] = arguments[i]; + }return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} + +// By default, debug will be true only if platform is a web platform and its page is served from localhost. +// When debug = true, error's stacks will contain asyncronic long stacks. +var debug = typeof location !== 'undefined' && +// By default, use debug mode if served from localhost. +/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); + +function setDebug(value, filter) { + debug = value; + libraryFilter = filter; +} + +var libraryFilter = function () { + return true; +}; + +var NEEDS_THROW_FOR_STACK = !new Error("").stack; + +function getErrorWithStack() { + "use strict"; + + if (NEEDS_THROW_FOR_STACK) try { + // Doing something naughty in strict mode here to trigger a specific error + // that can be explicitely ignored in debugger's exception settings. + // If we'd just throw new Error() here, IE's debugger's exception settings + // will just consider it as "exception thrown by javascript code" which is + // something you wouldn't want it to ignore. + getErrorWithStack.arguments; + throw new Error(); // Fallback if above line don't throw. + } catch (e) { + return e; + } + return new Error(); +} + +function prettyStack(exception, numIgnoredFrames) { + var stack = exception.stack; + if (!stack) return ""; + numIgnoredFrames = numIgnoredFrames || 0; + if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length; + return stack.split('\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) { + return "\n" + frame; + }).join(''); +} + +function deprecated(what, fn) { + return function () { + console.warn(what + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + prettyStack(getErrorWithStack(), 1)); + return fn.apply(this, arguments); + }; +} + +var dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise']; + +var idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone']; + +var errorList = dexieErrorNames.concat(idbDomErrorNames); + +var defaultTexts = { + VersionChanged: "Database version changed by other database connection", + DatabaseClosed: "Database has been closed", + Abort: "Transaction aborted", + TransactionInactive: "Transaction has already completed or failed" +}; + +// +// DexieError - base class of all out exceptions. +// +function DexieError(name, msg) { + // Reason we don't use ES6 classes is because: + // 1. It bloats transpiled code and increases size of minified code. + // 2. It doesn't give us much in this case. + // 3. It would require sub classes to call super(), which + // is not needed when deriving from Error. + this._e = getErrorWithStack(); + this.name = name; + this.message = msg; +} + +derive(DexieError).from(Error).extend({ + stack: { + get: function () { + return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); + } + }, + toString: function () { + return this.name + ": " + this.message; + } +}); + +function getMultiErrorMessage(msg, failures) { + return msg + ". Errors: " + failures.map(function (f) { + return f.toString(); + }).filter(function (v, i, s) { + return s.indexOf(v) === i; + }) // Only unique error strings + .join('\n'); +} + +// +// ModifyError - thrown in WriteableCollection.modify() +// Specific constructor because it contains members failures and failedKeys. +// +function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; +} +derive(ModifyError).from(DexieError); + +function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = failures; + this.message = getMultiErrorMessage(msg, failures); +} +derive(BulkError).from(DexieError); + +// +// +// Dynamically generate error names and exception classes based +// on the names in errorList. +// +// + +// Map of {ErrorName -> ErrorName + "Error"} +var errnames = errorList.reduce(function (obj, name) { + return obj[name] = name + "Error", obj; +}, {}); + +// Need an alias for DexieError because we're gonna create subclasses with the same name. +var BaseException = DexieError; +// Map of {ErrorName -> exception constructor} +var exceptions = errorList.reduce(function (obj, name) { + // Let the name be "DexieError" because this name may + // be shown in call stack and when debugging. DexieError is + // the most true name because it derives from DexieError, + // and we cannot change Function.name programatically without + // dynamically create a Function object, which would be considered + // 'eval-evil'. + var fullName = name + "Error"; + function DexieError(msgOrInner, inner) { + this._e = getErrorWithStack(); + this.name = fullName; + if (!msgOrInner) { + this.message = defaultTexts[name] || fullName; + this.inner = null; + } else if (typeof msgOrInner === 'string') { + this.message = msgOrInner; + this.inner = inner || null; + } else if (typeof msgOrInner === 'object') { + this.message = msgOrInner.name + ' ' + msgOrInner.message; + this.inner = msgOrInner; + } + } + derive(DexieError).from(BaseException); + obj[name] = DexieError; + return obj; +}, {}); + +// Use ECMASCRIPT standard exceptions where applicable: +exceptions.Syntax = SyntaxError; +exceptions.Type = TypeError; +exceptions.Range = RangeError; + +var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { + obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); + +function mapError(domError, message) { + if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError; + var rv = new exceptionMap[domError.name](message || domError.message, domError); + if ("stack" in domError) { + // Derive stack from inner exception if it has a stack + setProp(rv, "stack", { get: function () { + return this.inner.stack; + } }); + } + return rv; +} + +var fullNameExceptions = errorList.reduce(function (obj, name) { + if (["Syntax", "Type", "Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); + +fullNameExceptions.ModifyError = ModifyError; +fullNameExceptions.DexieError = DexieError; +fullNameExceptions.BulkError = BulkError; + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + // Subscribe. If additional arguments than just the subscriber was provided, forward them as well. + var i = arguments.length, + args = new Array(i - 1); + while (--i) { + args[i - 1] = arguments[i]; + }evs[eventName].subscribe.apply(null, args); + return ctx; + } else if (typeof eventName === 'string') { + // Return interface allowing to fire or unsubscribe from event + return evs[eventName]; + } + }; + rv.addEventType = add; + + for (var i = 1, l = arguments.length; i < l; ++i) { + add(arguments[i]); + } + + return rv; + + function add(eventName, chainFunction, defaultFunction) { + if (typeof eventName === 'object') return addConfiguredEvents(eventName); + if (!chainFunction) chainFunction = reverseStoppableEventChain; + if (!defaultFunction) defaultFunction = nop; + + var context = { + subscribers: [], + fire: defaultFunction, + subscribe: function (cb) { + if (context.subscribers.indexOf(cb) === -1) { + context.subscribers.push(cb); + context.fire = chainFunction(context.fire, cb); + } + }, + unsubscribe: function (cb) { + context.subscribers = context.subscribers.filter(function (fn) { + return fn !== cb; + }); + context.fire = context.subscribers.reduce(chainFunction, defaultFunction); + } + }; + evs[eventName] = rv[eventName] = context; + return context; + } + + function addConfiguredEvents(cfg) { + // events(this, {reading: [functionChain, nop]}); + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } else if (args === 'asap') { + // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack + // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten. + var context = add(eventName, mirror, function fire() { + // Optimazation-safe cloning of arguments into args. + var i = arguments.length, + args = new Array(i); + while (i--) { + args[i] = arguments[i]; + } // All each subscriber: + context.subscribers.forEach(function (fn) { + asap(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } else throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +// +// Promise Class for Dexie library +// +// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by +// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. +// +// Modifications needed to be done to support indexedDB because it wont accept setTimeout() +// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) . +// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45 +// +// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since +// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise. +// +// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another +// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use +// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick +// engine that is used instead of setImmediate() or setTimeout(). +// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. +// Also with inspiration from bluebird, asyncronic stacks in debug mode. +// +// Specific non-standard features of this Promise class: +// * Async static context support (Promise.PSD) +// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame +// and below + all promises that those promises creates or awaits. +// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). +// +// David Fahlander, https://github.com/dfahlander +// + +// Just a pointer that only this module knows about. +// Used in Promise constructor to emulate a private constructor. +var INTERNAL = {}; + +// Async stacks (long stacks) must not grow infinitely. +var LONG_STACKS_CLIP_LIMIT = 100; +var MAX_LONG_STACKS = 20; +var stack_being_generated = false; + +/* The default "nextTick" function used only for the very first promise in a promise chain. + As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks + emulated in this module. For indexedDB compatibility, this means that every method needs to + execute at least one promise before doing an indexedDB operation. Dexie will always call + db.ready().then() for every operation to make sure the indexedDB event is started in an + emulated micro tick. +*/ +var schedulePhysicalTick = _global.setImmediate ? +// setImmediate supported. Those modern platforms also supports Function.bind(). +setImmediate.bind(null, physicalTick) : _global.MutationObserver ? +// MutationObserver supported +function () { + var hiddenDiv = document.createElement("div"); + new MutationObserver(function () { + physicalTick(); + hiddenDiv = null; + }).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); +} : +// No support for setImmediate or MutationObserver. No worry, setTimeout is only called +// once time. Every tick that follows will be our emulated micro tick. +// Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug +function () { + setTimeout(physicalTick, 0); +}; + +// Confifurable through Promise.scheduler. +// Don't export because it would be unsafe to let unknown +// code call it unless they do try..catch within their callback. +// This function can be retrieved through getter of Promise.scheduler though, +// but users must not do Promise.scheduler (myFuncThatThrows exception)! +var asap$1 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; + +var isOutsideMicroTick = true; +var needsNewPhysicalTick = true; +var unhandledErrors = []; +var rejectingErrors = []; +var currentFulfiller = null; +var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions + +var globalPSD = { + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + //env: null, // Will be set whenever leaving a scope using wrappers.snapshot() + finalize: function () { + this.unhandleds.forEach(function (uh) { + try { + globalError(uh[0], uh[1]); + } catch (e) {} + }); + } +}; + +var PSD = globalPSD; + +var microtickQueue = []; // Callbacks to call in this or next physical tick. +var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. +var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. + +// Wrappers are not being used yet. Their framework is functioning and can be used +// to replace environment during a PSD scope (a.k.a. 'zone'). +/* **KEEP** export var wrappers = (() => { + var wrappers = []; + + return { + snapshot: () => { + var i = wrappers.length, + result = new Array(i); + while (i--) result[i] = wrappers[i].snapshot(); + return result; + }, + restore: values => { + var i = wrappers.length; + while (i--) wrappers[i].restore(values[i]); + }, + wrap: () => wrappers.map(w => w.wrap()), + add: wrapper => { + wrappers.push(wrapper); + } + }; +})(); +*/ + +function Promise(fn) { + if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. + + // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() + // execute the microtask engine implicitely within the call to resolve() or reject(). + // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack + // only contains library code when calling resolve() or reject(). + // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from + // global scope (event handler, timer etc)! + this._lib = false; + // Current async scope + var psd = this._PSD = PSD; + + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; // Number of previous promises (for long stacks) + linkToPreviousPromise(this, currentFulfiller); + } + + if (typeof fn !== 'function') { + if (fn !== INTERNAL) throw new TypeError('Not a function'); + // Private constructor (INTERNAL, state, value). + // Used internally by Promise.resolve() and Promise.reject(). + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). + return; + } + + this._state = null; // null (=pending), false (=rejected) or true (=resolved) + this._value = null; // error or result + ++psd.ref; // Refcounting current scope + executePromiseTask(this, fn); +} + +props(Promise.prototype, { + + then: function (onFulfilled, onRejected) { + var _this = this; + + var rv = new Promise(function (resolve, reject) { + propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject)); + }); + debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this); + return rv; + }, + + _then: function (onFulfilled, onRejected) { + // A little tinier version of then() that don't have to create a resulting promise. + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected)); + }, + + catch: function (onRejected) { + if (arguments.length === 1) return this.then(null, onRejected); + // First argument is the Error type to catch + var type = arguments[0], + handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + return ( + // Catching errors by its constructor type (similar to java / c++ / c#) + // Sample: promise.catch(TypeError, function (e) { ... }); + err instanceof type ? handler(err) : PromiseReject(err) + ); + }) : this.then(null, function (err) { + return ( + // Catching errors by the error.name property. Makes sense for indexedDB where error type + // is always DOMError but where e.name tells the actual error type. + // Sample: promise.catch('ConstraintError', function (e) { ... }); + err && err.name === type ? handler(err) : PromiseReject(err) + ); + }); + }, + + finally: function (onFinally) { + return this.then(function (value) { + onFinally(); + return value; + }, function (err) { + onFinally(); + return PromiseReject(err); + }); + }, + + // Deprecate in next major. Needed only for db.on.error. + uncaught: function (uncaughtHandler) { + var _this2 = this; + + // Be backward compatible and use "onuncatched" as the event name on this. + // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops. + this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler); + // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not + // a previous promise. Reason: the prevous promise may lack onuncatched handler. + if (this._state === false && unhandledErrors.indexOf(this) === -1) { + // Replace unhandled error's destinaion promise with this one! + unhandledErrors.some(function (p, i, l) { + return p._value === _this2._value && (l[i] = _this2); + }); + // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could + // take away this piece of code as well as the onuncatched and uncaught() method. + } + return this; + }, + + stack: { + get: function () { + if (this._stack) return this._stack; + try { + stack_being_generated = true; + var stacks = getStack(this, [], MAX_LONG_STACKS); + var stack = stacks.join("\nFrom previous: "); + if (this._state !== null) this._stack = stack; // Stack may be updated on reject. + return stack; + } finally { + stack_being_generated = false; + } + } + } +}); + +function Listener(onFulfilled, onRejected, resolve, reject) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = PSD; +} + +// Promise Static Properties +props(Promise, { + all: function () { + var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like. + return new Promise(function (resolve, reject) { + if (values.length === 0) resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { + return Promise.resolve(a).then(function (x) { + values[i] = x; + if (! --remaining) resolve(values); + }, reject); + }); + }); + }, + + resolve: function (value) { + if (value instanceof Promise) return value; + if (value && typeof value.then === 'function') return new Promise(function (resolve, reject) { + value.then(resolve, reject); + }); + return new Promise(INTERNAL, true, value); + }, + + reject: PromiseReject, + + race: function () { + var values = getArrayOf.apply(null, arguments); + return new Promise(function (resolve, reject) { + values.map(function (value) { + return Promise.resolve(value).then(resolve, reject); + }); + }); + }, + + PSD: { + get: function () { + return PSD; + }, + set: function (value) { + return PSD = value; + } + }, + + newPSD: newScope, + + usePSD: usePSD, + + scheduler: { + get: function () { + return asap$1; + }, + set: function (value) { + asap$1 = value; + } + }, + + rejectionMapper: { + get: function () { + return rejectionMapper; + }, + set: function (value) { + rejectionMapper = value; + } // Map reject failures + }, + + follow: function (fn) { + return new Promise(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() + psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. + psd.finalize = callBoth(function () { + var _this3 = this; + + // Unhandled standard or 3rd part promises are put in PSD.unhandleds and + // examined upon scope completion while unhandled rejections in this Promise + // will trigger directly through psd.onunhandled + run_at_end_of_this_or_next_physical_tick(function () { + _this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, resolve, reject); + }); + }, + + on: Events(null, { "error": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler + }) + +}); + +var PromiseOnError = Promise.on.error; +PromiseOnError.subscribe = deprecated("Promise.on('error')", PromiseOnError.subscribe); +PromiseOnError.unsubscribe = deprecated("Promise.on('error').unsubscribe", PromiseOnError.unsubscribe); + +/** +* Take a potentially misbehaving resolver function and make sure +* onFulfilled and onRejected are only called once. +* +* Makes no guarantees about asynchrony. +*/ +function executePromiseTask(promise, fn) { + // Promise Resolution Procedure: + // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + try { + fn(function (value) { + if (promise._state !== null) return; + if (value === promise) throw new TypeError('A promise cannot be resolved with itself.'); + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + if (value && typeof value.then === 'function') { + executePromiseTask(promise, function (resolve, reject) { + value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject); + }); + } else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) endMicroTickScope(); + }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below + } catch (ex) { + handleRejection(promise, ex); + } +} + +function handleRejection(promise, reason) { + rejectingErrors.push(reason); + if (promise._state !== null) return; + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + reason = rejectionMapper(reason); + promise._state = false; + promise._value = reason; + debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () { + var origProp = getPropertyDescriptor(reason, "stack"); + reason._promise = promise; + setProp(reason, "stack", { + get: function () { + return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack; + } + }); + }); + // Add the failure to a list of possibly uncaught errors + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) endMicroTickScope(); +} + +function propagateAllListeners(promise) { + //debug && linkToPreviousPromise(promise); + var listeners = promise._listeners; + promise._listeners = []; + for (var i = 0, len = listeners.length; i < len; ++i) { + propagateToListener(promise, listeners[i]); + } + var psd = promise._PSD; + --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); + if (numScheduledCalls === 0) { + // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, + // and that no deferreds where listening to this rejection or success. + // Since there is a risk that our stack can contain application code that may + // do stuff after this code is finished that may generate new calls, we cannot + // call finalizers here. + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors + }, []); + } +} + +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + var psd = listener.psd; + ++psd.ref; + ++numScheduledCalls; + asap$1(callListener, [cb, promise, listener]); +} + +function callListener(cb, promise, listener) { + var outerScope = PSD; + var psd = listener.psd; + try { + if (psd !== outerScope) { + // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment. + PSD = psd; + // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. + } + + // Set static variable currentFulfiller to the promise that is being fullfilled, + // so that we connect the chain of promises (for long stacks support) + currentFulfiller = promise; + + // Call callback and resolve our listener with it's return value. + var value = promise._value, + ret; + if (promise._state) { + ret = cb(value); + } else { + if (rejectingErrors.length) rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. + } + listener.resolve(ret); + } catch (e) { + // Exception thrown in callback. Reject our listener. + listener.reject(e); + } finally { + // Restore PSD, env and currentFulfiller. + if (psd !== outerScope) { + PSD = outerScope; + // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment + } + currentFulfiller = null; + if (--numScheduledCalls === 0) finalizePhysicalTick(); + --psd.ref || psd.finalize(); + } +} + +function getStack(promise, stacks, limit) { + if (stacks.length === limit) return stacks; + var stack = ""; + if (promise._state === false) { + var failure = promise._value, + errorName, + message; + + if (failure != null) { + errorName = failure.name || "Error"; + message = failure.message || failure; + stack = prettyStack(failure, 0); + } else { + errorName = failure; // If error is undefined or null, show that. + message = ""; + } + stacks.push(errorName + (message ? ": " + message : "") + stack); + } + if (debug) { + stack = prettyStack(promise._stackHolder, 2); + if (stack && stacks.indexOf(stack) === -1) stacks.push(stack); + if (promise._prev) getStack(promise._prev, stacks, limit); + } + return stacks; +} + +function linkToPreviousPromise(promise, prev) { + // Support long stacks by linking to previous completed promise. + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + // Prohibit infinite Promise loops to get an infinite long memory consuming "tail". + promise._prev = prev; + promise._numPrev = numPrev; + } +} + +/* The callback to schedule with setImmediate() or setTimeout(). + It runs a virtual microtick and executes any callback registered in microtickQueue. + */ +function physicalTick() { + beginMicroTickScope() && endMicroTickScope(); +} + +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} + +/* Executes micro-ticks without doing try..catch. + This can be possible because we only use this internally and + the registered functions are exception-safe (they do try..catch + internally before calling any external method). If registering + functions in the microtickQueue that are not exception-safe, this + would destroy the framework and make it instable. So we don't export + our asap method. +*/ +function endMicroTickScope() { + var callbacks, i, l; + do { + while (microtickQueue.length > 0) { + callbacks = microtickQueue; + microtickQueue = []; + l = callbacks.length; + for (i = 0; i < l; ++i) { + var item = callbacks[i]; + item[0].apply(null, item[1]); + } + } + } while (microtickQueue.length > 0); + isOutsideMicroTick = true; + needsNewPhysicalTick = true; +} + +function finalizePhysicalTick() { + var unhandledErrs = unhandledErrors; + unhandledErrors = []; + unhandledErrs.forEach(function (p) { + p._PSD.onunhandled.call(null, p._value, p); + }); + var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. + var i = finalizers.length; + while (i) { + finalizers[--i](); + } +} + +function run_at_end_of_this_or_next_physical_tick(fn) { + function finalizer() { + fn(); + tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); + } + tickFinalizers.push(finalizer); + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) finalizePhysicalTick(); + }, []); +} + +function addPossiblyUnhandledError(promise) { + // Only add to unhandledErrors if not already there. The first one to add to this list + // will be upon the first rejection so that the root cause (first promise in the + // rejection chain) is the one listed. + if (!unhandledErrors.some(function (p) { + return p._value === promise._value; + })) unhandledErrors.push(promise); +} + +function markErrorAsHandled(promise) { + // Called when a reject handled is actually being called. + // Search in unhandledErrors for any promise whos _value is this promise_value (list + // contains only rejected promises, and only one item per error) + var i = unhandledErrors.length; + while (i) { + if (unhandledErrors[--i]._value === promise._value) { + // Found a promise that failed with this same error object pointer, + // Remove that since there is a listener that actually takes care of it. + unhandledErrors.splice(i, 1); + return; + } + } +} + +// By default, log uncaught errors to the console +function defaultErrorHandler(e) { + console.warn('Unhandled rejection: ' + (e.stack || e)); +} + +function PromiseReject(reason) { + return new Promise(INTERNAL, false, reason); +} + +function wrap(fn, errorCatcher) { + var psd = PSD; + return function () { + var wasRootExec = beginMicroTickScope(), + outerScope = PSD; + + try { + if (outerScope !== psd) { + // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment + PSD = psd; + // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. + } + return fn.apply(this, arguments); + } catch (e) { + errorCatcher && errorCatcher(e); + } finally { + if (outerScope !== psd) { + PSD = outerScope; + // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment + } + if (wasRootExec) endMicroTickScope(); + } + }; +} + +function newScope(fn, a1, a2, a3) { + var parent = PSD, + psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + // **KEEP** psd.env = wrappers.wrap(psd); + + // unhandleds and onunhandled should not be specifically set here. + // Leave them on parent prototype. + // unhandleds.push(err) will push to parent's prototype + // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) + ++parent.ref; + psd.finalize = function () { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD(psd, fn, a1, a2, a3); + if (psd.ref === 0) psd.finalize(); + return rv; +} + +function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + if (psd !== outerScope) { + // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment. + PSD = psd; + // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. + } + return fn(a1, a2, a3); + } finally { + if (psd !== outerScope) { + PSD = outerScope; + // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment. + } + } +} + +var UNHANDLEDREJECTION = "unhandledrejection"; + +function globalError(err, promise) { + var rv; + try { + rv = promise.onuncatched(err); + } catch (e) {} + if (rv !== false) try { + var event, + eventData = { promise: promise, reason: err }; + if (_global.document && document.createEvent) { + event = document.createEvent('Event'); + event.initEvent(UNHANDLEDREJECTION, true, true); + extend(event, eventData); + } else if (_global.CustomEvent) { + event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData }); + extend(event, eventData); + } + if (event && _global.dispatchEvent) { + dispatchEvent(event); + if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) + // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. + try { + _global.onunhandledrejection(event); + } catch (_) {} + } + if (!event.defaultPrevented) { + // Backward compatibility: fire to events registered at Promise.on.error + Promise.on.error.fire(err, promise); + } + } catch (e) {} +} + +/* **KEEP** + +export function wrapPromise(PromiseClass) { + var proto = PromiseClass.prototype; + var origThen = proto.then; + + wrappers.add({ + snapshot: () => proto.then, + restore: value => {proto.then = value;}, + wrap: () => patchedThen + }); + + function patchedThen (onFulfilled, onRejected) { + var promise = this; + var onFulfilledProxy = wrap(function(value){ + var rv = value; + if (onFulfilled) { + rv = onFulfilled(rv); + if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. + } + --PSD.ref || PSD.finalize(); + return rv; + }); + var onRejectedProxy = wrap(function(err){ + promise._$err = err; + var unhandleds = PSD.unhandleds; + var idx = unhandleds.length, + rv; + while (idx--) if (unhandleds[idx]._$err === err) break; + if (onRejected) { + if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled. + rv = onRejected(err); + if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. + } else { + if (idx === -1) unhandleds.push(promise); + rv = PromiseClass.reject(err); + rv._$nointercept = true; // Prohibit eternal loop. + } + --PSD.ref || PSD.finalize(); + return rv; + }); + + if (this._$nointercept) return origThen.apply(this, arguments); + ++PSD.ref; + return origThen.call(this, onFulfilledProxy, onRejectedProxy); + } +} + +// Global Promise wrapper +if (_global.Promise) wrapPromise(_global.Promise); + +*/ + +doFakeAutoComplete(function () { + // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie. + asap$1 = function (fn, args) { + setTimeout(function () { + fn.apply(null, args); + }, 0); + }; +}); + +function rejection(err, uncaughtHandler) { + // Get the call stack and return a rejected promise. + var rv = Promise.reject(err); + return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv; +} + +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 1.5.0, Thu Oct 13 2016 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + +var DEXIE_VERSION = '1.5.0'; +var maxString = String.fromCharCode(65535); +var maxKey = function () { + try { + IDBKeyRange.only([[]]);return [[]]; + } catch (e) { + return maxString; + } +}(); +var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; +var STRING_EXPECTED = "String expected."; +var connections = []; +var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); +var hasIEDeleteObjectStoreBug = isIEOrEdge; +var hangsOnDeleteLargeKeyRange = isIEOrEdge; +var dexieStackFrameFilter = function (frame) { + return !/(dexie\.js|dexie\.min\.js)/.test(frame); +}; + +setDebug(debug, dexieStackFrameFilter); + +function Dexie(dbName, options) { + /// Specify only if you wich to control which addons that should run on this instance + var deps = Dexie.dependencies; + var opts = extend({ + // Default Options + addons: Dexie.addons, // Pick statically registered addons by default + autoOpen: true, // Don't require db.open() explicitely. + indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env. + IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env. + }, options); + var addons = opts.addons, + autoOpen = opts.autoOpen, + indexedDB = opts.indexedDB, + IDBKeyRange = opts.IDBKeyRange; + + var globalSchema = this._dbSchema = {}; + var versions = []; + var dbStoreNames = []; + var allTables = {}; + /// + var idbdb = null; // Instance of IDBDatabase + var dbOpenError = null; + var isBeingOpened = false; + var openComplete = false; + var READONLY = "readonly", + READWRITE = "readwrite"; + var db = this; + var dbReadyResolve, + dbReadyPromise = new Promise(function (resolve) { + dbReadyResolve = resolve; + }), + cancelOpen, + openCanceller = new Promise(function (_, reject) { + cancelOpen = reject; + }); + var autoSchema = true; + var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB), + hasGetAll; + + function init() { + // Default subscribers to "versionchange" and "blocked". + // Can be overridden by custom handlers. If custom handlers return false, these default + // behaviours will be prevented. + db.on("versionchange", function (ev) { + // Default behavior for versionchange event is to close database connection. + // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); + // Let's not block the other window from making it's delete() or open() call. + // NOTE! This event is never fired in IE,Edge or Safari. + if (ev.newVersion > 0) console.warn('Another connection wants to upgrade database \'' + db.name + '\'. Closing db now to resume the upgrade.');else console.warn('Another connection wants to delete database \'' + db.name + '\'. Closing db now to resume the delete request.'); + db.close(); + // In many web applications, it would be recommended to force window.reload() + // when this event occurs. To do that, subscribe to the versionchange event + // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) + // The reason for this is that your current web app obviously has old schema code that needs + // to be updated. Another window got a newer version of the app and needs to upgrade DB but + // your window is blocking it unless we close it here. + }); + db.on("blocked", function (ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn('Dexie.delete(\'' + db.name + '\') was blocked');else console.warn('Upgrade \'' + db.name + '\' blocked by other connection holding version ' + ev.oldVersion / 10); + }); + } + + // + // + // + // ------------------------- Versioning Framework--------------------------- + // + // + // + + this.version = function (versionNumber) { + /// + /// + if (idbdb || isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versionInstance = versions.filter(function (v) { + return v._cfg.version === versionNumber; + })[0]; + if (versionInstance) return versionInstance; + versionInstance = new Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + return versionInstance; + }; + + function Version(versionNumber) { + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + this.stores({}); // Derive earlier schemas by default. + } + + extend(Version.prototype, { + stores: function (stores) { + /// + /// Defines the schema for a particular version + /// + /// + /// Example:
+ /// {users: "id++,first,last,&username,*email",
+ /// passwords: "id++,&username"}
+ ///
+ /// Syntax: {Table: "[primaryKey][++],[&][*]index1,[&][*]index2,..."}

+ /// Special characters:
+ /// "&" means unique key,
+ /// "*" means value is multiEntry,
+ /// "++" means auto-increment and only applicable for primary key
+ /// + this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; + + // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax. + var storesSpec = {}; + versions.forEach(function (version) { + // 'versions' is always sorted by lowest version first. + extend(storesSpec, version._cfg.storesSource); + }); + + var dbschema = this._cfg.dbschema = {}; + this._parseStoresSpec(storesSpec, dbschema); + // Update the latest schema to this version + // Update API + globalSchema = db._dbSchema = dbschema; + removeTablesApi([allTables, db, Transaction.prototype]); + setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema); + dbStoreNames = keys(dbschema); + return this; + }, + upgrade: function (upgradeFunction) { + /// Function that performs upgrading actions. + var self = this; + fakeAutoComplete(function () { + upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear. + }); + this._cfg.contentUpgrade = upgradeFunction; + return this; + }, + _parseStoresSpec: function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var instanceTemplate = {}; + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) throw new exceptions.Schema("Primary key cannot be multi-valued"); + if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath); + indexes.forEach(function (idx) { + if (idx.auto) throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); + if (!idx.keyPath) throw new exceptions.Schema("Index must have a name and cannot be an empty string"); + setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { + return ""; + }) : ""); + }); + outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate); + } + }); + } + }); + + function runUpgraders(oldVersion, idbtrans, reject) { + var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema); + trans.create(idbtrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + newScope(function () { + PSD.trans = trans; + if (oldVersion === 0) { + // Create tables: + keys(globalSchema).forEach(function (tableName) { + createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + Promise.follow(function () { + return db.on.populate.fire(trans); + }).catch(rejectTransaction); + } else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction); + }); + } + + function updateTablesAndIndexes(oldVersion, trans, idbtrans) { + // Upgrade version to version, step-by-step from oldest to newest version. + // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version) + var queue = []; + var oldVersionStruct = versions.filter(function (version) { + return version._cfg.version === oldVersion; + })[0]; + if (!oldVersionStruct) throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing"); + globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema; + var anyContentUpgraderHasRun = false; + + var versToRun = versions.filter(function (v) { + return v._cfg.version > oldVersion; + }); + versToRun.forEach(function (version) { + /// + queue.push(function () { + var oldSchema = globalSchema; + var newSchema = version._cfg.dbschema; + adjustToExistingIndexNames(oldSchema, idbtrans); + adjustToExistingIndexNames(newSchema, idbtrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + // Add tables + diff.add.forEach(function (tuple) { + createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + // Change tables + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } else { + var store = idbtrans.objectStore(change.name); + // Add indexes + change.add.forEach(function (idx) { + addIndex(store, idx); + }); + // Update indexes + change.change.forEach(function (idx) { + store.deleteIndex(idx.name); + addIndex(store, idx); + }); + // Delete indexes + change.del.forEach(function (idxName) { + store.deleteIndex(idxName); + }); + } + }); + if (version._cfg.contentUpgrade) { + anyContentUpgraderHasRun = true; + return Promise.follow(function () { + version._cfg.contentUpgrade(trans); + }); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of. + var newSchema = version._cfg.dbschema; + // Delete old tables + deleteRemovedTables(newSchema, idbtrans); + } + }); + }); + + // Now, create a queue execution engine + function runQueue() { + return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve(); + } + + return runQueue().then(function () { + createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version) + }); + } + + function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], // Array of table names + add: [], // Array of [tableName, newDefinition] + change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs} + }; + for (var table in oldSchema) { + if (!newSchema[table]) diff.del.push(table); + } + for (table in newSchema) { + var oldDef = oldSchema[table], + newDef = newSchema[table]; + if (!oldDef) { + diff.add.push([table, newDef]); + } else { + var change = { + name: table, + def: newDef, + recreate: false, + del: [], + add: [], + change: [] + }; + if (oldDef.primKey.src !== newDef.primKey.src) { + // Primary key has changed. Remove and re-add table. + change.recreate = true; + diff.change.push(change); + } else { + // Same primary key. Just find out what differs: + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + for (var idxName in oldIndexes) { + if (!newIndexes[idxName]) change.del.push(idxName); + } + for (idxName in newIndexes) { + var oldIdx = oldIndexes[idxName], + newIdx = newIndexes[idxName]; + if (!oldIdx) change.add.push(newIdx);else if (oldIdx.src !== newIdx.src) change.change.push(newIdx); + } + if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { + diff.change.push(change); + } + } + } + } + return diff; + } + + function createTable(idbtrans, tableName, primKey, indexes) { + /// + var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); + indexes.forEach(function (idx) { + addIndex(store, idx); + }); + return store; + } + + function createMissingTables(newSchema, idbtrans) { + keys(newSchema).forEach(function (tableName) { + if (!idbtrans.db.objectStoreNames.contains(tableName)) { + createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); + } + }); + } + + function deleteRemovedTables(newSchema, idbtrans) { + for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) { + var storeName = idbtrans.db.objectStoreNames[i]; + if (newSchema[storeName] == null) { + idbtrans.db.deleteObjectStore(storeName); + } + } + } + + function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); + } + + function dbUncaught(err) { + return db.on.error.fire(err); + } + + // + // + // Dexie Protected API + // + // + + this._allTables = allTables; + + this._tableFactory = function createTable(mode, tableSchema) { + /// + if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection);else return new WriteableTable(tableSchema.name, tableSchema); + }; + + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { + return new Transaction(mode, storeNames, dbschema, parentTransaction); + }; + + /* Generate a temporary transaction when db operations are done outside a transactino scope. + */ + function tempTransaction(mode, storeNames, fn) { + // Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it. + if (!openComplete && !PSD.letThrough) { + if (!isBeingOpened) { + if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught); + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + return dbReadyPromise.then(function () { + return tempTransaction(mode, storeNames, fn); + }); + } else { + var trans = db._createTransaction(mode, storeNames, globalSchema); + return trans._promise(mode, function (resolve, reject) { + newScope(function () { + // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise. + PSD.trans = trans; + fn(resolve, reject, trans); + }); + }).then(function (result) { + // Instead of resolving value directly, wait with resolving it until transaction has completed. + // Otherwise the data would not be in the DB if requesting it in the then() operation. + // Specifically, to ensure that the following expression will work: + // + // db.friends.put({name: "Arne"}).then(function () { + // db.friends.where("name").equals("Arne").count(function(count) { + // assert (count === 1); + // }); + // }); + // + return trans._completion.then(function () { + return result; + }); + }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major. + trans._reject(err); + return rejection(err); + });*/ + } + } + + this._whenReady = function (fn) { + return new Promise(fake || openComplete || PSD.letThrough ? fn : function (resolve, reject) { + if (!isBeingOpened) { + if (!autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + dbReadyPromise.then(function () { + fn(resolve, reject); + }); + }).uncaught(dbUncaught); + }; + + // + // + // + // + // Dexie API + // + // + // + + this.verno = 0; + + this.open = function () { + if (isBeingOpened || idbdb) return dbReadyPromise.then(function () { + return dbOpenError ? rejection(dbOpenError, dbUncaught) : db; + }); + debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called. + isBeingOpened = true; + dbOpenError = null; + openComplete = false; + + // Function pointers to call when the core opening process completes. + var resolveDbReady = dbReadyResolve, + + // upgradeTransaction to abort on failure. + upgradeTransaction = null; + + return Promise.race([openCanceller, new Promise(function (resolve, reject) { + doFakeAutoComplete(function () { + return resolve(); + }); + + // Make sure caller has specified at least one version + if (versions.length > 0) autoSchema = false; + + // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE: + // IE fails when deleting objectStore after reading from it. + // A future version of Dexie.js will stopover an intermediate version to workaround this. + // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number. + + // If no API, throw! + if (!indexedDB) throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL " + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill."); + + var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134 + req.onerror = wrap(eventRejectHandler(reject)); + req.onblocked = wrap(fireOnBlocked); + req.onupgradeneeded = wrap(function (e) { + upgradeTransaction = req.transaction; + if (autoSchema && !db._allowEmptyDB) { + // Unless an addon has specified db._allowEmptyDB, lets make the call fail. + // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases. + // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we + // do not create a new database by accident here. + req.onerror = preventDefault; // Prohibit onabort error from firing before we're done! + upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.) + // Close database and delete it. + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here! + delreq.onsuccess = delreq.onerror = wrap(function () { + reject(new exceptions.NoSuchDatabase('Database ' + dbName + ' doesnt exist')); + }); + } else { + upgradeTransaction.onerror = wrap(eventRejectHandler(reject)); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix. + runUpgraders(oldVer / 10, upgradeTransaction, reject, req); + } + }, reject); + + req.onsuccess = wrap(function () { + // Core opening procedure complete. Now let's just record some stuff. + upgradeTransaction = null; + idbdb = req.result; + connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari. + + if (autoSchema) readGlobalSchema();else if (idbdb.objectStoreNames.length > 0) { + try { + adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY)); + } catch (e) { + // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120. + } + } + + idbdb.onversionchange = wrap(function (ev) { + db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari) + db.on("versionchange").fire(ev); + }); + + if (!hasNativeGetDatabaseNames) { + // Update localStorage with list of database names + globalDatabaseList(function (databaseNames) { + if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName); + }); + } + + resolve(); + }, reject); + })]).then(function () { + // Before finally resolving the dbReadyPromise and this promise, + // call and await all on('ready') subscribers: + // Dexie.vip() makes subscribers able to use the database while being opened. + // This is a must since these subscribers take part of the opening procedure. + return Dexie.vip(db.on.ready.fire); + }).then(function () { + // Resolve the db.open() with the db instance. + isBeingOpened = false; + return db; + }).catch(function (err) { + try { + // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit. + upgradeTransaction && upgradeTransaction.abort(); + } catch (e) {} + isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event). + db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh. + // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that. + dbOpenError = err; // Record the error. It will be used to reject further promises of db operations. + return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught(). + }).finally(function () { + openComplete = true; + resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters. + }); + }; + + this.close = function () { + var idx = connections.indexOf(db); + if (idx >= 0) connections.splice(idx, 1); + if (idbdb) { + try { + idbdb.close(); + } catch (e) {} + idbdb = null; + } + autoOpen = false; + dbOpenError = new exceptions.DatabaseClosed(); + if (isBeingOpened) cancelOpen(dbOpenError); + // Reset dbReadyPromise promise: + dbReadyPromise = new Promise(function (resolve) { + dbReadyResolve = resolve; + }); + openCanceller = new Promise(function (_, reject) { + cancelOpen = reject; + }); + }; + + this.delete = function () { + var hasArguments = arguments.length > 0; + return new Promise(function (resolve, reject) { + if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (isBeingOpened) { + dbReadyPromise.then(doDelete); + } else { + doDelete(); + } + function doDelete() { + db.close(); + var req = indexedDB.deleteDatabase(dbName); + req.onsuccess = wrap(function () { + if (!hasNativeGetDatabaseNames) { + globalDatabaseList(function (databaseNames) { + var pos = databaseNames.indexOf(dbName); + if (pos >= 0) return databaseNames.splice(pos, 1); + }); + } + resolve(); + }); + req.onerror = wrap(eventRejectHandler(reject)); + req.onblocked = fireOnBlocked; + } + }).uncaught(dbUncaught); + }; + + this.backendDB = function () { + return idbdb; + }; + + this.isOpen = function () { + return idbdb !== null; + }; + this.hasFailed = function () { + return dbOpenError !== null; + }; + this.dynamicallyOpened = function () { + return autoSchema; + }; + + // + // Properties + // + this.name = dbName; + + // db.tables - an array of all Table instances. + setProp(this, "tables", { + get: function () { + /// + return keys(allTables).map(function (name) { + return allTables[name]; + }); + } + }); + + // + // Events + // + this.on = Events(this, "error", "populate", "blocked", "versionchange", { ready: [promisableChain, nop] }); + this.on.error.subscribe = deprecated("Dexie.on.error", this.on.error.subscribe); + this.on.error.unsubscribe = deprecated("Dexie.on.error.unsubscribe", this.on.error.unsubscribe); + + this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { + return function (subscriber, bSticky) { + Dexie.vip(function () { + if (openComplete) { + // Database already open. Call subscriber asap. + if (!dbOpenError) Promise.resolve().then(subscriber); + // bSticky: Also subscribe to future open sucesses (after close / reopen) + if (bSticky) subscribe(subscriber); + } else { + // Database not yet open. Subscribe to it. + subscribe(subscriber); + // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. + if (!bSticky) subscribe(function unsubscribe() { + db.on.ready.unsubscribe(subscriber); + db.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + + fakeAutoComplete(function () { + db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema)); + db.on("error").fire(new Error()); + }); + + this.transaction = function (mode, tableInstances, scopeFunc) { + /// + /// + /// + /// "r" for readonly, or "rw" for readwrite + /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction + /// Function to execute with transaction + + // Let table arguments be all arguments between mode and last argument. + var i = arguments.length; + if (i < 2) throw new exceptions.InvalidArgument("Too few arguments"); + // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments) + // and clone arguments except the first one into local var 'args'. + var args = new Array(i - 1); + while (--i) { + args[i - 1] = arguments[i]; + } // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments. + scopeFunc = args.pop(); + var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays. + var parentTransaction = PSD.trans; + // Check if parent transactions is bound to this db instance, and if caller wants to reuse it + if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. + + try { + // + // Get storeNames from arguments. Either through given table instances, or through given table names. + // + var storeNames = tables.map(function (table) { + var storeName = table instanceof Table ? table.name : table; + if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); + return storeName; + }); + + // + // Resolve mode. Allow shortcuts "r" and "rw". + // + if (mode == "r" || mode == READONLY) mode = READONLY;else if (mode == "rw" || mode == READWRITE) mode = READWRITE;else throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + + if (parentTransaction) { + // Basic checks + if (parentTransaction.mode === READONLY && mode === READWRITE) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); + } + if (parentTransaction) { + storeNames.forEach(function (storeName) { + if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } else throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); + } + }); + } + } + } catch (e) { + return parentTransaction ? parentTransaction._promise(null, function (_, reject) { + reject(e); + }) : rejection(e, dbUncaught); + } + // If this is a sub-transaction, lock the parent and then launch the sub-transaction. + return parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, "lock") : db._whenReady(enterTransactionScope); + + function enterTransactionScope(resolve) { + var parentPSD = PSD; + resolve(Promise.resolve().then(function () { + return newScope(function () { + // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction(). + PSD.transless = PSD.transless || parentPSD; + // Our transaction. + //return new Promise((resolve, reject) => { + var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction); + // Let the transaction instance be part of a Promise-specific data (PSD) value. + PSD.trans = trans; + + if (parentTransaction) { + // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing) + trans.idbtrans = parentTransaction.idbtrans; + } else { + trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it. + } + + // Provide arguments to the scope function (for backward compatibility) + var tableArgs = storeNames.map(function (name) { + return allTables[name]; + }); + tableArgs.push(trans); + + var returnValue; + return Promise.follow(function () { + // Finally, call the scope function with our table and transaction arguments. + returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func. + if (returnValue) { + if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + // scopeFunc returned an iterator with throw-support. Handle yield as await. + returnValue = awaitIterator(returnValue); + } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) { + throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: " + scopeFunc.toString()); + } + } + }).uncaught(dbUncaught).then(function () { + if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion. + return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well. + }).then(function () { + return returnValue; + }).catch(function (e) { + //reject(e); + trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc! + return rejection(e); + }); + //}); + }); + })); + } + }; + + this.table = function (tableName) { + /// + if (fake && autoSchema) return new WriteableTable(tableName); + if (!hasOwn(allTables, tableName)) { + throw new exceptions.InvalidTable('Table ' + tableName + ' does not exist'); + } + return allTables[tableName]; + }; + + // + // + // + // Table Class + // + // + // + function Table(name, tableSchema, collClass) { + /// + this.name = name; + this.schema = tableSchema; + this.hook = allTables[name] ? allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + this._collClass = collClass || Collection; + } + + props(Table.prototype, { + + // + // Table Protected Methods + // + + _trans: function getTransaction(mode, fn, writeLocked) { + var trans = PSD.trans; + return trans && trans.db === db ? trans._promise(mode, fn, writeLocked) : tempTransaction(mode, [this.name], fn); + }, + _idbstore: function getIDBObjectStore(mode, fn, writeLocked) { + if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion. + var trans = PSD.trans, + tableName = this.name; + function supplyIdbStore(resolve, reject, trans) { + fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans); + } + return trans && trans.db === db ? trans._promise(mode, supplyIdbStore, writeLocked) : tempTransaction(mode, [this.name], supplyIdbStore); + }, + + // + // Table Public Methods + // + get: function (key, cb) { + var self = this; + return this._idbstore(READONLY, function (resolve, reject, idbstore) { + fake && resolve(self.schema.instanceTemplate); + var req = idbstore.get(key); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(self.hook.reading.fire(req.result)); + }, reject); + }).then(cb); + }, + where: function (indexName) { + return new WhereClause(this, indexName); + }, + count: function (cb) { + return this.toCollection().count(cb); + }, + offset: function (offset) { + return this.toCollection().offset(offset); + }, + limit: function (numRows) { + return this.toCollection().limit(numRows); + }, + reverse: function () { + return this.toCollection().reverse(); + }, + filter: function (filterFunction) { + return this.toCollection().and(filterFunction); + }, + each: function (fn) { + return this.toCollection().each(fn); + }, + toArray: function (cb) { + return this.toCollection().toArray(cb); + }, + orderBy: function (index) { + return new this._collClass(new WhereClause(this, index)); + }, + + toCollection: function () { + return new this._collClass(new WhereClause(this)); + }, + + mapToClass: function (constructor, structure) { + /// + /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making + /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}. + /// + /// Constructor function representing the class. + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], password} + this.schema.mappedClass = constructor; + var instanceTemplate = Object.create(constructor.prototype); + if (structure) { + // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance. + applyStructure(instanceTemplate, structure); + } + this.schema.instanceTemplate = instanceTemplate; + + // Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class + // no matter which method to use for reading (Table.get() or Table.where(...)... ) + var readHook = function (obj) { + if (!obj) return obj; // No valid object. (Value is null). Return as is. + // Create a new object that derives from constructor: + var res = Object.create(constructor.prototype); + // Clone members: + for (var m in obj) { + if (hasOwn(obj, m)) try { + res[m] = obj[m]; + } catch (_) {} + }return res; + }; + + if (this.schema.readHook) { + this.hook.reading.unsubscribe(this.schema.readHook); + } + this.schema.readHook = readHook; + this.hook("reading", readHook); + return constructor; + }, + defineClass: function (structure) { + /// + /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database + /// as well as making it possible to extend the prototype of the returned constructor function. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + return this.mapToClass(Dexie.defineClass(structure), structure); + } + }); + + // + // + // + // WriteableTable Class (extends Table) + // + // + // + function WriteableTable(name, tableSchema, collClass) { + Table.call(this, name, tableSchema, collClass || WriteableCollection); + } + + function BulkErrorHandlerCatchAll(errorList, done, supportHooks) { + return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) { + errorList.push(e); + done && done(); + }); + } + + function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) { + // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...], + // else keysOrTuples must be just an array of keys: [key1, key2, ...]. + return new Promise(function (resolve, reject) { + var len = keysOrTuples.length, + lastItem = len - 1; + if (len === 0) return resolve(); + if (!hasDeleteHook) { + for (var i = 0; i < len; ++i) { + var req = idbstore.delete(keysOrTuples[i]); + req.onerror = wrap(eventRejectHandler(reject)); + if (i === lastItem) req.onsuccess = wrap(function () { + return resolve(); + }); + } + } else { + var hookCtx, + errorHandler = hookedEventRejectHandler(reject), + successHandler = hookedEventSuccessHandler(null); + tryCatch(function () { + for (var i = 0; i < len; ++i) { + hookCtx = { onsuccess: null, onerror: null }; + var tuple = keysOrTuples[i]; + deletingHook.call(hookCtx, tuple[0], tuple[1], trans); + var req = idbstore.delete(tuple[0]); + req._hookCtx = hookCtx; + req.onerror = errorHandler; + if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve);else req.onsuccess = successHandler; + } + }, function (err) { + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + } + }).uncaught(dbUncaught); + } + + derive(WriteableTable).from(Table).extend({ + bulkDelete: function (keys$$1) { + if (this.hook.deleting.fire === nop) { + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + resolve(bulkDelete(idbstore, trans, keys$$1, false, nop)); + }); + } else { + return this.where(':id').anyOf(keys$$1).delete().then(function () {}); // Resolve with undefined. + } + }, + bulkPut: function (objects, keys$$1) { + var _this = this; + + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) return resolve(); // Caller provided empty list. + var done = function (result) { + if (errorList.length === 0) resolve(result);else reject(new BulkError(_this.name + '.bulkPut(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList)); + }; + var req, + errorList = [], + errorHandler, + numObjs = objects.length, + table = _this; + if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) { + // + // Standard Bulk (no 'creating' or 'updating' hooks to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } else { + var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(function (o) { + return getByKeyPath(o, idbstore.keyPath); + }); + // Generate map of {[key]: object} + var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) { + return key != null && [key, objects[i]]; + }); + var promise = !effectiveKeys ? + + // Auto-incremented key-less objects only without any keys argument. + table.bulkAdd(objects) : + + // Keys provided. Either as inbound in provided objects, or as a keys argument. + // Begin with updating those that exists in DB: + table.where(':id').anyOf(effectiveKeys.filter(function (key) { + return key != null; + })).modify(function () { + this.value = objectLookup[this.primKey]; + objectLookup[this.primKey] = null; // Mark as "don't add this" + }).catch(ModifyError, function (e) { + errorList = e.failures; // No need to concat here. These are the first errors added. + }).then(function () { + // Now, let's examine which items didnt exist so we can add them: + var objsToAdd = [], + keysToAdd = keys$$1 && []; + // Iterate backwards. Why? Because if same key was used twice, just add the last one. + for (var i = effectiveKeys.length - 1; i >= 0; --i) { + var key = effectiveKeys[i]; + if (key == null || objectLookup[key]) { + objsToAdd.push(objects[i]); + keys$$1 && keysToAdd.push(key); + if (key != null) objectLookup[key] = null; // Mark as "dont add again" + } + } + // The items are in reverse order so reverse them before adding. + // Could be important in order to get auto-incremented keys the way the caller + // would expect. Could have used unshift instead of push()/reverse(), + // but: http://jsperf.com/unshift-vs-reverse + objsToAdd.reverse(); + keys$$1 && keysToAdd.reverse(); + return table.bulkAdd(objsToAdd, keysToAdd); + }).then(function (lastAddedKey) { + // Resolve with key of the last object in given arguments to bulkPut(): + var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided. + return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey; + }); + + promise.then(done).catch(BulkError, function (e) { + // Concat failure from ModifyError and reject using our 'done' method. + errorList = errorList.concat(e.failures); + done(); + }).catch(reject); + } + }, "locked"); // If called from transaction scope, lock transaction til all steps are done. + }, + bulkAdd: function (objects, keys$$1) { + var self = this, + creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) return resolve(); // Caller provided empty list. + function done(result) { + if (errorList.length === 0) resolve(result);else reject(new BulkError(self.name + '.bulkAdd(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList)); + } + var req, + errorList = [], + errorHandler, + successHandler, + numObjs = objects.length; + if (creatingHook !== nop) { + // + // There are subscribers to hook('creating') + // Must behave as documented. + // + var keyPath = idbstore.keyPath, + hookCtx; + errorHandler = BulkErrorHandlerCatchAll(errorList, null, true); + successHandler = hookedEventSuccessHandler(null); + + tryCatch(function () { + for (var i = 0, l = objects.length; i < l; ++i) { + hookCtx = { onerror: null, onsuccess: null }; + var key = keys$$1 && keys$$1[i]; + var obj = objects[i], + effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined, + keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); + if (effectiveKey == null && keyToUse != null) { + if (keyPath) { + obj = deepClone(obj); + setByKeyPath(obj, keyPath, keyToUse); + } else { + key = keyToUse; + } + } + req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + if (i < l - 1) { + req.onerror = errorHandler; + if (hookCtx.onsuccess) req.onsuccess = successHandler; + } + } + }, function (err) { + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + + req.onerror = BulkErrorHandlerCatchAll(errorList, done, true); + req.onsuccess = hookedEventSuccessHandler(done); + } else { + // + // Standard Bulk (no 'creating' hook to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } + }); + }, + add: function (obj, key) { + /// + /// Add an object to the database. In case an object with same primary key already exists, the object will not be added. + /// + /// A javascript object to insert + /// Primary key + var creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + var hookCtx = { onsuccess: null, onerror: null }; + if (creatingHook !== nop) { + var effectiveKey = key != null ? key : idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined; + var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key. + if (effectiveKey == null && keyToUse != null) { + // Using "==" and "!=" to check for either null or undefined! + if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse);else key = keyToUse; + } + } + try { + var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + req.onerror = hookedEventRejectHandler(reject); + req.onsuccess = hookedEventSuccessHandler(function (result) { + // TODO: Remove these two lines in next major release (2.0?) + // It's no good practice to have side effects on provided parameters + var keyPath = idbstore.keyPath; + if (keyPath) setByKeyPath(obj, keyPath, result); + resolve(result); + }); + } catch (e) { + if (hookCtx.onerror) hookCtx.onerror(e); + throw e; + } + }); + }, + + put: function (obj, key) { + /// + /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated. + /// + /// A javascript object to insert or update + /// Primary key + var self = this, + creatingHook = this.hook.creating.fire, + updatingHook = this.hook.updating.fire; + if (creatingHook !== nop || updatingHook !== nop) { + // + // People listens to when("creating") or when("updating") events! + // We must know whether the put operation results in an CREATE or UPDATE. + // + return this._trans(READWRITE, function (resolve, reject, trans) { + // Since key is optional, make sure we get it from obj if not provided + var effectiveKey = key !== undefined ? key : self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath); + if (effectiveKey == null) { + // "== null" means checking for either null or undefined. + // No primary key. Must use add(). + self.add(obj).then(resolve, reject); + } else { + // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add(). + trans._lock(); // Needed because operation is splitted into modify() and add(). + // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation. + obj = deepClone(obj); + self.where(":id").equals(effectiveKey).modify(function () { + // Replace extisting value with our object + // CRUD event firing handled in WriteableCollection.modify() + this.value = obj; + }).then(function (count) { + if (count === 0) { + // Object's key was not found. Add the object instead. + // CRUD event firing will be done in add() + return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key. + } else { + return effectiveKey; // Resolve with the provided key. + } + }).finally(function () { + trans._unlock(); + }).then(resolve, reject); + } + }); + } else { + // Use the standard IDB put() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function (ev) { + var keyPath = idbstore.keyPath; + if (keyPath) setByKeyPath(obj, keyPath, ev.target.result); + resolve(req.result); + }; + }); + } + }, + + 'delete': function (key) { + /// Primary key of the object to delete + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will + // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted. + return this.where(":id").equals(key).delete(); + } else { + // No one listens. Use standard IDB delete() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.delete(key); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function () { + resolve(req.result); + }; + }); + } + }, + + clear: function () { + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will + // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted. + return this.toCollection().delete(); + } else { + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.clear(); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function () { + resolve(req.result); + }; + }); + } + }, + + update: function (keyOrObject, modifications) { + if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument("Modifications must be an object."); + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + // object to modify. Also modify given object with the modifications: + keys(modifications).forEach(function (keyPath) { + setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); + }); + var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === undefined) return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key"), dbUncaught); + return this.where(":id").equals(key).modify(modifications); + } else { + // key to modify + return this.where(":id").equals(keyOrObject).modify(modifications); + } + } + }); + + // + // + // + // Transaction Class + // + // + // + function Transaction(mode, storeNames, dbschema, parent) { + var _this2 = this; + + /// + /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction. + /// + /// Any of "readwrite" or "readonly" + /// Array of table names to operate on + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.idbtrans = null; + this.on = Events(this, "complete", "error", "abort"); + this.parent = parent || null; + this.active = true; + this._tables = null; + this._reculock = 0; + this._blockedFuncs = []; + this._psd = null; + this._dbschema = dbschema; + this._resolve = null; + this._reject = null; + this._completion = new Promise(function (resolve, reject) { + _this2._resolve = resolve; + _this2._reject = reject; + }).uncaught(dbUncaught); + + this._completion.then(function () { + _this2.on.complete.fire(); + }, function (e) { + _this2.on.error.fire(e); + _this2.parent ? _this2.parent._reject(e) : _this2.active && _this2.idbtrans && _this2.idbtrans.abort(); + _this2.active = false; + return rejection(e); // Indicate we actually DO NOT catch this error. + }); + } + + props(Transaction.prototype, { + // + // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions) + // + _lock: function () { + assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + // Temporary set all requests into a pending queue if they are called before database is ready. + ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage) + if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this; + return this; + }, + _unlock: function () { + assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + if (--this._reculock === 0) { + if (!PSD.global) PSD.lockOwnerFor = null; + while (this._blockedFuncs.length > 0 && !this._locked()) { + var fn = this._blockedFuncs.shift(); + try { + fn(); + } catch (e) {} + } + } + return this; + }, + _locked: function () { + // Checks if any write-lock is applied on this transaction. + // To simplify the Dexie API for extension implementations, we support recursive locks. + // This is accomplished by using "Promise Specific Data" (PSD). + // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ). + // PSD is local to code executing on top of the call stacks of any of any code executed by Promise(): + // * callback given to the Promise() constructor (function (resolve, reject){...}) + // * callbacks given to then()/catch()/finally() methods (function (value){...}) + // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise. + // Derivation is done so that the inner PSD __proto__ points to the outer PSD. + // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock. + return this._reculock && PSD.lockOwnerFor !== this; + }, + create: function (idbtrans) { + var _this3 = this; + + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()! + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + + idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode); + idbtrans.onerror = wrap(function (ev) { + preventDefault(ev); // Prohibit default bubbling to window.error + _this3._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(function (ev) { + preventDefault(ev); + _this3.active && _this3._reject(new exceptions.Abort()); + _this3.active = false; + _this3.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(function () { + _this3.active = false; + _this3._resolve(); + }); + return this; + }, + _promise: function (mode, fn, bWriteLock) { + var self = this; + return newScope(function () { + var p; + // Read lock always + if (!self._locked()) { + p = self.active ? new Promise(function (resolve, reject) { + if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly("Transaction is readonly"); + if (!self.idbtrans && mode) self.create(); + if (bWriteLock) self._lock(); // Write lock if write operation is requested + fn(resolve, reject, self); + }) : rejection(new exceptions.TransactionInactive()); + if (self.active && bWriteLock) p.finally(function () { + self._unlock(); + }); + } else { + // Transaction is write-locked. Wait for mutex. + p = new Promise(function (resolve, reject) { + self._blockedFuncs.push(function () { + self._promise(mode, fn, bWriteLock).then(resolve, reject); + }); + }); + } + p._lib = true; + return p.uncaught(dbUncaught); + }); + }, + + // + // Transaction Public Properties and Methods + // + abort: function () { + this.active && this._reject(new exceptions.Abort()); + this.active = false; + }, + + tables: { + get: deprecated("Transaction.tables", function () { + return arrayToObject(this.storeNames, function (name) { + return [name, allTables[name]]; + }); + }, "Use db.tables()") + }, + + complete: deprecated("Transaction.complete()", function (cb) { + return this.on("complete", cb); + }), + + error: deprecated("Transaction.error()", function (cb) { + return this.on("error", cb); + }), + + table: deprecated("Transaction.table()", function (name) { + if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable("Table " + name + " not in transaction"); + return allTables[name]; + }) + + }); + + // + // + // + // WhereClause + // + // + // + function WhereClause(table, index, orCollection) { + /// + /// + /// + this._ctx = { + table: table, + index: index === ":id" ? null : index, + collClass: table._collClass, + or: orCollection + }; + } + + props(WhereClause.prototype, function () { + + // WhereClause private methods + + function fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause; + + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; + } + + function emptyCollection(whereClause) { + return new whereClause._ctx.collClass(whereClause, function () { + return IDBKeyRange.only(""); + }).limit(0); + } + + function upperFactory(dir) { + return dir === "next" ? function (s) { + return s.toUpperCase(); + } : function (s) { + return s.toLowerCase(); + }; + } + function lowerFactory(dir) { + return dir === "next" ? function (s) { + return s.toLowerCase(); + } : function (s) { + return s.toUpperCase(); + }; + } + function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { + var length = Math.min(key.length, lowerNeedle.length); + var llp = -1; + for (var i = 0; i < length; ++i) { + var lwrKeyChar = lowerKey[i]; + if (lwrKeyChar !== lowerNeedle[i]) { + if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); + if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); + if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); + return null; + } + if (cmp(key[i], lwrKeyChar) < 0) llp = i; + } + if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length); + if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length); + return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1); + } + + function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { + /// + var upper, + lower, + compare, + upperNeedles, + lowerNeedles, + direction, + nextKeySuffix, + needlesLen = needles.length; + if (!needles.every(function (s) { + return typeof s === 'string'; + })) { + return fail(whereClause, STRING_EXPECTED); + } + function initDirection(dir) { + upper = upperFactory(dir); + lower = lowerFactory(dir); + compare = dir === "next" ? simpleCompare : simpleCompareReverse; + var needleBounds = needles.map(function (needle) { + return { lower: lower(needle), upper: upper(needle) }; + }).sort(function (a, b) { + return compare(a.lower, b.lower); + }); + upperNeedles = needleBounds.map(function (nb) { + return nb.upper; + }); + lowerNeedles = needleBounds.map(function (nb) { + return nb.lower; + }); + direction = dir; + nextKeySuffix = dir === "next" ? "" : suffix; + } + initDirection("next"); + + var c = new whereClause._ctx.collClass(whereClause, function () { + return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); + }); + + c._ondirectionchange = function (direction) { + // This event onlys occur before filter is called the first time. + initDirection(direction); + }; + + var firstPossibleNeedle = 0; + + c._addAlgorithm(function (cursor, advance, resolve) { + /// + /// + /// + var key = cursor.key; + if (typeof key !== 'string') return false; + var lowerKey = lower(key); + if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { + return true; + } else { + var lowestPossibleCasing = null; + for (var i = firstPossibleNeedle; i < needlesLen; ++i) { + var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); + if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1;else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { + lowestPossibleCasing = casing; + } + } + if (lowestPossibleCasing !== null) { + advance(function () { + cursor.continue(lowestPossibleCasing + nextKeySuffix); + }); + } else { + advance(resolve); + } + return false; + } + }); + return c; + } + + // + // WhereClause public methods + // + return { + between: function (lower, upper, includeLower, includeUpper) { + /// + /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates. + /// + /// + /// + /// Whether items that equals lower should be included. Default true. + /// Whether items that equals upper should be included. Default false. + /// + includeLower = includeLower !== false; // Default to true + includeUpper = includeUpper === true; // Default to false + try { + if (cmp(lower, upper) > 0 || cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection. + return new this._ctx.collClass(this, function () { + return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); + }); + } catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }, + equals: function (value) { + return new this._ctx.collClass(this, function () { + return IDBKeyRange.only(value); + }); + }, + above: function (value) { + return new this._ctx.collClass(this, function () { + return IDBKeyRange.lowerBound(value, true); + }); + }, + aboveOrEqual: function (value) { + return new this._ctx.collClass(this, function () { + return IDBKeyRange.lowerBound(value); + }); + }, + below: function (value) { + return new this._ctx.collClass(this, function () { + return IDBKeyRange.upperBound(value, true); + }); + }, + belowOrEqual: function (value) { + return new this._ctx.collClass(this, function () { + return IDBKeyRange.upperBound(value); + }); + }, + startsWith: function (str) { + /// + if (typeof str !== 'string') return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }, + startsWithIgnoreCase: function (str) { + /// + if (str === "") return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { + return x.indexOf(a[0]) === 0; + }, [str], maxString); + }, + equalsIgnoreCase: function (str) { + /// + return addIgnoreCaseAlgorithm(this, function (x, a) { + return x === a[0]; + }, [str], ""); + }, + anyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { + return a.indexOf(x) !== -1; + }, set, ""); + }, + startsWithAnyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { + return a.some(function (n) { + return x.indexOf(n) === 0; + }); + }, set, maxString); + }, + anyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = ascending; + try { + set.sort(compare); + } catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) return emptyCollection(this); + var c = new this._ctx.collClass(this, function () { + return IDBKeyRange.bound(set[0], set[set.length - 1]); + }); + + c._ondirectionchange = function (direction) { + compare = direction === "next" ? ascending : descending; + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function () { + cursor.continue(set[i]); + }); + return false; + } + }); + return c; + }, + + notEqual: function (value) { + return this.inAnyRange([[-Infinity, value], [value, maxKey]], { includeLowers: false, includeUppers: false }); + }, + + noneOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection. + try { + set.sort(ascending); + } catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + // Transform ["a","b","c"] to a set of ranges for between/above/below: [[-Infinity,"a"], ["a","b"], ["b","c"], ["c",maxKey]] + var ranges = set.reduce(function (res, val) { + return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]]; + }, null); + ranges.push([set[set.length - 1], maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + }, + + /** Filter out values withing given set of ranges. + * Example, give children and elders a rebate of 50%: + * + * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2}); + * + * @param {(string|number|Date|Array)[][]} ranges + * @param {{includeLowers: boolean, includeUppers: boolean}} options + */ + inAnyRange: function (ranges, options) { + var ctx = this._ctx; + if (ranges.length === 0) return emptyCollection(this); + if (!ranges.every(function (range) { + return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0; + })) { + return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); + } + var includeLowers = !options || options.includeLowers !== false; // Default to true + var includeUppers = options && options.includeUppers === true; // Default to false + + function addRange(ranges, newRange) { + for (var i = 0, l = ranges.length; i < l; ++i) { + var range = ranges[i]; + if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { + range[0] = min(range[0], newRange[0]); + range[1] = max(range[1], newRange[1]); + break; + } + } + if (i === l) ranges.push(newRange); + return ranges; + } + + var sortDirection = ascending; + function rangeSorter(a, b) { + return sortDirection(a[0], b[0]); + } + + // Join overlapping ranges + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + + var i = 0; + var keyIsBeyondCurrentEntry = includeUppers ? function (key) { + return ascending(key, set[i][1]) > 0; + } : function (key) { + return ascending(key, set[i][1]) >= 0; + }; + + var keyIsBeforeCurrentEntry = includeLowers ? function (key) { + return descending(key, set[i][0]) > 0; + } : function (key) { + return descending(key, set[i][0]) >= 0; + }; + + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + + var checkKey = keyIsBeyondCurrentEntry; + + var c = new ctx.collClass(this, function () { + return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); + }); + + c._ondirectionchange = function (direction) { + if (direction === "next") { + checkKey = keyIsBeyondCurrentEntry; + sortDirection = ascending; + } else { + checkKey = keyIsBeforeCurrentEntry; + sortDirection = descending; + } + set.sort(rangeSorter); + }; + + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (checkKey(key)) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) { + // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border. + // Continue to next key but don't include this one. + return false; + } else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function () { + if (sortDirection === ascending) cursor.continue(set[i][0]);else cursor.continue(set[i][1]); + }); + return false; + } + }); + return c; + }, + startsWithAnyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + + if (!set.every(function (s) { + return typeof s === 'string'; + })) { + return fail(this, "startsWithAnyOf() only works with strings"); + } + if (set.length === 0) return emptyCollection(this); + + return this.inAnyRange(set.map(function (str) { + return [str, str + maxString]; + })); + } + }; + }); + + // + // + // + // Collection Class + // + // + // + function Collection(whereClause, keyRangeGenerator) { + /// + /// + /// + /// Where clause instance + /// + var keyRange = null, + error = null; + if (keyRangeGenerator) try { + keyRange = keyRangeGenerator(); + } catch (ex) { + error = ex; + } + + var whereCtx = whereClause._ctx, + table = whereCtx.table; + this._ctx = { + table: table, + index: whereCtx.index, + isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name, + range: keyRange, + keysOnly: false, + dir: "next", + unique: "", + algorithm: null, + filter: null, + replayFilter: null, + justLimit: true, // True if a replayFilter is just a filter that performs a "limit" operation (or none at all) + isMatch: null, + offset: 0, + limit: Infinity, + error: error, // If set, any promise must be rejected with this error + or: whereCtx.or, + valueMapper: table.hook.reading.fire + }; + } + + function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); + } + + props(Collection.prototype, function () { + + // + // Collection Private Functions + // + + function addFilter(ctx, fn) { + ctx.filter = combine(ctx.filter, fn); + } + + function addReplayFilter(ctx, factory, isLimitFilter) { + var curr = ctx.replayFilter; + ctx.replayFilter = curr ? function () { + return combine(curr(), factory()); + } : factory; + ctx.justLimit = isLimitFilter && !curr; + } + + function addMatchFilter(ctx, fn) { + ctx.isMatch = combine(ctx.isMatch, fn); + } + + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string + * } + * @param store IDBObjectStore + **/ + function getIndexOrStore(ctx, store) { + if (ctx.isPrimKey) return store; + var indexSpec = ctx.table.schema.idxByName[ctx.index]; + if (!indexSpec) throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed"); + return store.index(indexSpec.name); + } + + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string, + * keysOnly: boolean, + * range?: IDBKeyRange, + * dir: "next" | "prev" + * } + */ + function openCursor(ctx, store) { + var idxOrStore = getIndexOrStore(ctx, store); + return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique); + } + + function iter(ctx, fn, resolve, reject, idbstore) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper); + } else (function () { + var set = {}; + var resolved = 0; + + function resolveboth() { + if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion. + } + + function union(item, cursor, advance) { + if (!filter || filter(cursor, advance, resolveboth, reject)) { + var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string + if (!hasOwn(set, key)) { + set[key] = true; + fn(item, cursor, advance); + } + } + } + + ctx.or._iterate(union, resolveboth, reject, idbstore); + iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper); + })(); + } + function getInstanceTemplate(ctx) { + return ctx.table.schema.instanceTemplate; + } + + return { + + // + // Collection Protected Functions + // + + _read: function (fn, cb) { + var ctx = this._ctx; + if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { + reject(ctx.error); + });else return ctx.table._idbstore(READONLY, fn).then(cb); + }, + _write: function (fn) { + var ctx = this._ctx; + if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { + reject(ctx.error); + });else return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued. + }, + _addAlgorithm: function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }, + + _iterate: function (fn, resolve, reject, idbstore) { + return iter(this._ctx, fn, resolve, reject, idbstore); + }, + + clone: function (props$$1) { + var rv = Object.create(this.constructor.prototype), + ctx = Object.create(this._ctx); + if (props$$1) extend(ctx, props$$1); + rv._ctx = ctx; + return rv; + }, + + raw: function () { + this._ctx.valueMapper = null; + return this; + }, + + // + // Collection Public methods + // + + each: function (fn) { + var ctx = this._ctx; + + if (fake) { + var item = getInstanceTemplate(ctx), + primKeyPath = ctx.table.schema.primKey.keyPath, + key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath), + primaryKey = getByKeyPath(item, primKeyPath); + fn(item, { key: key, primaryKey: primaryKey }); + } + + return this._read(function (resolve, reject, idbstore) { + iter(ctx, fn, resolve, reject, idbstore); + }); + }, + + count: function (cb) { + if (fake) return Promise.resolve(0).then(cb); + var ctx = this._ctx; + + if (isPlainKeyRange(ctx, true)) { + // This is a plain key range. We can use the count() method if the index. + return this._read(function (resolve, reject, idbstore) { + var idx = getIndexOrStore(ctx, idbstore); + var req = ctx.range ? idx.count(ctx.range) : idx.count(); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function (e) { + resolve(Math.min(e.target.result, ctx.limit)); + }; + }, cb); + } else { + // Algorithms, filters or expressions are applied. Need to count manually. + var count = 0; + return this._read(function (resolve, reject, idbstore) { + iter(ctx, function () { + ++count;return false; + }, function () { + resolve(count); + }, reject, idbstore); + }, cb); + } + }, + + sortBy: function (keyPath, cb) { + /// + var parts = keyPath.split('.').reverse(), + lastPart = parts[0], + lastIndex = parts.length - 1; + function getval(obj, i) { + if (i) return getval(obj[parts[i]], i - 1); + return obj[lastPart]; + } + var order = this._ctx.dir === "next" ? 1 : -1; + + function sorter(a, b) { + var aVal = getval(a, lastIndex), + bVal = getval(b, lastIndex); + return aVal < bVal ? -order : aVal > bVal ? order : 0; + } + return this.toArray(function (a) { + return a.sort(sorter); + }).then(cb); + }, + + toArray: function (cb) { + var ctx = this._ctx; + return this._read(function (resolve, reject, idbstore) { + fake && resolve([getInstanceTemplate(ctx)]); + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAll() or + // IDBKeyRange.getAll(): + var readingHook = ctx.table.hook.reading.fire; + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(function (res) { + try { + resolve(res.map(readingHook)); + } catch (e) { + reject(e); + } + })); + } else { + // Getting array through a cursor. + var a = []; + iter(ctx, function (item) { + a.push(item); + }, function arrayComplete() { + resolve(a); + }, reject, idbstore); + } + }, cb); + }, + + offset: function (offset) { + var ctx = this._ctx; + if (offset <= 0) return this; + ctx.offset += offset; // For count() + if (isPlainKeyRange(ctx)) { + addReplayFilter(ctx, function () { + var offsetLeft = offset; + return function (cursor, advance) { + if (offsetLeft === 0) return true; + if (offsetLeft === 1) { + --offsetLeft;return false; + } + advance(function () { + cursor.advance(offsetLeft); + offsetLeft = 0; + }); + return false; + }; + }); + } else { + addReplayFilter(ctx, function () { + var offsetLeft = offset; + return function () { + return --offsetLeft < 0; + }; + }); + } + return this; + }, + + limit: function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count() + addReplayFilter(this._ctx, function () { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included + return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here. + }; + }, true); + return this; + }, + + until: function (filterFunction, bIncludeStopEntry) { + var ctx = this._ctx; + fake && filterFunction(getInstanceTemplate(ctx)); + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } else { + return true; + } + }); + return this; + }, + + first: function (cb) { + return this.limit(1).toArray(function (a) { + return a[0]; + }).then(cb); + }, + + last: function (cb) { + return this.reverse().first(cb); + }, + + filter: function (filterFunction) { + /// function(val){return true/false} + fake && filterFunction(getInstanceTemplate(this._ctx)); + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + // match filters not used in Dexie.js but can be used by 3rd part libraries to test a + // collection for a match without querying DB. Used by Dexie.Observable. + addMatchFilter(this._ctx, filterFunction); + return this; + }, + + and: function (filterFunction) { + return this.filter(filterFunction); + }, + + or: function (indexName) { + return new WhereClause(this._ctx.table, indexName, this); + }, + + reverse: function () { + this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev"; + if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir); + return this; + }, + + desc: function () { + return this.reverse(); + }, + + eachKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { + cb(cursor.key, cursor); + }); + }, + + eachUniqueKey: function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }, + + eachPrimaryKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { + cb(cursor.primaryKey, cursor); + }); + }, + + keys: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.key); + }).then(function () { + return a; + }).then(cb); + }, + + primaryKeys: function (cb) { + var ctx = this._ctx; + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAllKeys() or + // IDBKeyRange.getAllKeys(): + return this._read(function (resolve, reject, idbstore) { + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = eventSuccessHandler(resolve); + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }, + + uniqueKeys: function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }, + + firstKey: function (cb) { + return this.limit(1).keys(function (a) { + return a[0]; + }).then(cb); + }, + + lastKey: function (cb) { + return this.reverse().firstKey(cb); + }, + + distinct: function () { + var ctx = this._ctx, + idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes. + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + } + }; + }); + + // + // + // WriteableCollection Class + // + // + function WriteableCollection() { + Collection.apply(this, arguments); + } + + derive(WriteableCollection).from(Collection).extend({ + + // + // WriteableCollection Public Methods + // + + modify: function (changes) { + var self = this, + ctx = this._ctx, + hook = ctx.table.hook, + updatingHook = hook.updating.fire, + deletingHook = hook.deleting.fire; + + fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate); + + return this._write(function (resolve, reject, idbstore, trans) { + var modifyer; + if (typeof changes === 'function') { + // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item) + if (updatingHook === nop && deletingHook === nop) { + // Noone cares about what is being changed. Just let the modifier function be the given argument as is. + modifyer = changes; + } else { + // People want to know exactly what is being modified or deleted. + // Let modifyer be a proxy function that finds out what changes the caller is actually doing + // and call the hooks accordingly! + modifyer = function (item) { + var origItem = deepClone(item); // Clone the item first so we can compare laters. + if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object) + if (!hasOwn(this, "value")) { + // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place. + deletingHook.call(this, this.primKey, item, trans); + } else { + // No deletion. Check what was changed + var objectDiff = getObjectDiff(origItem, this.value); + var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans); + if (additionalChanges) { + // Hook want to apply additional modifications. Make sure to fullfill the will of the hook. + item = this.value; + keys(additionalChanges).forEach(function (keyPath) { + setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + }); + } + } + }; + } + } else if (updatingHook === nop) { + // changes is a set of {keyPath: value} and no one is listening to the updating hook. + var keyPaths = keys(changes); + var numKeys = keyPaths.length; + modifyer = function (item) { + var anythingModified = false; + for (var i = 0; i < numKeys; ++i) { + var keyPath = keyPaths[i], + val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + anythingModified = true; + } + } + return anythingModified; + }; + } else { + // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and + // allow it to add additional modifications to make. + var origChanges = changes; + changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it. + modifyer = function (item) { + var anythingModified = false; + var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans); + if (additionalChanges) extend(changes, additionalChanges); + keys(changes).forEach(function (keyPath) { + var val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); + anythingModified = true; + } + }); + if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration + return anythingModified; + }; + } + + var count = 0; + var successCount = 0; + var iterationComplete = false; + var failures = []; + var failKeys = []; + var currentKey = null; + + function modifyItem(item, cursor) { + currentKey = cursor.primaryKey; + var thisContext = { + primKey: cursor.primaryKey, + value: item, + onsuccess: null, + onerror: null + }; + + function onerror(e) { + failures.push(e); + failKeys.push(thisContext.primKey); + checkFinished(); + return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction + } + + if (modifyer.call(thisContext, item, thisContext) !== false) { + // If a callback explicitely returns false, do not perform the update! + var bDelete = !hasOwn(thisContext, "value"); + ++count; + tryCatch(function () { + var req = bDelete ? cursor.delete() : cursor.update(thisContext.value); + req._hookCtx = thisContext; + req.onerror = hookedEventRejectHandler(onerror); + req.onsuccess = hookedEventSuccessHandler(function () { + ++successCount; + checkFinished(); + }); + }, onerror); + } else if (thisContext.onsuccess) { + // Hook will expect either onerror or onsuccess to always be called! + thisContext.onsuccess(thisContext.value); + } + } + + function doReject(e) { + if (e) { + failures.push(e); + failKeys.push(currentKey); + } + return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys)); + } + + function checkFinished() { + if (iterationComplete && successCount + failures.length === count) { + if (failures.length > 0) doReject();else resolve(successCount); + } + } + self.clone().raw()._iterate(modifyItem, function () { + iterationComplete = true; + checkFinished(); + }, doReject, idbstore); + }); + }, + + 'delete': function () { + var _this4 = this; + + var ctx = this._ctx, + range = ctx.range, + deletingHook = ctx.table.hook.deleting.fire, + hasDeleteHook = deletingHook !== nop; + if (!hasDeleteHook && isPlainKeyRange(ctx) && (ctx.isPrimKey && !hangsOnDeleteLargeKeyRange || !range)) // if no range, we'll use clear(). + { + // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208) + // For chromium, this is the way most optimized version. + // For IE/Edge, this could hang the indexedDB engine and make operating system instable + // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7) + return this._write(function (resolve, reject, idbstore) { + // Our API contract is to return a count of deleted items, so we have to count() before delete(). + var onerror = eventRejectHandler(reject), + countReq = range ? idbstore.count(range) : idbstore.count(); + countReq.onerror = onerror; + countReq.onsuccess = function () { + var count = countReq.result; + tryCatch(function () { + var delReq = range ? idbstore.delete(range) : idbstore.clear(); + delReq.onerror = onerror; + delReq.onsuccess = function () { + return resolve(count); + }; + }, function (err) { + return reject(err); + }); + }; + }); + } + + // Default version to use when collection is not a vanilla IDBKeyRange on the primary key. + // Divide into chunks to not starve RAM. + // If has delete hook, we will have to collect not just keys but also objects, so it will use + // more memory and need lower chunk size. + var CHUNKSIZE = hasDeleteHook ? 2000 : 10000; + + return this._write(function (resolve, reject, idbstore, trans) { + var totalCount = 0; + // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance. + var collection = _this4.clone({ + keysOnly: !ctx.isMatch && !hasDeleteHook }) // load just keys (unless filter() or and() or deleteHook has subscribers) + .distinct() // In case multiEntry is used, never delete same key twice because resulting count + // would become larger than actual delete count. + .limit(CHUNKSIZE).raw(); // Don't filter through reading-hooks (like mapped classes etc) + + var keysOrTuples = []; + + // We're gonna do things on as many chunks that are needed. + // Use recursion of nextChunk function: + var nextChunk = function () { + return collection.each(hasDeleteHook ? function (val, cursor) { + // Somebody subscribes to hook('deleting'). Collect all primary keys and their values, + // so that the hook can be called with its values in bulkDelete(). + keysOrTuples.push([cursor.primaryKey, cursor.value]); + } : function (val, cursor) { + // No one subscribes to hook('deleting'). Collect only primary keys: + keysOrTuples.push(cursor.primaryKey); + }).then(function () { + // Chromium deletes faster when doing it in sort order. + hasDeleteHook ? keysOrTuples.sort(function (a, b) { + return ascending(a[0], b[0]); + }) : keysOrTuples.sort(ascending); + return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook); + }).then(function () { + var count = keysOrTuples.length; + totalCount += count; + keysOrTuples = []; + return count < CHUNKSIZE ? totalCount : nextChunk(); + }); + }; + + resolve(nextChunk()); + }); + } + }); + + // + // + // + // ------------------------- Help functions --------------------------- + // + // + // + + function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; + } + + function setApiOnPlace(objs, tableNames, mode, dbschema) { + tableNames.forEach(function (tableName) { + var tableInstance = db._tableFactory(mode, dbschema[tableName]); + objs.forEach(function (obj) { + tableName in obj || (obj[tableName] = tableInstance); + }); + }); + } + + function removeTablesApi(objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof Table) delete obj[key]; + } + }); + } + + function iterate(req, filter, fn, resolve, reject, valueMapper) { + + // Apply valueMapper (hook('reading') or mappped class) + var mappedFn = valueMapper ? function (x, c, a) { + return fn(valueMapper(x), c, a); + } : fn; + // Wrap fn with PSD and microtick stuff from Promise. + var wrappedFn = wrap(mappedFn, reject); + + if (!req.onerror) req.onerror = eventRejectHandler(reject); + if (filter) { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { + cursor.continue(); + }; + if (filter(cursor, function (advancer) { + c = advancer; + }, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) { + c = advancer; + }); + c(); + } else { + resolve(); + } + }, reject); + } else { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { + cursor.continue(); + }; + wrappedFn(cursor.value, cursor, function (advancer) { + c = advancer; + }); + c(); + } else { + resolve(); + } + }, reject); + } + } + + function parseIndexSyntax(indexes) { + /// + /// + var rv = []; + indexes.split(',').forEach(function (index) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*" + // Let keyPath of "[a+b]" be ["a","b"]: + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + + rv.push(new IndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index))); + }); + return rv; + } + + function cmp(key1, key2) { + return indexedDB.cmp(key1, key2); + } + + function min(a, b) { + return cmp(a, b) < 0 ? a : b; + } + + function max(a, b) { + return cmp(a, b) > 0 ? a : b; + } + + function ascending(a, b) { + return indexedDB.cmp(a, b); + } + + function descending(a, b) { + return indexedDB.cmp(b, a); + } + + function simpleCompare(a, b) { + return a < b ? -1 : a === b ? 0 : 1; + } + + function simpleCompareReverse(a, b) { + return a > b ? -1 : a === b ? 0 : 1; + } + + function combine(filter1, filter2) { + return filter1 ? filter2 ? function () { + return filter1.apply(this, arguments) && filter2.apply(this, arguments); + } : filter1 : filter2; + } + + function readGlobalSchema() { + db.verno = idbdb.version / 10; + db._dbSchema = globalSchema = {}; + dbStoreNames = slice(idbdb.objectStoreNames, 0); + if (dbStoreNames.length === 0) return; // Database contains no stores. + var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly'); + dbStoreNames.forEach(function (storeName) { + var store = trans.objectStore(storeName), + keyPath = store.keyPath, + dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted); + indexes.push(index); + } + globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {}); + }); + setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema); + } + + function adjustToExistingIndexNames(schema, idbtrans) { + /// + /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db + /// + /// Map between name and TableSchema + /// + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + hasGetAll = 'getAll' in store; + for (var j = 0; j < store.indexNames.length; ++j) { + var indexName = store.indexNames[j]; + var keyPath = store.index(indexName).keyPath; + var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; + if (schema[storeName]) { + var indexSpec = schema[storeName].idxByName[dexieName]; + if (indexSpec) indexSpec.name = indexName; + } + } + } + } + + function fireOnBlocked(ev) { + db.on("blocked").fire(ev); + // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: + connections.filter(function (c) { + return c.name === db.name && c !== db && !c._vcFired; + }).map(function (c) { + return c.on("versionchange").fire(ev); + }); + } + + extend(this, { + Collection: Collection, + Table: Table, + Transaction: Transaction, + Version: Version, + WhereClause: WhereClause, + WriteableCollection: WriteableCollection, + WriteableTable: WriteableTable + }); + + init(); + + addons.forEach(function (fn) { + fn(db); + }); +} + +var fakeAutoComplete = function () {}; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) +var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) + +function parseType(type) { + if (typeof type === 'function') { + return new type(); + } else if (isArray(type)) { + return [parseType(type[0])]; + } else if (type && typeof type === 'object') { + var rv = {}; + applyStructure(rv, type); + return rv; + } else { + return type; + } +} + +function applyStructure(obj, structure) { + keys(structure).forEach(function (member) { + var value = parseType(structure[member]); + obj[member] = value; + }); + return obj; +} + +function eventSuccessHandler(done) { + return function (ev) { + done(ev.target.result); + }; +} + +function hookedEventSuccessHandler(resolve) { + // wrap() is needed when calling hooks because the rare scenario of: + // * hook does a db operation that fails immediately (IDB throws exception) + // For calling db operations on correct transaction, wrap makes sure to set PSD correctly. + // wrap() will also execute in a virtual tick. + // * If not wrapped in a virtual tick, direct exception will launch a new physical tick. + // * If this was the last event in the bulk, the promise will resolve after a physical tick + // and the transaction will have committed already. + // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise, + // because it is always marked with _lib = true when created using Transaction._promise(). + return wrap(function (event) { + var req = event.target, + result = req.result, + ctx = req._hookCtx, + // Contains the hook error handler. Put here instead of closure to boost performance. + hookSuccessHandler = ctx && ctx.onsuccess; + hookSuccessHandler && hookSuccessHandler(result); + resolve && resolve(result); + }, resolve); +} + +function eventRejectHandler(reject) { + return function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }; +} + +function hookedEventRejectHandler(reject) { + return wrap(function (event) { + // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks. + + var req = event.target, + err = req.error, + ctx = req._hookCtx, + // Contains the hook error handler. Put here instead of closure to boost performance. + hookErrorHandler = ctx && ctx.onerror; + hookErrorHandler && hookErrorHandler(err); + preventDefault(event); + reject(err); + return false; + }); +} + +function preventDefault(event) { + if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below. + event.stopPropagation(); + if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below. + event.preventDefault(); +} + +function globalDatabaseList(cb) { + var val, + localStorage = Dexie.dependencies.localStorage; + if (!localStorage) return cb([]); // Envs without localStorage support + try { + val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]"); + } catch (e) { + val = []; + } + if (cb(val)) { + localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val)); + } +} + +function awaitIterator(iterator) { + var callNext = function (result) { + return iterator.next(result); + }, + doThrow = function (error) { + return iterator.throw(error); + }, + onSuccess = step(callNext), + onError = step(doThrow); + + function step(getNext) { + return function (val) { + var next = getNext(val), + value = next.value; + + return next.done ? value : !value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError); + }; + } + + return step(callNext)(); +} + +// +// IndexSpec struct +// +function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) { + /// + /// + /// + /// + /// + /// + /// + this.name = name; + this.keyPath = keyPath; + this.unique = unique; + this.multi = multi; + this.auto = auto; + this.compound = compound; + this.dotted = dotted; + var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && '[' + [].join.call(keyPath, '+') + ']'; + this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc; +} + +// +// TableSchema struct +// +function TableSchema(name, primKey, indexes, instanceTemplate) { + /// + /// + /// + /// + this.name = name; + this.primKey = primKey || new IndexSpec(); + this.indexes = indexes || [new IndexSpec()]; + this.instanceTemplate = instanceTemplate; + this.mappedClass = null; + this.idxByName = arrayToObject(indexes, function (index) { + return [index.name, index]; + }); +} + +// Used in when defining dependencies later... +// (If IndexedDBShim is loaded, prefer it before standard indexedDB) +var idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {}; + +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} + +function getNativeGetDatabaseNamesFn(indexedDB) { + var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames); + return fn && fn.bind(indexedDB); +} + +// Export Error classes +props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...}; + +// +// Static methods and properties +// +props(Dexie, { + + // + // Static delete() method. + // + delete: function (databaseName) { + var db = new Dexie(databaseName), + promise = db.delete(); + promise.onblocked = function (fn) { + db.on("blocked", fn); + return this; + }; + return promise; + }, + + // + // Static exists() method. + // + exists: function (name) { + return new Dexie(name).open().then(function (db) { + db.close(); + return true; + }).catch(Dexie.NoSuchDatabaseError, function () { + return false; + }); + }, + + // + // Static method for retrieving a list of all existing databases at current host. + // + getDatabaseNames: function (cb) { + return new Promise(function (resolve, reject) { + var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB); + if (getDatabaseNames) { + // In case getDatabaseNames() becomes standard, let's prepare to support it: + var req = getDatabaseNames(); + req.onsuccess = function (event) { + resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array + }; + req.onerror = eventRejectHandler(reject); + } else { + globalDatabaseList(function (val) { + resolve(val); + return false; + }); + } + }).then(cb); + }, + + defineClass: function (structure) { + /// + /// Create a javascript constructor based on given template for which properties to expect in the class. + /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + + // Default constructor able to copy given properties into this object. + function Class(properties) { + /// Properties to initialize object with. + /// + properties ? extend(this, properties) : fake && applyStructure(this, structure); + } + return Class; + }, + + applyStructure: applyStructure, + + ignoreTransaction: function (scopeFunc) { + // In case caller is within a transaction but needs to create a separate transaction. + // Example of usage: + // + // Let's say we have a logger function in our app. Other application-logic should be unaware of the + // logger function and not need to include the 'logentries' table in all transaction it performs. + // The logging should always be done in a separate transaction and not be dependant on the current + // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction. + // + // Dexie.ignoreTransaction(function() { + // db.logentries.add(newLogEntry); + // }); + // + // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction + // in current Promise-scope. + // + // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an + // API for this because + // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout(). + // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate(). + // 3) setImmediate() is not supported in the ES standard. + // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough. + return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional. + scopeFunc(); // No need to change scope because there is no ongoing transaction. + }, + + vip: function (fn) { + // To be used by subscribers to the on('ready') event. + // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing. + // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD + // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since + // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that. + // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip() + // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by + // the caller will not resolve until database is opened. + return newScope(function () { + PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing. + return fn(); + }); + }, + + async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); + return rv; + } catch (e) { + return rejection(e); + } + }; + }, + + spawn: function (generatorFn, args, thiz) { + try { + var rv = awaitIterator(generatorFn.apply(thiz, args || [])); + if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); + return rv; + } catch (e) { + return rejection(e); + } + }, + + // Dexie.currentTransaction property + currentTransaction: { + get: function () { + return PSD.trans || null; + } + }, + + // Export our Promise implementation since it can be handy as a standalone Promise implementation + Promise: Promise, + + // Dexie.debug proptery: + // Dexie.debug = false + // Dexie.debug = true + // Dexie.debug = "dexie" - don't hide dexie's stack frames. + debug: { + get: function () { + return debug; + }, + set: function (value) { + setDebug(value, value === 'dexie' ? function () { + return true; + } : dexieStackFrameFilter); + } + }, + + // Export our derive/extend/override methodology + derive: derive, + extend: extend, + props: props, + override: override, + // Export our Events() function - can be handy as a toolkit + Events: Events, + events: { get: deprecated(function () { + return Events; + }) }, // Backward compatible lowercase version. + // Utilities + getByKeyPath: getByKeyPath, + setByKeyPath: setByKeyPath, + delByKeyPath: delByKeyPath, + shallowClone: shallowClone, + deepClone: deepClone, + getObjectDiff: getObjectDiff, + asap: asap, + maxKey: maxKey, + // Addon registry + addons: [], + // Global DB connection list + connections: connections, + + MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate. + errnames: errnames, + + // Export other static classes + IndexSpec: IndexSpec, + TableSchema: TableSchema, + + // + // Dependencies + // + // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included. + // + // In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). + // For node.js, you need to require indexeddb-js or similar and then set these deps. + // + dependencies: { + // Required: + indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange + }, + + // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc. + semVer: DEXIE_VERSION, + version: DEXIE_VERSION.split('.').map(function (n) { + return parseInt(n); + }).reduce(function (p, c, i) { + return p + c / Math.pow(10, i * 2); + }), + fakeAutoComplete: fakeAutoComplete, + + // https://github.com/dfahlander/Dexie.js/issues/186 + // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return + // x.default. Workaround: Set Dexie.default = Dexie. + default: Dexie +}); + +tryCatch(function () { + // Optional dependencies + // localStorage + Dexie.dependencies.localStorage = (typeof chrome !== "undefined" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage; +}); + +// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0. +Promise.rejectionMapper = mapError; + +// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015. +doFakeAutoComplete(function () { + Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete; + Dexie.fake = fake = true; +}); + +return Dexie; + +}))); +//# sourceMappingURL=dexie.js.map diff --git a/dist/dexie.js.map b/dist/dexie.js.map new file mode 100644 index 000000000..ac9e04e8d --- /dev/null +++ b/dist/dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.js","sources":["../tools/tmp/src/utils.js","../tools/tmp/src/chaining-functions.js","../tools/tmp/src/debug.js","../tools/tmp/src/errors.js","../tools/tmp/src/Events.js","../tools/tmp/src/Promise.js","../tools/tmp/src/promise-utils.js","../tools/tmp/src/Dexie.js"],"sourcesContent":["/*\r\n* Dexie.js - a minimalistic wrapper for IndexedDB\r\n* ===============================================\r\n*\r\n* By David Fahlander, david.fahlander@gmail.com\r\n*\r\n* Version {version}, {date}\r\n* www.dexie.com\r\n* Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n*/\nexport var keys = Object.keys;\nexport var isArray = Array.isArray;\nexport var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;\n\nexport function extend(obj, extension) {\n if (typeof extension !== 'object') return obj;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj;\n}\n\nexport var getProto = Object.getPrototypeOf;\nexport var _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props(proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n keys(extension).forEach(function (key) {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport function setProp(obj, prop, functionOrGetSet, options) {\n Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n var pd = getOwnPropertyDescriptor(obj, prop),\n proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);\n}\n\nvar _slice = [].slice;\nexport function slice(args, start, end) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function doFakeAutoComplete(fn) {\n var to = setTimeout(fn, 1000);\n clearTimeout(to);\n}\n\nexport function assert(b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n if (_global.setImmediate) setImmediate(fn);else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter(function (value, index, self) {\n return self.indexOf(value) === index;\n });\n}\n\n/** Generate an object (hash map) based on given array.\r\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\r\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\r\n * current item wont affect the resulting object.\r\n */\nexport function arrayToObject(array, extractor) {\n return array.reduce(function (result, item, i) {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn, onerror, args) {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\") {\n if (value === undefined) delete obj[currentKeyPath];else obj[currentKeyPath] = value;\n } else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj) innerObj = obj[currentKeyPath] = {};\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) delete obj[keyPath];else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);else if ('length' in keyPath) [].map.call(keyPath, function (kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nexport function deepClone(any) {\n if (!any || typeof any !== 'object') return any;\n var rv;\n if (isArray(any)) {\n rv = [];\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(deepClone(any[i]));\n }\n } else if (any instanceof Date) {\n rv = new Date();\n rv.setTime(any.getTime());\n } else {\n rv = any.constructor ? Object.create(any.constructor.prototype) : {};\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = deepClone(any[prop]);\n }\n }\n }\n return rv;\n}\n\nexport function getObjectDiff(a, b, rv, prfx) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach(function (prop) {\n if (!hasOwn(b, prop)) rv[prfx + prop] = undefined; // Property removed\n else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp && ap.constructor === bp.constructor)\n // Same type of object but its properties may have changed\n getObjectDiff(ap, bp, rv, prfx + prop + \".\");else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed\n }\n });\n keys(b).forEach(function (prop) {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\nexport var getIteratorOf = iteratorSymbol ? function (x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () {\n return null;\n};\n\nexport var NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf(arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if (it = getIteratorOf(arrayLike)) {\n a = [];\n while (x = it.next(), !x.done) {\n a.push(x.value);\n }return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) {\n a[i] = arrayLike[i];\n }return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) {\n a[i] = arguments[i];\n }return a;\n}\n\nvar concat = [].concat;\nexport function flatten(a) {\n return concat.apply([], a);\n}","import { extend } from './utils';\n\nexport function nop() {}\nexport function mirror(val) {\n return val;\n}\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess,\n // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess,\n // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess,\n // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ? res2 === undefined ? undefined : res2 : extend(res, res2);\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) {\n args[i] = arguments[i];\n }return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n// By default, use debug mode if served from localhost.\n/^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\n\nexport var libraryFilter = function () {\n return true;\n};\n\nexport var NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\n\n if (NEEDS_THROW_FOR_STACK) try {\n // Doing something naughty in strict mode here to trigger a specific error\n // that can be explicitely ignored in debugger's exception settings.\n // If we'd just throw new Error() here, IE's debugger's exception settings\n // will just consider it as \"exception thrown by javascript code\" which is\n // something you wouldn't want it to ignore.\n getErrorWithStack.arguments;\n throw new Error(); // Fallback if above line don't throw.\n } catch (e) {\n return e;\n }\n return new Error();\n}\n\nexport function prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack) return \"\";\n numIgnoredFrames = numIgnoredFrames || 0;\n if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) {\n return \"\\n\" + frame;\n }).join('');\n}\n\nexport function deprecated(what, fn) {\n return function () {\n console.warn(what + \" is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. \" + prettyStack(getErrorWithStack(), 1));\n return fn.apply(this, arguments);\n };\n}","import { derive, setProp } from './utils';\nimport { getErrorWithStack, prettyStack } from './debug';\n\nvar dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise'];\n\nvar idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone'];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError(name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n stack: {\n get: function () {\n return this._stack || (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function () {\n return this.name + \": \" + this.message;\n }\n});\n\nfunction getMultiErrorMessage(msg, failures) {\n return msg + \". Errors: \" + failures.map(function (f) {\n return f.toString();\n }).filter(function (v, i, s) {\n return s.indexOf(v) === i;\n }) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in WriteableCollection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError(msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError(msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = failures;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce(function (obj, name) {\n return obj[name] = name + \"Error\", obj;\n}, {});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nvar BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce(function (obj, name) {\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError(msgOrInner, inner) {\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = msgOrInner;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = msgOrInner.name + ' ' + msgOrInner.message;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name] = DexieError;\n return obj;\n}, {});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce(function (obj, name) {\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError(domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", { get: function () {\n return this.inner.stack;\n } });\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce(function (obj, name) {\n if ([\"Syntax\", \"Type\", \"Range\"].indexOf(name) === -1) obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;","import { keys, isArray, asap } from './utils';\nimport { nop, mirror, reverseStoppableEventChain } from './chaining-functions';\nimport { exceptions } from './errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length,\n args = new Array(i - 1);\n while (--i) {\n args[i - 1] = arguments[i];\n }evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof eventName === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n\n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n\n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) {\n return fn !== cb;\n });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length,\n args = new Array(i);\n while (i--) {\n args[i] = arguments[i];\n } // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}","import { doFakeAutoComplete, tryCatch, props, setProp, _global, getPropertyDescriptor, getArrayOf, extend } from './utils';\nimport { reverseStoppableEventChain, nop, callBoth, mirror } from './chaining-functions';\nimport Events from './Events';\nimport { debug, prettyStack, getErrorWithStack, deprecated } from './debug';\n\n//\n// Promise Class for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// Modifications needed to be done to support indexedDB because it wont accept setTimeout()\n// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) .\n// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45\n//\n// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since\n// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick\n// engine that is used instead of setImmediate() or setTimeout().\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Async static context support (Promise.PSD)\n// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nvar LONG_STACKS_CLIP_LIMIT = 100,\n\n// When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \nMAX_LONG_STACKS = 20,\n stack_being_generated = false;\n\n/* The default \"nextTick\" function used only for the very first promise in a promise chain.\r\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\r\n emulated in this module. For indexedDB compatibility, this means that every method needs to \r\n execute at least one promise before doing an indexedDB operation. Dexie will always call \r\n db.ready().then() for every operation to make sure the indexedDB event is started in an\r\n emulated micro tick.\r\n*/\nvar schedulePhysicalTick = _global.setImmediate ?\n// setImmediate supported. Those modern platforms also supports Function.bind().\nsetImmediate.bind(null, physicalTick) : _global.MutationObserver ?\n// MutationObserver supported\nfunction () {\n var hiddenDiv = document.createElement(\"div\");\n new MutationObserver(function () {\n physicalTick();\n hiddenDiv = null;\n }).observe(hiddenDiv, { attributes: true });\n hiddenDiv.setAttribute('i', '1');\n} :\n// No support for setImmediate or MutationObserver. No worry, setTimeout is only called\n// once time. Every tick that follows will be our emulated micro tick.\n// Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug \nfunction () {\n setTimeout(physicalTick, 0);\n};\n\n// Confifurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler (myFuncThatThrows exception)!\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true,\n // True when NOT in a virtual microTick.\nneedsNewPhysicalTick = true,\n // True when a push to microtickQueue must also schedulePhysicalTick()\nunhandledErrors = [],\n // Rejected promises that has occured. Used for firing unhandledrejection.\nrejectingErrors = [],\n // Tracks if errors are being re-rejected during onRejected callback.\ncurrentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n\nexport var globalPSD = {\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n //env: null, // Will be set whenever leaving a scope using wrappers.snapshot()\n finalize: function () {\n this.unhandleds.forEach(function (uh) {\n try {\n globalError(uh[0], uh[1]);\n } catch (e) {}\n });\n }\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\n// Wrappers are not being used yet. Their framework is functioning and can be used\n// to replace environment during a PSD scope (a.k.a. 'zone').\n/* **KEEP** export var wrappers = (() => {\r\n var wrappers = [];\r\n\r\n return {\r\n snapshot: () => {\r\n var i = wrappers.length,\r\n result = new Array(i);\r\n while (i--) result[i] = wrappers[i].snapshot();\r\n return result;\r\n },\r\n restore: values => {\r\n var i = wrappers.length;\r\n while (i--) wrappers[i].restore(values[i]);\r\n },\r\n wrap: () => wrappers.map(w => w.wrap()),\r\n add: wrapper => {\r\n wrappers.push(wrapper);\r\n }\r\n };\r\n})();\r\n*/\n\nexport default function Promise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');\n this._listeners = [];\n this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.\n\n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = this._PSD = PSD;\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n linkToPreviousPromise(this, currentFulfiller);\n }\n\n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n\n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\nprops(Promise.prototype, {\n\n then: function (onFulfilled, onRejected) {\n var _this = this;\n\n var rv = new Promise(function (resolve, reject) {\n propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject));\n });\n debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this);\n return rv;\n },\n\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected));\n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, function (err) {\n return (\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err)\n );\n }) : this.then(null, function (err) {\n return (\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err)\n );\n });\n },\n\n finally: function (onFinally) {\n return this.then(function (value) {\n onFinally();\n return value;\n }, function (err) {\n onFinally();\n return PromiseReject(err);\n });\n },\n\n // Deprecate in next major. Needed only for db.on.error.\n uncaught: function (uncaughtHandler) {\n var _this2 = this;\n\n // Be backward compatible and use \"onuncatched\" as the event name on this.\n // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops.\n this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler);\n // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not\n // a previous promise. Reason: the prevous promise may lack onuncatched handler. \n if (this._state === false && unhandledErrors.indexOf(this) === -1) {\n // Replace unhandled error's destinaion promise with this one!\n unhandledErrors.some(function (p, i, l) {\n return p._value === _this2._value && (l[i] = _this2);\n });\n // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could\n // take away this piece of code as well as the onuncatched and uncaught() method.\n }\n return this;\n },\n\n stack: {\n get: function () {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack(this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n }\n});\n\nfunction Listener(onFulfilled, onRejected, resolve, reject) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = PSD;\n}\n\n// Promise Static Properties\nprops(Promise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like.\n return new Promise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach(function (a, i) {\n return Promise.resolve(a).then(function (x) {\n values[i] = x;\n if (! --remaining) resolve(values);\n }, reject);\n });\n });\n },\n\n resolve: function (value) {\n if (value instanceof Promise) return value;\n if (value && typeof value.then === 'function') return new Promise(function (resolve, reject) {\n value.then(resolve, reject);\n });\n return new Promise(INTERNAL, true, value);\n },\n\n reject: PromiseReject,\n\n race: function () {\n var values = getArrayOf.apply(null, arguments);\n return new Promise(function (resolve, reject) {\n values.map(function (value) {\n return Promise.resolve(value).then(resolve, reject);\n });\n });\n },\n\n PSD: {\n get: function () {\n return PSD;\n },\n set: function (value) {\n return PSD = value;\n }\n },\n\n newPSD: newScope,\n\n usePSD: usePSD,\n\n scheduler: {\n get: function () {\n return asap;\n },\n set: function (value) {\n asap = value;\n }\n },\n\n rejectionMapper: {\n get: function () {\n return rejectionMapper;\n },\n set: function (value) {\n rejectionMapper = value;\n } // Map reject failures\n },\n\n follow: function (fn) {\n return new Promise(function (resolve, reject) {\n return newScope(function (resolve, reject) {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n var _this3 = this;\n\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(function () {\n _this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, resolve, reject);\n });\n },\n\n on: Events(null, { \"error\": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler\n })\n\n});\n\nvar PromiseOnError = Promise.on.error;\nPromiseOnError.subscribe = deprecated(\"Promise.on('error')\", PromiseOnError.subscribe);\nPromiseOnError.unsubscribe = deprecated(\"Promise.on('error').unsubscribe\", PromiseOnError.unsubscribe);\n\n/**\r\n* Take a potentially misbehaving resolver function and make sure\r\n* onFulfilled and onRejected are only called once.\r\n*\r\n* Makes no guarantees about asynchrony.\r\n*/\nfunction executePromiseTask(promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(function (value) {\n if (promise._state !== null) return;\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, function (resolve, reject) {\n value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection(promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () {\n var origProp = getPropertyDescriptor(reason, \"stack\");\n reason._promise = promise;\n setProp(reason, \"stack\", {\n get: function () {\n return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack;\n }\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners(promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(function () {\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject)(promise._value);\n }\n var psd = listener.psd;\n ++psd.ref;\n ++numScheduledCalls;\n asap(callListener, [cb, promise, listener]);\n}\n\nfunction callListener(cb, promise, listener) {\n var outerScope = PSD;\n var psd = listener.psd;\n try {\n if (psd !== outerScope) {\n // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment.\n PSD = psd;\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\n }\n\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n\n // Call callback and resolve our listener with it's return value.\n var value = promise._value,\n ret;\n if (promise._state) {\n ret = cb(value);\n } else {\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore PSD, env and currentFulfiller.\n if (psd !== outerScope) {\n PSD = outerScope;\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment\n }\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --psd.ref || psd.finalize();\n }\n}\n\nfunction getStack(promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n\n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) {\n // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with setImmediate() or setTimeout().\r\n It runs a virtual microtick and executes any callback registered in microtickQueue.\r\n */\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\n\nfunction beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\r\n This can be possible because we only use this internally and\r\n the registered functions are exception-safe (they do try..catch\r\n internally before calling any external method). If registering\r\n functions in the microtickQueue that are not exception-safe, this\r\n would destroy the framework and make it instable. So we don't export\r\n our asap method.\r\n*/\nfunction endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(function (p) {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) {\n finalizers[--i]();\n }\n}\n\nfunction run_at_end_of_this_or_next_physical_tick(fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(function () {\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(function (p) {\n return p._value === promise._value;\n })) unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) {\n if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n }\n}\n\n// By default, log uncaught errors to the console\nfunction defaultErrorHandler(e) {\n console.warn('Unhandled rejection: ' + (e.stack || e));\n}\n\nfunction PromiseReject(reason) {\n return new Promise(INTERNAL, false, reason);\n}\n\nexport function wrap(fn, errorCatcher) {\n var psd = PSD;\n return function () {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n if (outerScope !== psd) {\n // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment\n PSD = psd;\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\n }\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n if (outerScope !== psd) {\n PSD = outerScope;\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment\n }\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\nexport function newScope(fn, a1, a2, a3) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n // **KEEP** psd.env = wrappers.wrap(psd);\n\n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n };\n var rv = usePSD(psd, fn, a1, a2, a3);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\nexport function usePSD(psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n if (psd !== outerScope) {\n // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment.\n PSD = psd;\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\n }\n return fn(a1, a2, a3);\n } finally {\n if (psd !== outerScope) {\n PSD = outerScope;\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment.\n }\n }\n}\n\nvar UNHANDLEDREJECTION = \"unhandledrejection\";\n\nfunction globalError(err, promise) {\n var rv;\n try {\n rv = promise.onuncatched(err);\n } catch (e) {}\n if (rv !== false) try {\n var event,\n eventData = { promise: promise, reason: err };\n if (_global.document && document.createEvent) {\n event = document.createEvent('Event');\n event.initEvent(UNHANDLEDREJECTION, true, true);\n extend(event, eventData);\n } else if (_global.CustomEvent) {\n event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData });\n extend(event, eventData);\n }\n if (event && _global.dispatchEvent) {\n dispatchEvent(event);\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\n // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.\n try {\n _global.onunhandledrejection(event);\n } catch (_) {}\n }\n if (!event.defaultPrevented) {\n // Backward compatibility: fire to events registered at Promise.on.error\n Promise.on.error.fire(err, promise);\n }\n } catch (e) {}\n}\n\n/* **KEEP** \r\n\r\nexport function wrapPromise(PromiseClass) {\r\n var proto = PromiseClass.prototype;\r\n var origThen = proto.then;\r\n \r\n wrappers.add({\r\n snapshot: () => proto.then,\r\n restore: value => {proto.then = value;},\r\n wrap: () => patchedThen\r\n });\r\n\r\n function patchedThen (onFulfilled, onRejected) {\r\n var promise = this;\r\n var onFulfilledProxy = wrap(function(value){\r\n var rv = value;\r\n if (onFulfilled) {\r\n rv = onFulfilled(rv);\r\n if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.\r\n }\r\n --PSD.ref || PSD.finalize();\r\n return rv;\r\n });\r\n var onRejectedProxy = wrap(function(err){\r\n promise._$err = err;\r\n var unhandleds = PSD.unhandleds;\r\n var idx = unhandleds.length,\r\n rv;\r\n while (idx--) if (unhandleds[idx]._$err === err) break;\r\n if (onRejected) {\r\n if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled.\r\n rv = onRejected(err);\r\n if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.\r\n } else {\r\n if (idx === -1) unhandleds.push(promise);\r\n rv = PromiseClass.reject(err);\r\n rv._$nointercept = true; // Prohibit eternal loop.\r\n }\r\n --PSD.ref || PSD.finalize();\r\n return rv;\r\n });\r\n \r\n if (this._$nointercept) return origThen.apply(this, arguments);\r\n ++PSD.ref;\r\n return origThen.call(this, onFulfilledProxy, onRejectedProxy);\r\n }\r\n}\r\n\r\n// Global Promise wrapper\r\nif (_global.Promise) wrapPromise(_global.Promise);\r\n\r\n*/\n\ndoFakeAutoComplete(function () {\n // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie.\n asap = function (fn, args) {\n setTimeout(function () {\n fn.apply(null, args);\n }, 0);\n };\n});","import Promise from './Promise';\n\nexport function rejection(err, uncaughtHandler) {\n // Get the call stack and return a rejected promise.\n var rv = Promise.reject(err);\n return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv;\n}","/*\r\n * Dexie.js - a minimalistic wrapper for IndexedDB\r\n * ===============================================\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n */\n\nimport { keys, setProp, isArray, extend, props, derive, slice, override, _global, doFakeAutoComplete, asap, trycatcher, tryCatch, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, getObjectDiff, assert, NO_CHAR_ARRAY, getArrayOf, arrayToObject, hasOwn, flatten } from './utils';\nimport { rejection } from './promise-utils';\nimport { ModifyError, BulkError, errnames, exceptions, fullNameExceptions, mapError } from './errors';\nimport Promise, { wrap, PSD, newScope, usePSD } from './Promise';\nimport Events from './Events';\nimport { nop, mirror, pureFunctionChain, hookCreatingChain, hookUpdatingChain, hookDeletingChain, promisableChain } from './chaining-functions';\nimport * as Debug from './debug';\n\nvar DEXIE_VERSION = '{version}',\n maxString = String.fromCharCode(65535),\n\n// maxKey is an Array if indexedDB implementations supports array keys (not supported by IE,Edge or Safari at the moment)\n// Otherwise maxKey is maxString. This is handy when needing an open upper border without limit.\nmaxKey = function () {\n try {\n IDBKeyRange.only([[]]);return [[]];\n } catch (e) {\n return maxString;\n }\n}(),\n INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\",\n STRING_EXPECTED = \"String expected.\",\n connections = [],\n isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent),\n hasIEDeleteObjectStoreBug = isIEOrEdge,\n hangsOnDeleteLargeKeyRange = isIEOrEdge,\n dexieStackFrameFilter = function (frame) {\n return !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\n};\n\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport default function Dexie(dbName, options) {\n /// Specify only if you wich to control which addons that should run on this instance\n var deps = Dexie.dependencies;\n var opts = extend({\n // Default Options\n addons: Dexie.addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env.\n IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env.\n }, options);\n var addons = opts.addons,\n autoOpen = opts.autoOpen,\n indexedDB = opts.indexedDB,\n IDBKeyRange = opts.IDBKeyRange;\n\n var globalSchema = this._dbSchema = {};\n var versions = [];\n var dbStoreNames = [];\n var allTables = {};\n ///\n var idbdb = null; // Instance of IDBDatabase\n var dbOpenError = null;\n var isBeingOpened = false;\n var openComplete = false;\n var READONLY = \"readonly\",\n READWRITE = \"readwrite\";\n var db = this;\n var dbReadyResolve,\n dbReadyPromise = new Promise(function (resolve) {\n dbReadyResolve = resolve;\n }),\n cancelOpen,\n openCanceller = new Promise(function (_, reject) {\n cancelOpen = reject;\n });\n var autoSchema = true;\n var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),\n hasGetAll;\n\n function init() {\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n db.on(\"versionchange\", function (ev) {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0) console.warn('Another connection wants to upgrade database \\'' + db.name + '\\'. Closing db now to resume the upgrade.');else console.warn('Another connection wants to delete database \\'' + db.name + '\\'. Closing db now to resume the delete request.');\n db.close();\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n db.on(\"blocked\", function (ev) {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn('Dexie.delete(\\'' + db.name + '\\') was blocked');else console.warn('Upgrade \\'' + db.name + '\\' blocked by other connection holding version ' + ev.oldVersion / 10);\n });\n }\n\n //\n //\n //\n // ------------------------- Versioning Framework---------------------------\n //\n //\n //\n\n this.version = function (versionNumber) {\n /// \n /// \n if (idbdb || isBeingOpened) throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n var versionInstance = versions.filter(function (v) {\n return v._cfg.version === versionNumber;\n })[0];\n if (versionInstance) return versionInstance;\n versionInstance = new Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n return versionInstance;\n };\n\n function Version(versionNumber) {\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n this.stores({}); // Derive earlier schemas by default.\n }\n\n extend(Version.prototype, {\n stores: function (stores) {\n /// \n /// Defines the schema for a particular version\n /// \n /// \n /// Example:
\n /// {users: \"id++,first,last,&username,*email\",
\n /// passwords: \"id++,&username\"}
\n ///
\n /// Syntax: {Table: \"[primaryKey][++],[&][*]index1,[&][*]index2,...\"}

\n /// Special characters:
\n /// \"&\" means unique key,
\n /// \"*\" means value is multiEntry,
\n /// \"++\" means auto-increment and only applicable for primary key
\n /// \n this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n var storesSpec = {};\n versions.forEach(function (version) {\n // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n });\n\n var dbschema = this._cfg.dbschema = {};\n this._parseStoresSpec(storesSpec, dbschema);\n // Update the latest schema to this version\n // Update API\n globalSchema = db._dbSchema = dbschema;\n removeTablesApi([allTables, db, Transaction.prototype]);\n setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema);\n dbStoreNames = keys(dbschema);\n return this;\n },\n upgrade: function (upgradeFunction) {\n /// Function that performs upgrading actions.\n var self = this;\n fakeAutoComplete(function () {\n upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear.\n });\n this._cfg.contentUpgrade = upgradeFunction;\n return this;\n },\n _parseStoresSpec: function (stores, outSchema) {\n keys(stores).forEach(function (tableName) {\n if (stores[tableName] !== null) {\n var instanceTemplate = {};\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);\n indexes.forEach(function (idx) {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () {\n return \"\";\n }) : \"\");\n });\n outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);\n }\n });\n }\n });\n\n function runUpgraders(oldVersion, idbtrans, reject) {\n var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);\n trans.create(idbtrans);\n trans._completion.catch(reject);\n var rejectTransaction = trans._reject.bind(trans);\n newScope(function () {\n PSD.trans = trans;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(function (tableName) {\n createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n Promise.follow(function () {\n return db.on.populate.fire(trans);\n }).catch(rejectTransaction);\n } else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);\n });\n }\n\n function updateTablesAndIndexes(oldVersion, trans, idbtrans) {\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n var queue = [];\n var oldVersionStruct = versions.filter(function (version) {\n return version._cfg.version === oldVersion;\n })[0];\n if (!oldVersionStruct) throw new exceptions.Upgrade(\"Dexie specification of currently installed DB version is missing\");\n globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;\n var anyContentUpgraderHasRun = false;\n\n var versToRun = versions.filter(function (v) {\n return v._cfg.version > oldVersion;\n });\n versToRun.forEach(function (version) {\n /// \n queue.push(function () {\n var oldSchema = globalSchema;\n var newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(oldSchema, idbtrans);\n adjustToExistingIndexNames(newSchema, idbtrans);\n globalSchema = db._dbSchema = newSchema;\n var diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(function (tuple) {\n createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(function (change) {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n var store = idbtrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(function (idx) {\n addIndex(store, idx);\n });\n // Update indexes\n change.change.forEach(function (idx) {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(function (idxName) {\n store.deleteIndex(idxName);\n });\n }\n });\n if (version._cfg.contentUpgrade) {\n anyContentUpgraderHasRun = true;\n return Promise.follow(function () {\n version._cfg.contentUpgrade(trans);\n });\n }\n });\n queue.push(function (idbtrans) {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) {\n // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n var newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n });\n });\n\n // Now, create a queue execution engine\n function runQueue() {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve();\n }\n\n return runQueue().then(function () {\n createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n }\n\n function getSchemaDiff(oldSchema, newSchema) {\n var diff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n for (var table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n var oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n var change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (oldDef.primKey.src !== newDef.primKey.src) {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n var oldIndexes = oldDef.idxByName;\n var newIndexes = newDef.idxByName;\n for (var idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n var oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n }\n\n function createTable(idbtrans, tableName, primKey, indexes) {\n /// \n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });\n indexes.forEach(function (idx) {\n addIndex(store, idx);\n });\n return store;\n }\n\n function createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(function (tableName) {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n }\n\n function deleteRemovedTables(newSchema, idbtrans) {\n for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {\n var storeName = idbtrans.db.objectStoreNames[i];\n if (newSchema[storeName] == null) {\n idbtrans.db.deleteObjectStore(storeName);\n }\n }\n }\n\n function addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n }\n\n function dbUncaught(err) {\n return db.on.error.fire(err);\n }\n\n //\n //\n // Dexie Protected API\n //\n //\n\n this._allTables = allTables;\n\n this._tableFactory = function createTable(mode, tableSchema) {\n /// \n if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection);else return new WriteableTable(tableSchema.name, tableSchema);\n };\n\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {\n return new Transaction(mode, storeNames, dbschema, parentTransaction);\n };\n\n /* Generate a temporary transaction when db operations are done outside a transactino scope.\r\n */\n function tempTransaction(mode, storeNames, fn) {\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n if (!openComplete && !PSD.letThrough) {\n if (!isBeingOpened) {\n if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught);\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return dbReadyPromise.then(function () {\n return tempTransaction(mode, storeNames, fn);\n });\n } else {\n var trans = db._createTransaction(mode, storeNames, globalSchema);\n return trans._promise(mode, function (resolve, reject) {\n newScope(function () {\n // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n fn(resolve, reject, trans);\n });\n }).then(function (result) {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n return trans._completion.then(function () {\n return result;\n });\n }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\r\n trans._reject(err);\r\n return rejection(err);\r\n });*/\n }\n }\n\n this._whenReady = function (fn) {\n return new Promise(fake || openComplete || PSD.letThrough ? fn : function (resolve, reject) {\n if (!isBeingOpened) {\n if (!autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n dbReadyPromise.then(function () {\n fn(resolve, reject);\n });\n }).uncaught(dbUncaught);\n };\n\n //\n //\n //\n //\n // Dexie API\n //\n //\n //\n\n this.verno = 0;\n\n this.open = function () {\n if (isBeingOpened || idbdb) return dbReadyPromise.then(function () {\n return dbOpenError ? rejection(dbOpenError, dbUncaught) : db;\n });\n Debug.debug && (openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n isBeingOpened = true;\n dbOpenError = null;\n openComplete = false;\n\n // Function pointers to call when the core opening process completes.\n var resolveDbReady = dbReadyResolve,\n\n // upgradeTransaction to abort on failure.\n upgradeTransaction = null;\n\n return Promise.race([openCanceller, new Promise(function (resolve, reject) {\n doFakeAutoComplete(function () {\n return resolve();\n });\n\n // Make sure caller has specified at least one version\n if (versions.length > 0) autoSchema = false;\n\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI(\"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \" + \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\n\n var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(\"IndexedDB API not available\"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = wrap(eventRejectHandler(reject));\n req.onblocked = wrap(fireOnBlocked);\n req.onupgradeneeded = wrap(function (e) {\n upgradeTransaction = req.transaction;\n if (autoSchema && !db._allowEmptyDB) {\n // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(function () {\n reject(new exceptions.NoSuchDatabase('Database ' + dbName + ' doesnt exist'));\n });\n } else {\n upgradeTransaction.onerror = wrap(eventRejectHandler(reject));\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n runUpgraders(oldVer / 10, upgradeTransaction, reject, req);\n }\n }, reject);\n\n req.onsuccess = wrap(function () {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n idbdb = req.result;\n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n\n if (autoSchema) readGlobalSchema();else if (idbdb.objectStoreNames.length > 0) {\n try {\n adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));\n } catch (e) {\n // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n }\n }\n\n idbdb.onversionchange = wrap(function (ev) {\n db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n\n if (!hasNativeGetDatabaseNames) {\n // Update localStorage with list of database names\n globalDatabaseList(function (databaseNames) {\n if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName);\n });\n }\n\n resolve();\n }, reject);\n })]).then(function () {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n return Dexie.vip(db.on.ready.fire);\n }).then(function () {\n // Resolve the db.open() with the db instance.\n isBeingOpened = false;\n return db;\n }).catch(function (err) {\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch (e) {}\n isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).\n db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.\n dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught().\n }).finally(function () {\n openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n });\n };\n\n this.close = function () {\n var idx = connections.indexOf(db);\n if (idx >= 0) connections.splice(idx, 1);\n if (idbdb) {\n try {\n idbdb.close();\n } catch (e) {}\n idbdb = null;\n }\n autoOpen = false;\n dbOpenError = new exceptions.DatabaseClosed();\n if (isBeingOpened) cancelOpen(dbOpenError);\n // Reset dbReadyPromise promise:\n dbReadyPromise = new Promise(function (resolve) {\n dbReadyResolve = resolve;\n });\n openCanceller = new Promise(function (_, reject) {\n cancelOpen = reject;\n });\n };\n\n this.delete = function () {\n var hasArguments = arguments.length > 0;\n return new Promise(function (resolve, reject) {\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (isBeingOpened) {\n dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n function doDelete() {\n db.close();\n var req = indexedDB.deleteDatabase(dbName);\n req.onsuccess = wrap(function () {\n if (!hasNativeGetDatabaseNames) {\n globalDatabaseList(function (databaseNames) {\n var pos = databaseNames.indexOf(dbName);\n if (pos >= 0) return databaseNames.splice(pos, 1);\n });\n }\n resolve();\n });\n req.onerror = wrap(eventRejectHandler(reject));\n req.onblocked = fireOnBlocked;\n }\n }).uncaught(dbUncaught);\n };\n\n this.backendDB = function () {\n return idbdb;\n };\n\n this.isOpen = function () {\n return idbdb !== null;\n };\n this.hasFailed = function () {\n return dbOpenError !== null;\n };\n this.dynamicallyOpened = function () {\n return autoSchema;\n };\n\n //\n // Properties\n //\n this.name = dbName;\n\n // db.tables - an array of all Table instances.\n setProp(this, \"tables\", {\n get: function () {\n /// \n return keys(allTables).map(function (name) {\n return allTables[name];\n });\n }\n });\n\n //\n // Events\n //\n this.on = Events(this, \"error\", \"populate\", \"blocked\", \"versionchange\", { ready: [promisableChain, nop] });\n this.on.error.subscribe = Debug.deprecated(\"Dexie.on.error\", this.on.error.subscribe);\n this.on.error.unsubscribe = Debug.deprecated(\"Dexie.on.error.unsubscribe\", this.on.error.unsubscribe);\n\n this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {\n return function (subscriber, bSticky) {\n Dexie.vip(function () {\n if (openComplete) {\n // Database already open. Call subscriber asap.\n if (!dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n };\n });\n\n fakeAutoComplete(function () {\n db.on(\"populate\").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema));\n db.on(\"error\").fire(new Error());\n });\n\n this.transaction = function (mode, tableInstances, scopeFunc) {\n /// \n ///\n /// \n /// \"r\" for readonly, or \"rw\" for readwrite\n /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction\n /// Function to execute with transaction\n\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) {\n args[i - 1] = arguments[i];\n } // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n var parentTransaction = PSD.trans;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;\n var onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n var storeNames = tables.map(function (table) {\n var storeName = table instanceof Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode == READONLY) mode = READONLY;else if (mode == \"rw\" || mode == READWRITE) mode = READWRITE;else throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && mode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null;\n } else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(function (storeName) {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null;\n } else throw new exceptions.SubTransaction(\"Table \" + storeName + \" not included in parent transaction.\");\n }\n });\n }\n }\n } catch (e) {\n return parentTransaction ? parentTransaction._promise(null, function (_, reject) {\n reject(e);\n }) : rejection(e, dbUncaught);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n return parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, \"lock\") : db._whenReady(enterTransactionScope);\n\n function enterTransactionScope(resolve) {\n var parentPSD = PSD;\n resolve(Promise.resolve().then(function () {\n return newScope(function () {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n PSD.transless = PSD.transless || parentPSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n PSD.trans = trans;\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.\n }\n\n // Provide arguments to the scope function (for backward compatibility)\n var tableArgs = storeNames.map(function (name) {\n return allTables[name];\n });\n tableArgs.push(trans);\n\n var returnValue;\n return Promise.follow(function () {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func.\n if (returnValue) {\n if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) {\n throw new exceptions.IncompatiblePromise(\"Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: \" + scopeFunc.toString());\n }\n }\n }).uncaught(dbUncaught).then(function () {\n if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion.\n return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well.\n }).then(function () {\n return returnValue;\n }).catch(function (e) {\n //reject(e);\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n //});\n });\n }));\n }\n };\n\n this.table = function (tableName) {\n /// \n if (fake && autoSchema) return new WriteableTable(tableName);\n if (!hasOwn(allTables, tableName)) {\n throw new exceptions.InvalidTable('Table ' + tableName + ' does not exist');\n }\n return allTables[tableName];\n };\n\n //\n //\n //\n // Table Class\n //\n //\n //\n function Table(name, tableSchema, collClass) {\n /// \n this.name = name;\n this.schema = tableSchema;\n this.hook = allTables[name] ? allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n this._collClass = collClass || Collection;\n }\n\n props(Table.prototype, {\n\n //\n // Table Protected Methods\n //\n\n _trans: function getTransaction(mode, fn, writeLocked) {\n var trans = PSD.trans;\n return trans && trans.db === db ? trans._promise(mode, fn, writeLocked) : tempTransaction(mode, [this.name], fn);\n },\n _idbstore: function getIDBObjectStore(mode, fn, writeLocked) {\n if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion.\n var trans = PSD.trans,\n tableName = this.name;\n function supplyIdbStore(resolve, reject, trans) {\n fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);\n }\n return trans && trans.db === db ? trans._promise(mode, supplyIdbStore, writeLocked) : tempTransaction(mode, [this.name], supplyIdbStore);\n },\n\n //\n // Table Public Methods\n //\n get: function (key, cb) {\n var self = this;\n return this._idbstore(READONLY, function (resolve, reject, idbstore) {\n fake && resolve(self.schema.instanceTemplate);\n var req = idbstore.get(key);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(self.hook.reading.fire(req.result));\n }, reject);\n }).then(cb);\n },\n where: function (indexName) {\n return new WhereClause(this, indexName);\n },\n count: function (cb) {\n return this.toCollection().count(cb);\n },\n offset: function (offset) {\n return this.toCollection().offset(offset);\n },\n limit: function (numRows) {\n return this.toCollection().limit(numRows);\n },\n reverse: function () {\n return this.toCollection().reverse();\n },\n filter: function (filterFunction) {\n return this.toCollection().and(filterFunction);\n },\n each: function (fn) {\n return this.toCollection().each(fn);\n },\n toArray: function (cb) {\n return this.toCollection().toArray(cb);\n },\n orderBy: function (index) {\n return new this._collClass(new WhereClause(this, index));\n },\n\n toCollection: function () {\n return new this._collClass(new WhereClause(this));\n },\n\n mapToClass: function (constructor, structure) {\n /// \n /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making\n /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.\n /// \n /// Constructor function representing the class.\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], password}\n this.schema.mappedClass = constructor;\n var instanceTemplate = Object.create(constructor.prototype);\n if (structure) {\n // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.\n applyStructure(instanceTemplate, structure);\n }\n this.schema.instanceTemplate = instanceTemplate;\n\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n var readHook = function (obj) {\n if (!obj) return obj; // No valid object. (Value is null). Return as is.\n // Create a new object that derives from constructor:\n var res = Object.create(constructor.prototype);\n // Clone members:\n for (var m in obj) {\n if (hasOwn(obj, m)) try {\n res[m] = obj[m];\n } catch (_) {}\n }return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n },\n defineClass: function (structure) {\n /// \n /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database\n /// as well as making it possible to extend the prototype of the returned constructor function.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n return this.mapToClass(Dexie.defineClass(structure), structure);\n }\n });\n\n //\n //\n //\n // WriteableTable Class (extends Table)\n //\n //\n //\n function WriteableTable(name, tableSchema, collClass) {\n Table.call(this, name, tableSchema, collClass || WriteableCollection);\n }\n\n function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) {\n errorList.push(e);\n done && done();\n });\n }\n\n function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {\n // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],\n // else keysOrTuples must be just an array of keys: [key1, key2, ...].\n return new Promise(function (resolve, reject) {\n var len = keysOrTuples.length,\n lastItem = len - 1;\n if (len === 0) return resolve();\n if (!hasDeleteHook) {\n for (var i = 0; i < len; ++i) {\n var req = idbstore.delete(keysOrTuples[i]);\n req.onerror = wrap(eventRejectHandler(reject));\n if (i === lastItem) req.onsuccess = wrap(function () {\n return resolve();\n });\n }\n } else {\n var hookCtx,\n errorHandler = hookedEventRejectHandler(reject),\n successHandler = hookedEventSuccessHandler(null);\n tryCatch(function () {\n for (var i = 0; i < len; ++i) {\n hookCtx = { onsuccess: null, onerror: null };\n var tuple = keysOrTuples[i];\n deletingHook.call(hookCtx, tuple[0], tuple[1], trans);\n var req = idbstore.delete(tuple[0]);\n req._hookCtx = hookCtx;\n req.onerror = errorHandler;\n if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve);else req.onsuccess = successHandler;\n }\n }, function (err) {\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n }\n }).uncaught(dbUncaught);\n }\n\n derive(WriteableTable).from(Table).extend({\n bulkDelete: function (keys) {\n if (this.hook.deleting.fire === nop) {\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n resolve(bulkDelete(idbstore, trans, keys, false, nop));\n });\n } else {\n return this.where(':id').anyOf(keys).delete().then(function () {}); // Resolve with undefined.\n }\n },\n bulkPut: function (objects, keys) {\n var _this = this;\n\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys) throw new exceptions.InvalidArgument(\"bulkPut() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys) throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length) throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n var done = function (result) {\n if (errorList.length === 0) resolve(result);else reject(new BulkError(_this.name + '.bulkPut(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));\n };\n var req,\n errorList = [],\n errorHandler,\n numObjs = objects.length,\n table = _this;\n if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) {\n //\n // Standard Bulk (no 'creating' or 'updating' hooks to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n } else {\n var effectiveKeys = keys || idbstore.keyPath && objects.map(function (o) {\n return getByKeyPath(o, idbstore.keyPath);\n });\n // Generate map of {[key]: object}\n var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) {\n return key != null && [key, objects[i]];\n });\n var promise = !effectiveKeys ?\n\n // Auto-incremented key-less objects only without any keys argument.\n table.bulkAdd(objects) :\n\n // Keys provided. Either as inbound in provided objects, or as a keys argument.\n // Begin with updating those that exists in DB:\n table.where(':id').anyOf(effectiveKeys.filter(function (key) {\n return key != null;\n })).modify(function () {\n this.value = objectLookup[this.primKey];\n objectLookup[this.primKey] = null; // Mark as \"don't add this\"\n }).catch(ModifyError, function (e) {\n errorList = e.failures; // No need to concat here. These are the first errors added.\n }).then(function () {\n // Now, let's examine which items didnt exist so we can add them:\n var objsToAdd = [],\n keysToAdd = keys && [];\n // Iterate backwards. Why? Because if same key was used twice, just add the last one.\n for (var i = effectiveKeys.length - 1; i >= 0; --i) {\n var key = effectiveKeys[i];\n if (key == null || objectLookup[key]) {\n objsToAdd.push(objects[i]);\n keys && keysToAdd.push(key);\n if (key != null) objectLookup[key] = null; // Mark as \"dont add again\"\n }\n }\n // The items are in reverse order so reverse them before adding.\n // Could be important in order to get auto-incremented keys the way the caller\n // would expect. Could have used unshift instead of push()/reverse(),\n // but: http://jsperf.com/unshift-vs-reverse\n objsToAdd.reverse();\n keys && keysToAdd.reverse();\n return table.bulkAdd(objsToAdd, keysToAdd);\n }).then(function (lastAddedKey) {\n // Resolve with key of the last object in given arguments to bulkPut():\n var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.\n return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;\n });\n\n promise.then(done).catch(BulkError, function (e) {\n // Concat failure from ModifyError and reject using our 'done' method.\n errorList = errorList.concat(e.failures);\n done();\n }).catch(reject);\n }\n }, \"locked\"); // If called from transaction scope, lock transaction til all steps are done.\n },\n bulkAdd: function (objects, keys) {\n var self = this,\n creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n if (!idbstore.keyPath && !self.schema.primKey.auto && !keys) throw new exceptions.InvalidArgument(\"bulkAdd() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys) throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length) throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n function done(result) {\n if (errorList.length === 0) resolve(result);else reject(new BulkError(self.name + '.bulkAdd(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));\n }\n var req,\n errorList = [],\n errorHandler,\n successHandler,\n numObjs = objects.length;\n if (creatingHook !== nop) {\n //\n // There are subscribers to hook('creating')\n // Must behave as documented.\n //\n var keyPath = idbstore.keyPath,\n hookCtx;\n errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);\n successHandler = hookedEventSuccessHandler(null);\n\n tryCatch(function () {\n for (var i = 0, l = objects.length; i < l; ++i) {\n hookCtx = { onerror: null, onsuccess: null };\n var key = keys && keys[i];\n var obj = objects[i],\n effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,\n keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);\n if (effectiveKey == null && keyToUse != null) {\n if (keyPath) {\n obj = deepClone(obj);\n setByKeyPath(obj, keyPath, keyToUse);\n } else {\n key = keyToUse;\n }\n }\n req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n if (i < l - 1) {\n req.onerror = errorHandler;\n if (hookCtx.onsuccess) req.onsuccess = successHandler;\n }\n }\n }, function (err) {\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n\n req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);\n req.onsuccess = hookedEventSuccessHandler(done);\n } else {\n //\n // Standard Bulk (no 'creating' hook to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n }\n });\n },\n add: function (obj, key) {\n /// \n /// Add an object to the database. In case an object with same primary key already exists, the object will not be added.\n /// \n /// A javascript object to insert\n /// Primary key\n var creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n var hookCtx = { onsuccess: null, onerror: null };\n if (creatingHook !== nop) {\n var effectiveKey = key != null ? key : idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined;\n var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when(\"creating\") to generate the key.\n if (effectiveKey == null && keyToUse != null) {\n // Using \"==\" and \"!=\" to check for either null or undefined!\n if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse);else key = keyToUse;\n }\n }\n try {\n var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n req.onerror = hookedEventRejectHandler(reject);\n req.onsuccess = hookedEventSuccessHandler(function (result) {\n // TODO: Remove these two lines in next major release (2.0?)\n // It's no good practice to have side effects on provided parameters\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, result);\n resolve(result);\n });\n } catch (e) {\n if (hookCtx.onerror) hookCtx.onerror(e);\n throw e;\n }\n });\n },\n\n put: function (obj, key) {\n /// \n /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.\n /// \n /// A javascript object to insert or update\n /// Primary key\n var self = this,\n creatingHook = this.hook.creating.fire,\n updatingHook = this.hook.updating.fire;\n if (creatingHook !== nop || updatingHook !== nop) {\n //\n // People listens to when(\"creating\") or when(\"updating\") events!\n // We must know whether the put operation results in an CREATE or UPDATE.\n //\n return this._trans(READWRITE, function (resolve, reject, trans) {\n // Since key is optional, make sure we get it from obj if not provided\n var effectiveKey = key !== undefined ? key : self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath);\n if (effectiveKey == null) {\n // \"== null\" means checking for either null or undefined.\n // No primary key. Must use add().\n self.add(obj).then(resolve, reject);\n } else {\n // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().\n trans._lock(); // Needed because operation is splitted into modify() and add().\n // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.\n obj = deepClone(obj);\n self.where(\":id\").equals(effectiveKey).modify(function () {\n // Replace extisting value with our object\n // CRUD event firing handled in WriteableCollection.modify()\n this.value = obj;\n }).then(function (count) {\n if (count === 0) {\n // Object's key was not found. Add the object instead.\n // CRUD event firing will be done in add()\n return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key.\n } else {\n return effectiveKey; // Resolve with the provided key.\n }\n }).finally(function () {\n trans._unlock();\n }).then(resolve, reject);\n }\n });\n } else {\n // Use the standard IDB put() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function (ev) {\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);\n resolve(req.result);\n };\n });\n }\n },\n\n 'delete': function (key) {\n /// Primary key of the object to delete\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using WriteableCollection.delete() that will\n // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted.\n return this.where(\":id\").equals(key).delete();\n } else {\n // No one listens. Use standard IDB delete() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.delete(key);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function () {\n resolve(req.result);\n };\n });\n }\n },\n\n clear: function () {\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using WriteableCollection.delete() that will\n // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted.\n return this.toCollection().delete();\n } else {\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.clear();\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function () {\n resolve(req.result);\n };\n });\n }\n },\n\n update: function (keyOrObject, modifications) {\n if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument(\"Modifications must be an object.\");\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n // object to modify. Also modify given object with the modifications:\n keys(modifications).forEach(function (keyPath) {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\"Given object does not contain its primary key\"), dbUncaught);\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n });\n\n //\n //\n //\n // Transaction Class\n //\n //\n //\n function Transaction(mode, storeNames, dbschema, parent) {\n var _this2 = this;\n\n /// \n /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.\n /// \n /// Any of \"readwrite\" or \"readonly\"\n /// Array of table names to operate on\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._tables = null;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._psd = null;\n this._dbschema = dbschema;\n this._resolve = null;\n this._reject = null;\n this._completion = new Promise(function (resolve, reject) {\n _this2._resolve = resolve;\n _this2._reject = reject;\n }).uncaught(dbUncaught);\n\n this._completion.then(function () {\n _this2.on.complete.fire();\n }, function (e) {\n _this2.on.error.fire(e);\n _this2.parent ? _this2.parent._reject(e) : _this2.active && _this2.idbtrans && _this2.idbtrans.abort();\n _this2.active = false;\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n }\n\n props(Transaction.prototype, {\n //\n // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n _lock: function () {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n },\n _unlock: function () {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fn = this._blockedFuncs.shift();\n try {\n fn();\n } catch (e) {}\n }\n }\n return this;\n },\n _locked: function () {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n },\n create: function (idbtrans) {\n var _this3 = this;\n\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);\n idbtrans.onerror = wrap(function (ev) {\n preventDefault(ev); // Prohibit default bubbling to window.error\n _this3._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(function (ev) {\n preventDefault(ev);\n _this3.active && _this3._reject(new exceptions.Abort());\n _this3.active = false;\n _this3.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(function () {\n _this3.active = false;\n _this3._resolve();\n });\n return this;\n },\n _promise: function (mode, fn, bWriteLock) {\n var self = this;\n return newScope(function () {\n var p;\n // Read lock always\n if (!self._locked()) {\n p = self.active ? new Promise(function (resolve, reject) {\n if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly(\"Transaction is readonly\");\n if (!self.idbtrans && mode) self.create();\n if (bWriteLock) self._lock(); // Write lock if write operation is requested\n fn(resolve, reject, self);\n }) : rejection(new exceptions.TransactionInactive());\n if (self.active && bWriteLock) p.finally(function () {\n self._unlock();\n });\n } else {\n // Transaction is write-locked. Wait for mutex.\n p = new Promise(function (resolve, reject) {\n self._blockedFuncs.push(function () {\n self._promise(mode, fn, bWriteLock).then(resolve, reject);\n });\n });\n }\n p._lib = true;\n return p.uncaught(dbUncaught);\n });\n },\n\n //\n // Transaction Public Properties and Methods\n //\n abort: function () {\n this.active && this._reject(new exceptions.Abort());\n this.active = false;\n },\n\n tables: {\n get: Debug.deprecated(\"Transaction.tables\", function () {\n return arrayToObject(this.storeNames, function (name) {\n return [name, allTables[name]];\n });\n }, \"Use db.tables()\")\n },\n\n complete: Debug.deprecated(\"Transaction.complete()\", function (cb) {\n return this.on(\"complete\", cb);\n }),\n\n error: Debug.deprecated(\"Transaction.error()\", function (cb) {\n return this.on(\"error\", cb);\n }),\n\n table: Debug.deprecated(\"Transaction.table()\", function (name) {\n if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable(\"Table \" + name + \" not in transaction\");\n return allTables[name];\n })\n\n });\n\n //\n //\n //\n // WhereClause\n //\n //\n //\n function WhereClause(table, index, orCollection) {\n /// \n /// \n /// \n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n collClass: table._collClass,\n or: orCollection\n };\n }\n\n props(WhereClause.prototype, function () {\n\n // WhereClause private methods\n\n function fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause;\n\n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n }\n\n function emptyCollection(whereClause) {\n return new whereClause._ctx.collClass(whereClause, function () {\n return IDBKeyRange.only(\"\");\n }).limit(0);\n }\n\n function upperFactory(dir) {\n return dir === \"next\" ? function (s) {\n return s.toUpperCase();\n } : function (s) {\n return s.toLowerCase();\n };\n }\n function lowerFactory(dir) {\n return dir === \"next\" ? function (s) {\n return s.toLowerCase();\n } : function (s) {\n return s.toUpperCase();\n };\n }\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1);\n }\n\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n /// \n var upper,\n lower,\n compare,\n upperNeedles,\n lowerNeedles,\n direction,\n nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(function (s) {\n return typeof s === 'string';\n })) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = dir === \"next\" ? simpleCompare : simpleCompareReverse;\n var needleBounds = needles.map(function (needle) {\n return { lower: lower(needle), upper: upper(needle) };\n }).sort(function (a, b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb) {\n return nb.upper;\n });\n lowerNeedles = needleBounds.map(function (nb) {\n return nb.lower;\n });\n direction = dir;\n nextKeySuffix = dir === \"next\" ? \"\" : suffix;\n }\n initDirection(\"next\");\n\n var c = new whereClause._ctx.collClass(whereClause, function () {\n return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix);\n });\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i = firstPossibleNeedle; i < needlesLen; ++i) {\n var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction);\n if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1;else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () {\n cursor.continue(lowestPossibleCasing + nextKeySuffix);\n });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n }\n\n //\n // WhereClause public methods\n //\n return {\n between: function (lower, upper, includeLower, includeUpper) {\n /// \n /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.\n /// \n /// \n /// \n /// Whether items that equals lower should be included. Default true.\n /// Whether items that equals upper should be included. Default false.\n /// \n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if (cmp(lower, upper) > 0 || cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper);\n });\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n },\n equals: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.only(value);\n });\n },\n above: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.lowerBound(value, true);\n });\n },\n aboveOrEqual: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.lowerBound(value);\n });\n },\n below: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.upperBound(value, true);\n });\n },\n belowOrEqual: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.upperBound(value);\n });\n },\n startsWith: function (str) {\n /// \n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n },\n startsWithIgnoreCase: function (str) {\n /// \n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return x.indexOf(a[0]) === 0;\n }, [str], maxString);\n },\n equalsIgnoreCase: function (str) {\n /// \n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return x === a[0];\n }, [str], \"\");\n },\n anyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return a.indexOf(x) !== -1;\n }, set, \"\");\n },\n startsWithAnyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return a.some(function (n) {\n return x.indexOf(n) === 0;\n });\n }, set, maxString);\n },\n anyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n var compare = ascending;\n try {\n set.sort(compare);\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n if (set.length === 0) return emptyCollection(this);\n var c = new this._ctx.collClass(this, function () {\n return IDBKeyRange.bound(set[0], set[set.length - 1]);\n });\n\n c._ondirectionchange = function (direction) {\n compare = direction === \"next\" ? ascending : descending;\n set.sort(compare);\n };\n var i = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function () {\n cursor.continue(set[i]);\n });\n return false;\n }\n });\n return c;\n },\n\n notEqual: function (value) {\n return this.inAnyRange([[-Infinity, value], [value, maxKey]], { includeLowers: false, includeUppers: false });\n },\n\n noneOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection.\n try {\n set.sort(ascending);\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[-Infinity,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n var ranges = set.reduce(function (res, val) {\n return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]];\n }, null);\n ranges.push([set[set.length - 1], maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n },\n\n /** Filter out values withing given set of ranges.\r\n * Example, give children and elders a rebate of 50%:\r\n *\r\n * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});\r\n *\r\n * @param {(string|number|Date|Array)[][]} ranges\r\n * @param {{includeLowers: boolean, includeUppers: boolean}} options\r\n */\n inAnyRange: function (ranges, options) {\n var ctx = this._ctx;\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(function (range) {\n return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;\n })) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n var includeLowers = !options || options.includeLowers !== false; // Default to true\n var includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n for (var i = 0, l = ranges.length; i < l; ++i) {\n var range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l) ranges.push(newRange);\n return ranges;\n }\n\n var sortDirection = ascending;\n function rangeSorter(a, b) {\n return sortDirection(a[0], b[0]);\n }\n\n // Join overlapping ranges\n var set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n var i = 0;\n var keyIsBeyondCurrentEntry = includeUppers ? function (key) {\n return ascending(key, set[i][1]) > 0;\n } : function (key) {\n return ascending(key, set[i][1]) >= 0;\n };\n\n var keyIsBeforeCurrentEntry = includeLowers ? function (key) {\n return descending(key, set[i][0]) > 0;\n } : function (key) {\n return descending(key, set[i][0]) >= 0;\n };\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n var checkKey = keyIsBeyondCurrentEntry;\n\n var c = new ctx.collClass(this, function () {\n return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);\n });\n\n c._ondirectionchange = function (direction) {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function () {\n if (sortDirection === ascending) cursor.continue(set[i][0]);else cursor.continue(set[i][1]);\n });\n return false;\n }\n });\n return c;\n },\n startsWithAnyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(function (s) {\n return typeof s === 'string';\n })) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map(function (str) {\n return [str, str + maxString];\n }));\n }\n };\n });\n\n //\n //\n //\n // Collection Class\n //\n //\n //\n function Collection(whereClause, keyRangeGenerator) {\n /// \n ///\n /// \n /// Where clause instance\n /// \n var keyRange = null,\n error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n var whereCtx = whereClause._ctx,\n table = whereCtx.table;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name,\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: table.hook.reading.fire\n };\n }\n\n function isPlainKeyRange(ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n }\n\n props(Collection.prototype, function () {\n\n //\n // Collection Private Functions\n //\n\n function addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n }\n\n function addReplayFilter(ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? function () {\n return combine(curr(), factory());\n } : factory;\n ctx.justLimit = isLimitFilter && !curr;\n }\n\n function addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n }\n\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string\r\n * }\r\n * @param store IDBObjectStore\r\n **/\n function getIndexOrStore(ctx, store) {\n if (ctx.isPrimKey) return store;\n var indexSpec = ctx.table.schema.idxByName[ctx.index];\n if (!indexSpec) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + store.name + \" is not indexed\");\n return store.index(indexSpec.name);\n }\n\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string,\r\n * keysOnly: boolean,\r\n * range?: IDBKeyRange,\r\n * dir: \"next\" | \"prev\"\r\n * }\r\n */\n function openCursor(ctx, store) {\n var idxOrStore = getIndexOrStore(ctx, store);\n return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);\n }\n\n function iter(ctx, fn, resolve, reject, idbstore) {\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);\n } else (function () {\n var set = {};\n var resolved = 0;\n\n function resolveboth() {\n if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.\n }\n\n function union(item, cursor, advance) {\n if (!filter || filter(cursor, advance, resolveboth, reject)) {\n var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n ctx.or._iterate(union, resolveboth, reject, idbstore);\n iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);\n })();\n }\n function getInstanceTemplate(ctx) {\n return ctx.table.schema.instanceTemplate;\n }\n\n return {\n\n //\n // Collection Protected Functions\n //\n\n _read: function (fn, cb) {\n var ctx = this._ctx;\n if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {\n reject(ctx.error);\n });else return ctx.table._idbstore(READONLY, fn).then(cb);\n },\n _write: function (fn) {\n var ctx = this._ctx;\n if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {\n reject(ctx.error);\n });else return ctx.table._idbstore(READWRITE, fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n },\n _addAlgorithm: function (fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n },\n\n _iterate: function (fn, resolve, reject, idbstore) {\n return iter(this._ctx, fn, resolve, reject, idbstore);\n },\n\n clone: function (props) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n },\n\n raw: function () {\n this._ctx.valueMapper = null;\n return this;\n },\n\n //\n // Collection Public methods\n //\n\n each: function (fn) {\n var ctx = this._ctx;\n\n if (fake) {\n var item = getInstanceTemplate(ctx),\n primKeyPath = ctx.table.schema.primKey.keyPath,\n key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath),\n primaryKey = getByKeyPath(item, primKeyPath);\n fn(item, { key: key, primaryKey: primaryKey });\n }\n\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, fn, resolve, reject, idbstore);\n });\n },\n\n count: function (cb) {\n if (fake) return Promise.resolve(0).then(cb);\n var ctx = this._ctx;\n\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return this._read(function (resolve, reject, idbstore) {\n var idx = getIndexOrStore(ctx, idbstore);\n var req = ctx.range ? idx.count(ctx.range) : idx.count();\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function (e) {\n resolve(Math.min(e.target.result, ctx.limit));\n };\n }, cb);\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, function () {\n ++count;return false;\n }, function () {\n resolve(count);\n }, reject, idbstore);\n }, cb);\n }\n },\n\n sortBy: function (keyPath, cb) {\n /// \n var parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n },\n\n toArray: function (cb) {\n var ctx = this._ctx;\n return this._read(function (resolve, reject, idbstore) {\n fake && resolve([getInstanceTemplate(ctx)]);\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n var readingHook = ctx.table.hook.reading.fire;\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(function (res) {\n try {\n resolve(res.map(readingHook));\n } catch (e) {\n reject(e);\n }\n }));\n } else {\n // Getting array through a cursor.\n var a = [];\n iter(ctx, function (item) {\n a.push(item);\n }, function arrayComplete() {\n resolve(a);\n }, reject, idbstore);\n }\n }, cb);\n },\n\n offset: function (offset) {\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, function () {\n var offsetLeft = offset;\n return function (cursor, advance) {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) {\n --offsetLeft;return false;\n }\n advance(function () {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, function () {\n var offsetLeft = offset;\n return function () {\n return --offsetLeft < 0;\n };\n });\n }\n return this;\n },\n\n limit: function (numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, function () {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n },\n\n until: function (filterFunction, bIncludeStopEntry) {\n var ctx = this._ctx;\n fake && filterFunction(getInstanceTemplate(ctx));\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n },\n\n first: function (cb) {\n return this.limit(1).toArray(function (a) {\n return a[0];\n }).then(cb);\n },\n\n last: function (cb) {\n return this.reverse().first(cb);\n },\n\n filter: function (filterFunction) {\n /// function(val){return true/false}\n fake && filterFunction(getInstanceTemplate(this._ctx));\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction);\n return this;\n },\n\n and: function (filterFunction) {\n return this.filter(filterFunction);\n },\n\n or: function (indexName) {\n return new WhereClause(this._ctx.table, indexName, this);\n },\n\n reverse: function () {\n this._ctx.dir = this._ctx.dir === \"prev\" ? \"next\" : \"prev\";\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n },\n\n desc: function () {\n return this.reverse();\n },\n\n eachKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) {\n cb(cursor.key, cursor);\n });\n },\n\n eachUniqueKey: function (cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n },\n\n eachPrimaryKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) {\n cb(cursor.primaryKey, cursor);\n });\n },\n\n keys: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n },\n\n primaryKeys: function (cb) {\n var ctx = this._ctx;\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read(function (resolve, reject, idbstore) {\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = eventSuccessHandler(resolve);\n }).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n },\n\n uniqueKeys: function (cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n },\n\n firstKey: function (cb) {\n return this.limit(1).keys(function (a) {\n return a[0];\n }).then(cb);\n },\n\n lastKey: function (cb) {\n return this.reverse().firstKey(cb);\n },\n\n distinct: function () {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n };\n });\n\n //\n //\n // WriteableCollection Class\n //\n //\n function WriteableCollection() {\n Collection.apply(this, arguments);\n }\n\n derive(WriteableCollection).from(Collection).extend({\n\n //\n // WriteableCollection Public Methods\n //\n\n modify: function (changes) {\n var self = this,\n ctx = this._ctx,\n hook = ctx.table.hook,\n updatingHook = hook.updating.fire,\n deletingHook = hook.deleting.fire;\n\n fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate);\n\n return this._write(function (resolve, reject, idbstore, trans) {\n var modifyer;\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n if (updatingHook === nop && deletingHook === nop) {\n // Noone cares about what is being changed. Just let the modifier function be the given argument as is.\n modifyer = changes;\n } else {\n // People want to know exactly what is being modified or deleted.\n // Let modifyer be a proxy function that finds out what changes the caller is actually doing\n // and call the hooks accordingly!\n modifyer = function (item) {\n var origItem = deepClone(item); // Clone the item first so we can compare laters.\n if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)\n if (!hasOwn(this, \"value\")) {\n // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.\n deletingHook.call(this, this.primKey, item, trans);\n } else {\n // No deletion. Check what was changed\n var objectDiff = getObjectDiff(origItem, this.value);\n var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);\n if (additionalChanges) {\n // Hook want to apply additional modifications. Make sure to fullfill the will of the hook.\n item = this.value;\n keys(additionalChanges).forEach(function (keyPath) {\n setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n });\n }\n }\n };\n }\n } else if (updatingHook === nop) {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i],\n val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n } else {\n // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and\n // allow it to add additional modifications to make.\n var origChanges = changes;\n changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.\n modifyer = function (item) {\n var anythingModified = false;\n var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);\n if (additionalChanges) extend(changes, additionalChanges);\n keys(changes).forEach(function (keyPath) {\n var val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n });\n if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration\n return anythingModified;\n };\n }\n\n var count = 0;\n var successCount = 0;\n var iterationComplete = false;\n var failures = [];\n var failKeys = [];\n var currentKey = null;\n\n function modifyItem(item, cursor) {\n currentKey = cursor.primaryKey;\n var thisContext = {\n primKey: cursor.primaryKey,\n value: item,\n onsuccess: null,\n onerror: null\n };\n\n function onerror(e) {\n failures.push(e);\n failKeys.push(thisContext.primKey);\n checkFinished();\n return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction\n }\n\n if (modifyer.call(thisContext, item, thisContext) !== false) {\n // If a callback explicitely returns false, do not perform the update!\n var bDelete = !hasOwn(thisContext, \"value\");\n ++count;\n tryCatch(function () {\n var req = bDelete ? cursor.delete() : cursor.update(thisContext.value);\n req._hookCtx = thisContext;\n req.onerror = hookedEventRejectHandler(onerror);\n req.onsuccess = hookedEventSuccessHandler(function () {\n ++successCount;\n checkFinished();\n });\n }, onerror);\n } else if (thisContext.onsuccess) {\n // Hook will expect either onerror or onsuccess to always be called!\n thisContext.onsuccess(thisContext.value);\n }\n }\n\n function doReject(e) {\n if (e) {\n failures.push(e);\n failKeys.push(currentKey);\n }\n return reject(new ModifyError(\"Error modifying one or more objects\", failures, successCount, failKeys));\n }\n\n function checkFinished() {\n if (iterationComplete && successCount + failures.length === count) {\n if (failures.length > 0) doReject();else resolve(successCount);\n }\n }\n self.clone().raw()._iterate(modifyItem, function () {\n iterationComplete = true;\n checkFinished();\n }, doReject, idbstore);\n });\n },\n\n 'delete': function () {\n var _this4 = this;\n\n var ctx = this._ctx,\n range = ctx.range,\n deletingHook = ctx.table.hook.deleting.fire,\n hasDeleteHook = deletingHook !== nop;\n if (!hasDeleteHook && isPlainKeyRange(ctx) && (ctx.isPrimKey && !hangsOnDeleteLargeKeyRange || !range)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write(function (resolve, reject, idbstore) {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n var onerror = eventRejectHandler(reject),\n countReq = range ? idbstore.count(range) : idbstore.count();\n countReq.onerror = onerror;\n countReq.onsuccess = function () {\n var count = countReq.result;\n tryCatch(function () {\n var delReq = range ? idbstore.delete(range) : idbstore.clear();\n delReq.onerror = onerror;\n delReq.onsuccess = function () {\n return resolve(count);\n };\n }, function (err) {\n return reject(err);\n });\n };\n });\n }\n\n // Default version to use when collection is not a vanilla IDBKeyRange on the primary key.\n // Divide into chunks to not starve RAM.\n // If has delete hook, we will have to collect not just keys but also objects, so it will use\n // more memory and need lower chunk size.\n var CHUNKSIZE = hasDeleteHook ? 2000 : 10000;\n\n return this._write(function (resolve, reject, idbstore, trans) {\n var totalCount = 0;\n // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.\n var collection = _this4.clone({\n keysOnly: !ctx.isMatch && !hasDeleteHook }) // load just keys (unless filter() or and() or deleteHook has subscribers)\n .distinct() // In case multiEntry is used, never delete same key twice because resulting count\n // would become larger than actual delete count.\n .limit(CHUNKSIZE).raw(); // Don't filter through reading-hooks (like mapped classes etc)\n\n var keysOrTuples = [];\n\n // We're gonna do things on as many chunks that are needed.\n // Use recursion of nextChunk function:\n var nextChunk = function () {\n return collection.each(hasDeleteHook ? function (val, cursor) {\n // Somebody subscribes to hook('deleting'). Collect all primary keys and their values,\n // so that the hook can be called with its values in bulkDelete().\n keysOrTuples.push([cursor.primaryKey, cursor.value]);\n } : function (val, cursor) {\n // No one subscribes to hook('deleting'). Collect only primary keys:\n keysOrTuples.push(cursor.primaryKey);\n }).then(function () {\n // Chromium deletes faster when doing it in sort order.\n hasDeleteHook ? keysOrTuples.sort(function (a, b) {\n return ascending(a[0], b[0]);\n }) : keysOrTuples.sort(ascending);\n return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);\n }).then(function () {\n var count = keysOrTuples.length;\n totalCount += count;\n keysOrTuples = [];\n return count < CHUNKSIZE ? totalCount : nextChunk();\n });\n };\n\n resolve(nextChunk());\n });\n }\n });\n\n //\n //\n //\n // ------------------------- Help functions ---------------------------\n //\n //\n //\n\n function lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n }\n\n function setApiOnPlace(objs, tableNames, mode, dbschema) {\n tableNames.forEach(function (tableName) {\n var tableInstance = db._tableFactory(mode, dbschema[tableName]);\n objs.forEach(function (obj) {\n tableName in obj || (obj[tableName] = tableInstance);\n });\n });\n }\n\n function removeTablesApi(objs) {\n objs.forEach(function (obj) {\n for (var key in obj) {\n if (obj[key] instanceof Table) delete obj[key];\n }\n });\n }\n\n function iterate(req, filter, fn, resolve, reject, valueMapper) {\n\n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? function (x, c, a) {\n return fn(valueMapper(x), c, a);\n } : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn, reject);\n\n if (!req.onerror) req.onerror = eventRejectHandler(reject);\n if (filter) {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () {\n cursor.continue();\n };\n if (filter(cursor, function (advancer) {\n c = advancer;\n }, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) {\n c = advancer;\n });\n c();\n } else {\n resolve();\n }\n }, reject);\n } else {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () {\n cursor.continue();\n };\n wrappedFn(cursor.value, cursor, function (advancer) {\n c = advancer;\n });\n c();\n } else {\n resolve();\n }\n }, reject);\n }\n }\n\n function parseIndexSyntax(indexes) {\n /// \n /// \n var rv = [];\n indexes.split(',').forEach(function (index) {\n index = index.trim();\n var name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n rv.push(new IndexSpec(name, keyPath || null, /\\&/.test(index), /\\*/.test(index), /\\+\\+/.test(index), isArray(keyPath), /\\./.test(index)));\n });\n return rv;\n }\n\n function cmp(key1, key2) {\n return indexedDB.cmp(key1, key2);\n }\n\n function min(a, b) {\n return cmp(a, b) < 0 ? a : b;\n }\n\n function max(a, b) {\n return cmp(a, b) > 0 ? a : b;\n }\n\n function ascending(a, b) {\n return indexedDB.cmp(a, b);\n }\n\n function descending(a, b) {\n return indexedDB.cmp(b, a);\n }\n\n function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n }\n\n function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n }\n\n function combine(filter1, filter2) {\n return filter1 ? filter2 ? function () {\n return filter1.apply(this, arguments) && filter2.apply(this, arguments);\n } : filter1 : filter2;\n }\n\n function readGlobalSchema() {\n db.verno = idbdb.version / 10;\n db._dbSchema = globalSchema = {};\n dbStoreNames = slice(idbdb.objectStoreNames, 0);\n if (dbStoreNames.length === 0) return; // Database contains no stores.\n var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');\n dbStoreNames.forEach(function (storeName) {\n var store = trans.objectStore(storeName),\n keyPath = store.keyPath,\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var primKey = new IndexSpec(keyPath, keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);\n var indexes = [];\n for (var j = 0; j < store.indexNames.length; ++j) {\n var idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);\n indexes.push(index);\n }\n globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});\n });\n setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema);\n }\n\n function adjustToExistingIndexNames(schema, idbtrans) {\n /// \n /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n /// \n /// Map between name and TableSchema\n /// \n var storeNames = idbtrans.db.objectStoreNames;\n for (var i = 0; i < storeNames.length; ++i) {\n var storeName = storeNames[i];\n var store = idbtrans.objectStore(storeName);\n hasGetAll = 'getAll' in store;\n for (var j = 0; j < store.indexNames.length; ++j) {\n var indexName = store.indexNames[j];\n var keyPath = store.index(indexName).keyPath;\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n var indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) indexSpec.name = indexName;\n }\n }\n }\n }\n\n function fireOnBlocked(ev) {\n db.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections.filter(function (c) {\n return c.name === db.name && c !== db && !c._vcFired;\n }).map(function (c) {\n return c.on(\"versionchange\").fire(ev);\n });\n }\n\n extend(this, {\n Collection: Collection,\n Table: Table,\n Transaction: Transaction,\n Version: Version,\n WhereClause: WhereClause,\n WriteableCollection: WriteableCollection,\n WriteableTable: WriteableTable\n });\n\n init();\n\n addons.forEach(function (fn) {\n fn(db);\n });\n}\n\nvar fakeAutoComplete = function () {}; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\nvar fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\n\nfunction parseType(type) {\n if (typeof type === 'function') {\n return new type();\n } else if (isArray(type)) {\n return [parseType(type[0])];\n } else if (type && typeof type === 'object') {\n var rv = {};\n applyStructure(rv, type);\n return rv;\n } else {\n return type;\n }\n}\n\nfunction applyStructure(obj, structure) {\n keys(structure).forEach(function (member) {\n var value = parseType(structure[member]);\n obj[member] = value;\n });\n return obj;\n}\n\nfunction eventSuccessHandler(done) {\n return function (ev) {\n done(ev.target.result);\n };\n}\n\nfunction hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function (event) {\n var req = event.target,\n result = req.result,\n ctx = req._hookCtx,\n // Contains the hook error handler. Put here instead of closure to boost performance.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\nfunction eventRejectHandler(reject) {\n return function (event) {\n preventDefault(event);\n reject(event.target.error);\n return false;\n };\n}\n\nfunction hookedEventRejectHandler(reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n\n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,\n // Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject(err);\n return false;\n });\n}\n\nfunction preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nfunction globalDatabaseList(cb) {\n var val,\n localStorage = Dexie.dependencies.localStorage;\n if (!localStorage) return cb([]); // Envs without localStorage support\n try {\n val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || \"[]\");\n } catch (e) {\n val = [];\n }\n if (cb(val)) {\n localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val));\n }\n}\n\nfunction awaitIterator(iterator) {\n var callNext = function (result) {\n return iterator.next(result);\n },\n doThrow = function (error) {\n return iterator.throw(error);\n },\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext) {\n return function (val) {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value : !value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError);\n };\n }\n\n return step(callNext)();\n}\n\n//\n// IndexSpec struct\n//\nfunction IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n this.name = name;\n this.keyPath = keyPath;\n this.unique = unique;\n this.multi = multi;\n this.auto = auto;\n this.compound = compound;\n this.dotted = dotted;\n var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && '[' + [].join.call(keyPath, '+') + ']';\n this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + keyPathSrc;\n}\n\n//\n// TableSchema struct\n//\nfunction TableSchema(name, primKey, indexes, instanceTemplate) {\n /// \n /// \n /// \n /// \n this.name = name;\n this.primKey = primKey || new IndexSpec();\n this.indexes = indexes || [new IndexSpec()];\n this.instanceTemplate = instanceTemplate;\n this.mappedClass = null;\n this.idxByName = arrayToObject(indexes, function (index) {\n return [index.name, index];\n });\n}\n\n// Used in when defining dependencies later...\n// (If IndexedDBShim is loaded, prefer it before standard indexedDB)\nvar idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {};\n\nfunction safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nfunction getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\n// Export Error classes\nprops(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};\n\n//\n// Static methods and properties\n// \nprops(Dexie, {\n\n //\n // Static delete() method.\n //\n delete: function (databaseName) {\n var db = new Dexie(databaseName),\n promise = db.delete();\n promise.onblocked = function (fn) {\n db.on(\"blocked\", fn);\n return this;\n };\n return promise;\n },\n\n //\n // Static exists() method.\n //\n exists: function (name) {\n return new Dexie(name).open().then(function (db) {\n db.close();\n return true;\n }).catch(Dexie.NoSuchDatabaseError, function () {\n return false;\n });\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames: function (cb) {\n return new Promise(function (resolve, reject) {\n var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB);\n if (getDatabaseNames) {\n // In case getDatabaseNames() becomes standard, let's prepare to support it:\n var req = getDatabaseNames();\n req.onsuccess = function (event) {\n resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array\n };\n req.onerror = eventRejectHandler(reject);\n } else {\n globalDatabaseList(function (val) {\n resolve(val);\n return false;\n });\n }\n }).then(cb);\n },\n\n defineClass: function (structure) {\n /// \n /// Create a javascript constructor based on given template for which properties to expect in the class.\n /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n\n // Default constructor able to copy given properties into this object.\n function Class(properties) {\n /// Properties to initialize object with.\n /// \n properties ? extend(this, properties) : fake && applyStructure(this, structure);\n }\n return Class;\n },\n\n applyStructure: applyStructure,\n\n ignoreTransaction: function (scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n\n vip: function (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n },\n\n async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n\n // Dexie.currentTransaction property\n currentTransaction: {\n get: function () {\n return PSD.trans || null;\n }\n },\n\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n\n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: function () {\n return Debug.debug;\n },\n set: function (value) {\n Debug.setDebug(value, value === 'dexie' ? function () {\n return true;\n } : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive,\n extend: extend,\n props: props,\n override: override,\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n events: { get: Debug.deprecated(function () {\n return Events;\n }) }, // Backward compatible lowercase version.\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n asap: asap,\n maxKey: maxKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.\n errnames: errnames,\n\n // Export other static classes\n IndexSpec: IndexSpec,\n TableSchema: TableSchema,\n\n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: {\n // Required:\n indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange\n },\n\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.').map(function (n) {\n return parseInt(n);\n }).reduce(function (p, c, i) {\n return p + c / Math.pow(10, i * 2);\n }),\n fakeAutoComplete: fakeAutoComplete,\n\n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n default: Dexie\n});\n\ntryCatch(function () {\n // Optional dependencies\n // localStorage\n Dexie.dependencies.localStorage = (typeof chrome !== \"undefined\" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage;\n});\n\n// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.\nPromise.rejectionMapper = mapError;\n\n// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015.\ndoFakeAutoComplete(function () {\n Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete;\n Dexie.fake = fake = true;\n});"],"names":["asap","Debug.setDebug","Debug.debug","Debug.getErrorWithStack","Debug.deprecated","keys","props"],"mappings":";;;;;;AAAA;;;;;;;;;;AAUA,AAAO,IAAI,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;AAC9B,AAAO,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;AACnC,AAAO,IAAI,OAAO,GAAG,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI,GAAG,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM,GAAG,MAAM,CAAC;;AAE1G,AAAO,SAAS,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE;IACnC,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,OAAO,GAAG,CAAC;IAC9C,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,UAAU,GAAG,EAAE;QACnC,GAAG,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;KAC7B,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;CACd;;AAED,AAAO,IAAI,QAAQ,GAAG,MAAM,CAAC,cAAc,CAAC;AAC5C,AAAO,IAAI,OAAO,GAAG,EAAE,CAAC,cAAc,CAAC;AACvC,AAAO,SAAS,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE;IAC9B,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;CAClC;;AAED,AAAO,SAAS,KAAK,CAAC,KAAK,EAAE,SAAS,EAAE;IACpC,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,SAAS,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;IAC5E,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,UAAU,GAAG,EAAE;QACnC,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,CAAC,GAAG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MAAM,EAAE,aAAa;IACrB,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE;QAC/C,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC;KACtB,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE;QACzB,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;KACtC,CAAC;IACF,gBAAgB,EAAE,gBAAgB;;;;;IAKlC,OAAO,EAAE,KAAK;CACjB,CAAC,CAAC;;AAEH,QAAQ,CAAC,YAAY;;;IAGjB,KAAK,CAAC,YAAY,CAAC,YAAY,GAAG,CAAC,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,KAAK,IAAI,GAAG,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC,IAAI,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC;CACxJ,CAAC,CAAC;;;AAGH,OAAO,CAAC,eAAe,GAAG,QAAQ,CAAC;;;AAGnC,kBAAkB,CAAC,YAAY;IAC3B,KAAK,CAAC,gBAAgB,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;IAC/D,KAAK,CAAC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;CAC5B,CAAC,;;,;;"} \ No newline at end of file diff --git a/dist/dexie.min.js b/dist/dexie.min.js new file mode 100644 index 000000000..1ad5fc276 --- /dev/null +++ b/dist/dexie.min.js @@ -0,0 +1,3 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):n.Dexie=t()}(this,function(){"use strict";function n(n,t){return"object"!=typeof t?n:(jn(t).forEach(function(e){n[e]=t[e]}),n)}function t(n,t){return Cn.call(n,t)}function e(n,t){"function"==typeof t&&(t=t(Pn(n))),jn(t).forEach(function(e){r(n,e,t[e])})}function r(e,r,i,o){Object.defineProperty(e,r,n(i&&t(i,"get")&&"function"==typeof i.get?{get:i.get,set:i.set,configurable:!0}:{value:i,configurable:!0,writable:!0},o))}function i(n){return{from:function(t){return n.prototype=Object.create(t.prototype),r(n.prototype,"constructor",n),{extend:e.bind(null,n.prototype)}}}}function o(n,t){var e,r=In(n,t);return r||(e=Pn(n))&&o(e,t)}function u(n,t,e){return Dn.call(n,t,e)}function a(n,t){return t(n)}function c(n){var t=setTimeout(n,1e3);clearTimeout(t)}function s(n){if(!n)throw new Error("Assertion Failed")}function f(n){On.setImmediate?setImmediate(n):setTimeout(n,0)}function l(n,t){return n.reduce(function(n,e,r){var i=t(e,r);return i&&(n[i[0]]=i[1]),n},{})}function h(n,t){return function(){try{n.apply(this,arguments)}catch(n){t(n)}}}function d(n,t,e){try{n.apply(null,e)}catch(n){t&&t(n)}}function v(n,e){if(t(n,e))return n[e];if(!e)return n;if("string"!=typeof e){for(var r=[],i=0,o=e.length;i0;)for(n=ct,ct=[],e=n.length,t=0;t0);nt=!0,tt=!0}function Z(){var n=et;et=[],n.forEach(function(n){n._PSD.onunhandled.call(null,n._value,n)});for(var t=ft.slice(0),e=t.length;e;)t[--e]()}function nn(n){function t(){n(),ft.splice(ft.indexOf(t),1)}ft.push(t),++st,Zn(function(){0===--st&&Z()},[])}function tn(n){et.some(function(t){return t._value===n._value})||et.push(n)}function en(n){for(var t=et.length;t;)if(et[--t]._value===n._value)return void et.splice(t,1)}function rn(n){console.warn("Unhandled rejection: "+(n.stack||n))}function on(n){return new U(Jn,!1,n)}function un(n,t){var e=at;return function(){var r=$(),i=at;try{return i!==e&&(at=e),n.apply(this,arguments)}catch(n){t&&t(n)}finally{i!==e&&(at=i),r&&X()}}}function an(n,t,e,r){var i=at,o=Object.create(i);o.parent=i,o.ref=0,o.global=!1,++i.ref,o.finalize=function(){--this.parent.ref||this.parent.finalize()};var u=cn(o,n,t,e,r);return 0===o.ref&&o.finalize(),u}function cn(n,t,e,r,i){var o=at;try{return n!==o&&(at=n),t(e,r,i)}finally{n!==o&&(at=o)}}function sn(t,e){var r;try{r=e.onuncatched(t)}catch(n){}if(r!==!1)try{var i,o={promise:e,reason:t};if(On.document&&document.createEvent?(i=document.createEvent("Event"),i.initEvent(ht,!0,!0),n(i,o)):On.CustomEvent&&(i=new CustomEvent(ht,{detail:o}),n(i,o)),i&&On.dispatchEvent&&(dispatchEvent(i),!On.PromiseRejectionEvent&&On.onunhandledrejection))try{On.onunhandledrejection(i)}catch(n){}i.defaultPrevented||U.on.error.fire(t,e)}catch(n){}}function fn(n,t){var e=U.reject(n);return t?e.uncaught(t):e}function ln(o,f){function y(){rt.on("versionchange",function(n){n.newVersion>0?console.warn("Another connection wants to upgrade database '"+rt.name+"'. Closing db now to resume the upgrade."):console.warn("Another connection wants to delete database '"+rt.name+"'. Closing db now to resume the delete request."),rt.close()}),rt.on("blocked",function(n){!n.newVersion||n.newVersionn});return a.forEach(function(n){i.push(function(){var r=Gn,i=n._cfg.dbschema;Tn(r,e),Tn(i,e),Gn=rt._dbSchema=i;var o=T(r,i);if(o.add.forEach(function(n){B(e,n[0],n[1].primKey,n[1].indexes)}),o.change.forEach(function(n){if(n.recreate)throw new Wn.Upgrade("Not yet support for changing primary key");var t=e.objectStore(n.name);n.add.forEach(function(n){z(t,n)}),n.change.forEach(function(n){t.deleteIndex(n.name),z(t,n)}),n.del.forEach(function(n){t.deleteIndex(n)})}),n._cfg.contentUpgrade)return u=!0,U.follow(function(){n._cfg.contentUpgrade(t)})}),i.push(function(t){if(!u||!_t){var e=n._cfg.dbschema;q(e,t)}})}),r().then(function(){M(Gn,e)})}function T(n,t){var e={del:[],add:[],change:[]};for(var r in n)t[r]||e.del.push(r);for(r in t){var i=n[r],o=t[r];if(i){var u={name:r,def:o,recreate:!1,del:[],add:[],change:[]};if(i.primKey.src!==o.primKey.src)u.recreate=!0,e.change.push(u);else{var a=i.idxByName,c=o.idxByName;for(var s in a)c[s]||u.del.push(s);for(s in c){var f=a[s],l=c[s];f?f.src!==l.src&&u.change.push(l):u.add.push(l)}(u.del.length>0||u.add.length>0||u.change.length>0)&&e.change.push(u)}}else e.add.push([r,o])}return e}function B(n,t,e,r){var i=n.db.createObjectStore(t,e.keyPath?{keyPath:e.keyPath,autoIncrement:e.auto}:{autoIncrement:e.auto});return r.forEach(function(n){z(i,n)}),i}function M(n,t){jn(n).forEach(function(e){t.db.objectStoreNames.contains(e)||B(t,e,n[e].primKey,n[e].indexes)})}function q(n,t){for(var e=0;e0?n:t}function On(n,t){return Ln.cmp(n,t)}function Pn(n,t){return Ln.cmp(t,n)}function Cn(n,t){return nt?-1:n===t?0:1}function Dn(n,t){return n?t?function(){return n.apply(this,arguments)&&t.apply(this,arguments)}:n:t}function Sn(){if(rt.verno=$n.version/10,rt._dbSchema=Gn={},Qn=u($n.objectStoreNames,0),0!==Qn.length){var n=$n.transaction(kn(Qn),"readonly");Qn.forEach(function(t){for(var e=n.objectStore(t),r=e.keyPath,i=r&&"string"==typeof r&&r.indexOf(".")!==-1,o=new wn(r,r||"",!1,!1,!!e.autoIncrement,r&&"string"!=typeof r,i),u=[],a=0;a0&&(ut=!1),!Ln)throw new Wn.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL (not locally). If using old Safari versions, make sure to include indexedDB polyfill.");var r=ut?Ln.open(o):Ln.open(o,Math.round(10*rt.verno));if(!r)throw new Wn.MissingAPI("IndexedDB API not available");r.onerror=un(yn(e)),r.onblocked=un(Bn),r.onupgradeneeded=un(function(n){if(t=r.transaction,ut&&!rt._allowEmptyDB){r.onerror=gn,t.abort(),r.result.close();var i=Ln.deleteDatabase(o);i.onsuccess=i.onerror=un(function(){e(new Wn.NoSuchDatabase("Database "+o+" doesnt exist"))})}else{t.onerror=un(yn(e));var u=n.oldVersion>Math.pow(2,62)?0:n.oldVersion;C(u/10,t,e,r)}},e),r.onsuccess=un(function(){if(t=null,$n=r.result,gt.push(rt),ut)Sn();else if($n.objectStoreNames.length>0)try{Tn(Gn,$n.transaction(kn($n.objectStoreNames),tt))}catch(n){}$n.onversionchange=un(function(n){rt._vcFired=!0,rt.on("versionchange").fire(n)}),ct||bn(function(n){if(n.indexOf(o)===-1)return n.push(o)}),n()},e)})]).then(function(){return ln.vip(rt.on.ready.fire)}).then(function(){return Zn=!1,rt}).catch(function(n){try{t&&t.abort()}catch(n){}return Zn=!1,rt.close(),Xn=n,fn(Xn,V)}).finally(function(){nt=!0,n()})},this.close=function(){var n=gt.indexOf(rt);if(n>=0&>.splice(n,1),$n){try{$n.close()}catch(n){}$n=null}Vn=!1,Xn=new Wn.DatabaseClosed,Zn&&Fn(Xn),it=new U(function(n){Nn=n}),ot=new U(function(n,t){Fn=t})},this.delete=function(){var n=arguments.length>0;return new U(function(t,e){function r(){rt.close();var n=Ln.deleteDatabase(o);n.onsuccess=un(function(){ct||bn(function(n){var t=n.indexOf(o);if(t>=0)return n.splice(t,1)}),t()}),n.onerror=un(yn(e)),n.onblocked=Bn}if(n)throw new Wn.InvalidArgument("Arguments not allowed in db.delete()");Zn?it.then(r):r()}).uncaught(V)},this.backendDB=function(){return $n},this.isOpen=function(){return null!==$n},this.hasFailed=function(){return null!==Xn},this.dynamicallyOpened=function(){return ut},this.name=o,r(this,"tables",{get:function(){return jn(Yn).map(function(n){return Yn[n]})}}),this.on=R(this,"error","populate","blocked","versionchange",{ready:[I,x]}),this.on.error.subscribe=K("Dexie.on.error",this.on.error.subscribe),this.on.error.unsubscribe=K("Dexie.on.error.unsubscribe",this.on.error.unsubscribe),this.on.ready.subscribe=a(this.on.ready.subscribe,function(n){return function(t,e){ln.vip(function(){nt?(Xn||U.resolve().then(t),e&&n(t)):(n(t),e||n(function n(){rt.on.ready.unsubscribe(t),rt.on.ready.unsubscribe(n)}))})}}),kt(function(){rt.on("populate").fire(rt._createTransaction(et,Qn,Gn)),rt.on("error").fire(new Error)}),this.transaction=function(n,e,r){function i(e){var i=at;e(U.resolve().then(function(){return an(function(){at.transless=at.transless||i;var e=rt._createTransaction(n,f,Gn,c);at.trans=e,c?e.idbtrans=c.idbtrans:e.create();var o=f.map(function(n){return Yn[n]});o.push(e);var u;return U.follow(function(){if(u=r.apply(e,o))if("function"==typeof u.next&&"function"==typeof u.throw)u=_n(u);else if("function"==typeof u.then&&!t(u,"_PSD"))throw new Wn.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: "+r.toString())}).uncaught(V).then(function(){return c&&e._resolve(),e._completion}).then(function(){return u}).catch(function(n){return e._reject(n),fn(n)})})}))}var o=arguments.length;if(o<2)throw new Wn.InvalidArgument("Too few arguments");for(var u=new Array(o-1);--o;)u[o-1]=arguments[o];r=u.pop();var a=w(u),c=at.trans;c&&c.db===rt&&n.indexOf("!")===-1||(c=null);var s=n.indexOf("?")!==-1;n=n.replace("!","").replace("?","");try{var f=a.map(function(n){var t=n instanceof W?n.name:n;if("string"!=typeof t)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return t});if("r"==n||n==tt)n=tt;else{if("rw"!=n&&n!=et)throw new Wn.InvalidArgument("Invalid transaction mode: "+n);n=et}if(c){if(c.mode===tt&&n===et){if(!s)throw new Wn.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");c=null}c&&f.forEach(function(n){if(c&&c.storeNames.indexOf(n)===-1){if(!s)throw new Wn.SubTransaction("Table "+n+" not included in parent transaction.");c=null}})}}catch(n){return c?c._promise(null,function(t,e){e(n)}):fn(n,V)}return c?c._promise(n,i,"lock"):rt._whenReady(i)},this.table=function(n){if(Et&&ut)return new H(n);if(!t(Yn,n))throw new Wn.InvalidTable("Table "+n+" does not exist");return Yn[n]},e(W.prototype,{_trans:function(n,t,e){var r=at.trans;return r&&r.db===rt?r._promise(n,t,e):L(n,[this.name],t)},_idbstore:function(n,t,e){function r(n,e,r){t(n,e,r.idbtrans.objectStore(o),r)}if(Et)return new U(t);var i=at.trans,o=this.name;return i&&i.db===rt?i._promise(n,r,e):L(n,[this.name],r)},get:function(n,t){var e=this;return this._idbstore(tt,function(t,r,i){Et&&t(e.schema.instanceTemplate);var o=i.get(n);o.onerror=yn(r),o.onsuccess=un(function(){t(e.hook.reading.fire(o.result))},r)}).then(t)},where:function(n){return new Y(this,n)},count:function(n){return this.toCollection().count(n)},offset:function(n){return this.toCollection().offset(n)},limit:function(n){return this.toCollection().limit(n)},reverse:function(){return this.toCollection().reverse()},filter:function(n){return this.toCollection().and(n)},each:function(n){return this.toCollection().each(n)},toArray:function(n){return this.toCollection().toArray(n)},orderBy:function(n){return new this._collClass(new Y(this,n))},toCollection:function(){return new this._collClass(new Y(this))},mapToClass:function(n,e){this.schema.mappedClass=n;var r=Object.create(n.prototype);e&&dn(r,e),this.schema.instanceTemplate=r;var i=function(e){if(!e)return e;var r=Object.create(n.prototype);for(var i in e)if(t(e,i))try{r[i]=e[i]}catch(n){}return r};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=i,this.hook("reading",i),n},defineClass:function(n){return this.mapToClass(ln.defineClass(n),n)}}),i(H).from(W).extend({bulkDelete:function(n){return this.hook.deleting.fire===x?this._idbstore(et,function(t,e,r,i){t(J(r,i,n,!1,x))}):this.where(":id").anyOf(n).delete().then(function(){})},bulkPut:function(n,t){var e=this;return this._idbstore(et,function(r,i,o){if(!o.keyPath&&!e.schema.primKey.auto&&!t)throw new Wn.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument");if(o.keyPath&&t)throw new Wn.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(t&&t.length!==n.length)throw new Wn.InvalidArgument("Arguments objects and keys must have the same length");if(0===n.length)return r();var u,a,c=function(n){0===s.length?r(n):i(new F(e.name+".bulkPut(): "+s.length+" of "+f+" operations failed",s))},s=[],f=n.length,h=e;if(e.hook.creating.fire===x&&e.hook.updating.fire===x){a=G(s);for(var d=0,p=n.length;d=0;--i){var o=y[i];(null==o||m[o])&&(e.push(n[i]),t&&r.push(o),null!=o&&(m[o]=null))}return e.reverse(),t&&r.reverse(),h.bulkAdd(e,r)}).then(function(n){var t=y[y.length-1];return null!=t?t:n}):h.bulkAdd(n);g.then(c).catch(F,function(n){s=s.concat(n.failures),c()}).catch(i)}},"locked")},bulkAdd:function(n,t){var e=this,r=this.hook.creating.fire;return this._idbstore(et,function(i,o,u,a){function c(n){0===h.length?i(n):o(new F(e.name+".bulkAdd(): "+h.length+" of "+y+" operations failed",h))}if(!u.keyPath&&!e.schema.primKey.auto&&!t)throw new Wn.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument");if(u.keyPath&&t)throw new Wn.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(t&&t.length!==n.length)throw new Wn.InvalidArgument("Arguments objects and keys must have the same length");if(0===n.length)return i();var s,f,l,h=[],y=n.length;if(r!==x){var m,b=u.keyPath;f=G(h,null,!0),l=pn(null),d(function(){for(var e=0,i=n.length;e0&&!this._locked();){var n=this._blockedFuncs.shift();try{n()}catch(n){}}return this},_locked:function(){return this._reculock&&at.lockOwnerFor!==this},create:function(n){var t=this;if(s(!this.idbtrans),!n&&!$n)switch(Xn&&Xn.name){case"DatabaseClosedError":throw new Wn.DatabaseClosed(Xn);case"MissingAPIError":throw new Wn.MissingAPI(Xn.message,Xn);default:throw new Wn.OpenFailed(Xn)}if(!this.active)throw new Wn.TransactionInactive;return s(null===this._completion._state),n=this.idbtrans=n||$n.transaction(kn(this.storeNames),this.mode),n.onerror=un(function(e){gn(e),t._reject(n.error)}),n.onabort=un(function(n){gn(n),t.active&&t._reject(new Wn.Abort),t.active=!1,t.on("abort").fire(n)}),n.oncomplete=un(function(){t.active=!1,t._resolve()}),this},_promise:function(n,t,e){var r=this;return an(function(){var i;return r._locked()?i=new U(function(i,o){r._blockedFuncs.push(function(){r._promise(n,t,e).then(i,o)})}):(i=r.active?new U(function(i,o){if(n===et&&r.mode!==et)throw new Wn.ReadOnly("Transaction is readonly");!r.idbtrans&&n&&r.create(),e&&r._lock(),t(i,o,r)}):fn(new Wn.TransactionInactive),r.active&&e&&i.finally(function(){ +r._unlock()})),i._lib=!0,i.uncaught(V)})},abort:function(){this.active&&this._reject(new Wn.Abort),this.active=!1},tables:{get:K("Transaction.tables",function(){return l(this.storeNames,function(n){return[n,Yn[n]]})},"Use db.tables()")},complete:K("Transaction.complete()",function(n){return this.on("complete",n)}),error:K("Transaction.error()",function(n){return this.on("error",n)}),table:K("Transaction.table()",function(n){if(this.storeNames.indexOf(n)===-1)throw new Wn.InvalidTable("Table "+n+" not in transaction");return Yn[n]})}),e(Y.prototype,function(){function n(n,t,e){var r=n instanceof Y?new n._ctx.collClass(n):n;return r._ctx.error=e?new e(t):new TypeError(t),r}function t(n){return new n._ctx.collClass(n,function(){return Hn.only("")}).limit(0)}function e(n){return"next"===n?function(n){return n.toUpperCase()}:function(n){return n.toLowerCase()}}function r(n){return"next"===n?function(n){return n.toLowerCase()}:function(n){return n.toUpperCase()}}function i(n,t,e,r,i,o){for(var u=Math.min(n.length,r.length),a=-1,c=0;c=0?n.substr(0,a)+t[a]+e.substr(a+1):null;i(n[c],s)<0&&(a=c)}return u0)&&(a=s)}return t(null!==a?function(){n.continue(a+p)}:e),!1}),m}return{between:function(e,r,i,o){i=i!==!1,o=o===!0;try{return cn(e,r)>0||0===cn(e,r)&&(i||o)&&(!i||!o)?t(this):new this._ctx.collClass(this,function(){return Hn.bound(e,r,!i,!o)})}catch(t){return n(this,yt)}},equals:function(n){return new this._ctx.collClass(this,function(){return Hn.only(n)})},above:function(n){return new this._ctx.collClass(this,function(){return Hn.lowerBound(n,!0)})},aboveOrEqual:function(n){return new this._ctx.collClass(this,function(){return Hn.lowerBound(n)})},below:function(n){return new this._ctx.collClass(this,function(){return Hn.upperBound(n,!0)})},belowOrEqual:function(n){return new this._ctx.collClass(this,function(){return Hn.upperBound(n)})},startsWith:function(t){return"string"!=typeof t?n(this,mt):this.between(t,t+vt,!0,!0)},startsWithIgnoreCase:function(n){return""===n?this.startsWith(n):o(this,function(n,t){return 0===n.indexOf(t[0])},[n],vt)},equalsIgnoreCase:function(n){return o(this,function(n,t){return n===t[0]},[n],"")},anyOfIgnoreCase:function(){var n=_.apply(Kn,arguments);return 0===n.length?t(this):o(this,function(n,t){return t.indexOf(n)!==-1},n,"")},startsWithAnyOfIgnoreCase:function(){var n=_.apply(Kn,arguments);return 0===n.length?t(this):o(this,function(n,t){return t.some(function(t){return 0===n.indexOf(t)})},n,vt)},anyOf:function(){var e=_.apply(Kn,arguments),r=On;try{e.sort(r)}catch(t){return n(this,yt)}if(0===e.length)return t(this);var i=new this._ctx.collClass(this,function(){return Hn.bound(e[0],e[e.length-1])});i._ondirectionchange=function(n){r="next"===n?On:Pn,e.sort(r)};var o=0;return i._addAlgorithm(function(n,t,i){for(var u=n.key;r(u,e[o])>0;)if(++o,o===e.length)return t(i),!1;return 0===r(u,e[o])||(t(function(){n.continue(e[o])}),!1)}),i},notEqual:function(n){return this.inAnyRange([[-(1/0),n],[n,pt]],{includeLowers:!1,includeUppers:!1})},noneOf:function(){var t=_.apply(Kn,arguments);if(0===t.length)return new this._ctx.collClass(this);try{t.sort(On)}catch(t){return n(this,yt)}var e=t.reduce(function(n,t){return n?n.concat([[n[n.length-1][1],t]]):[[-(1/0),t]]},null);return e.push([t[t.length-1],pt]),this.inAnyRange(e,{includeLowers:!1,includeUppers:!1})},inAnyRange:function(e,r){function i(n,t){for(var e=0,r=n.length;e0){i[0]=sn(i[0],t[0]),i[1]=hn(i[1],t[1]);break}}return e===r&&n.push(t),n}function o(n,t){return l(n[0],t[0])}function u(n){return!d(n)&&!v(n)}var a=this._ctx;if(0===e.length)return t(this);if(!e.every(function(n){return void 0!==n[0]&&void 0!==n[1]&&On(n[0],n[1])<=0}))return n(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Wn.InvalidArgument);var c,s=!r||r.includeLowers!==!1,f=r&&r.includeUppers===!0,l=On;try{c=e.reduce(i,[]),c.sort(o)}catch(t){return n(this,yt)}var h=0,d=f?function(n){return On(n,c[h][1])>0}:function(n){return On(n,c[h][1])>=0},v=s?function(n){return Pn(n,c[h][0])>0}:function(n){return Pn(n,c[h][0])>=0},p=d,y=new a.collClass(this,function(){return Hn.bound(c[0][0],c[c.length-1][1],!s,!f)});return y._ondirectionchange=function(n){"next"===n?(p=d,l=On):(p=v,l=Pn),c.sort(o)},y._addAlgorithm(function(n,t,e){for(var r=n.key;p(r);)if(++h,h===c.length)return t(e),!1;return!!u(r)||0!==cn(r,c[h][1])&&0!==cn(r,c[h][0])&&(t(function(){l===On?n.continue(c[h][0]):n.continue(c[h][1])}),!1)}),y},startsWithAnyOf:function(){var e=_.apply(Kn,arguments);return e.every(function(n){return"string"==typeof n})?0===e.length?t(this):this.inAnyRange(e.map(function(n){return[n,n+vt]})):n(this,"startsWithAnyOf() only works with strings")}}}),e($.prototype,function(){function e(n,t){n.filter=Dn(n.filter,t)}function r(n,t,e){var r=n.replayFilter;n.replayFilter=r?function(){return Dn(r(),t())}:t,n.justLimit=e&&!r}function i(n,t){n.isMatch=Dn(n.isMatch,t)}function o(n,t){if(n.isPrimKey)return t;var e=n.table.schema.idxByName[n.index];if(!e)throw new Wn.Schema("KeyPath "+n.index+" on object store "+t.name+" is not indexed");return t.index(e.name)}function u(n,t){var e=o(n,t);return n.keysOnly&&"openKeyCursor"in e?e.openKeyCursor(n.range||null,n.dir+n.unique):e.openCursor(n.range||null,n.dir+n.unique)}function a(n,e,r,i,o){var a=n.replayFilter?Dn(n.filter,n.replayFilter()):n.filter;n.or?function(){function c(){2===++l&&r()}function s(n,r,o){if(!a||a(r,o,c,i)){var u=r.primaryKey.toString();t(f,u)||(f[u]=!0,e(n,r,o))}}var f={},l=0;n.or._iterate(s,c,i,o),rn(u(n,o),n.algorithm,s,c,i,!n.keysOnly&&n.valueMapper)}():rn(u(n,o),Dn(n.algorithm,a),e,r,i,!n.keysOnly&&n.valueMapper)}function c(n){return n.table.schema.instanceTemplate}return{_read:function(n,t){var e=this._ctx;return e.error?e.table._trans(null,function(n,t){t(e.error)}):e.table._idbstore(tt,n).then(t)},_write:function(n){var t=this._ctx;return t.error?t.table._trans(null,function(n,e){e(t.error)}):t.table._idbstore(et,n,"locked")},_addAlgorithm:function(n){var t=this._ctx;t.algorithm=Dn(t.algorithm,n)},_iterate:function(n,t,e,r){return a(this._ctx,n,t,e,r)},clone:function(t){var e=Object.create(this.constructor.prototype),r=Object.create(this._ctx);return t&&n(r,t),e._ctx=r,e},raw:function(){return this._ctx.valueMapper=null,this},each:function(n){var t=this._ctx;if(Et){var e=c(t),r=t.table.schema.primKey.keyPath,i=v(e,t.index?t.table.schema.idxByName[t.index].keyPath:r),o=v(e,r);n(e,{key:i,primaryKey:o})}return this._read(function(e,r,i){a(t,n,e,r,i)})},count:function(n){if(Et)return U.resolve(0).then(n);var t=this._ctx;if(X(t,!0))return this._read(function(n,e,r){var i=o(t,r),u=t.range?i.count(t.range):i.count();u.onerror=yn(e),u.onsuccess=function(e){n(Math.min(e.target.result,t.limit))}},n);var e=0;return this._read(function(n,r,i){a(t,function(){return++e,!1},function(){n(e)},r,i)},n)},sortBy:function(n,t){function e(n,t){return t?e(n[i[t]],t-1):n[o]}function r(n,t){var r=e(n,u),i=e(t,u);return ri?a:0}var i=n.split(".").reverse(),o=i[0],u=i.length-1,a="next"===this._ctx.dir?1:-1;return this.toArray(function(n){return n.sort(r)}).then(t)},toArray:function(n){var t=this._ctx;return this._read(function(n,e,r){if(Et&&n([c(t)]),qn&&"next"===t.dir&&X(t,!0)&&t.limit>0){var i=t.table.hook.reading.fire,u=o(t,r),s=t.limit<1/0?u.getAll(t.range,t.limit):u.getAll(t.range);s.onerror=yn(e),s.onsuccess=i===k?vn(n):un(vn(function(t){try{n(t.map(i))}catch(n){e(n)}}))}else{var f=[];a(t,function(n){f.push(n)},function(){n(f)},e,r)}},n)},offset:function(n){var t=this._ctx;return n<=0?this:(t.offset+=n,X(t)?r(t,function(){var t=n;return function(n,e){return 0===t||(1===t?(--t,!1):(e(function(){n.advance(t),t=0}),!1))}}):r(t,function(){var t=n;return function(){return--t<0}}),this)},limit:function(n){return this._ctx.limit=Math.min(this._ctx.limit,n),r(this._ctx,function(){var t=n;return function(n,e,r){return--t<=0&&e(r),t>=0}},!0),this},until:function(n,t){var r=this._ctx;return Et&&n(c(r)),e(this._ctx,function(e,r,i){return!n(e.value)||(r(i),t)}),this},first:function(n){return this.limit(1).toArray(function(n){return n[0]}).then(n)},last:function(n){return this.reverse().first(n)},filter:function(n){return Et&&n(c(this._ctx)),e(this._ctx,function(t){return n(t.value)}),i(this._ctx,n),this},and:function(n){return this.filter(n)},or:function(n){return new Y(this._ctx.table,n,this)},reverse:function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},desc:function(){return this.reverse()},eachKey:function(n){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each(function(t,e){n(e.key,e)})},eachUniqueKey:function(n){return this._ctx.unique="unique",this.eachKey(n)},eachPrimaryKey:function(n){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each(function(t,e){n(e.primaryKey,e)})},keys:function(n){var t=this._ctx;t.keysOnly=!t.isMatch;var e=[];return this.each(function(n,t){e.push(t.key)}).then(function(){return e}).then(n)},primaryKeys:function(n){var t=this._ctx;if(qn&&"next"===t.dir&&X(t,!0)&&t.limit>0)return this._read(function(n,e,r){var i=o(t,r),u=t.limit<1/0?i.getAllKeys(t.range,t.limit):i.getAllKeys(t.range);u.onerror=yn(e),u.onsuccess=vn(n)}).then(n);t.keysOnly=!t.isMatch;var e=[];return this.each(function(n,t){e.push(t.primaryKey)}).then(function(){return e}).then(n)},uniqueKeys:function(n){return this._ctx.unique="unique",this.keys(n)},firstKey:function(n){return this.limit(1).keys(function(n){return n[0]}).then(n)},lastKey:function(n){return this.reverse().firstKey(n)},distinct:function(){var n=this._ctx,r=n.index&&n.table.schema.idxByName[n.index];if(!r||!r.multi)return this;var i={};return e(this._ctx,function(n){var e=n.primaryKey.toString(),r=t(i,e);return i[e]=!0,!r}),this}}}),i(Z).from($).extend({modify:function(e){var r=this,i=this._ctx,o=i.table.hook,u=o.updating.fire,a=o.deleting.fire;return Et&&"function"==typeof e&&e.call({value:i.table.schema.instanceTemplate},i.table.schema.instanceTemplate),this._write(function(i,o,c,s){function f(n,e){function r(n){return O.push(n),P.push(i.primKey),h(),!0}C=e.primaryKey;var i={primKey:e.primaryKey,value:n,onsuccess:null,onerror:null};if(y.call(i,n,i)!==!1){var o=!t(i,"value");++E,d(function(){var n=o?e.delete():e.update(i.value);n._hookCtx=i,n.onerror=mn(r),n.onsuccess=pn(function(){++j,h()})},r)}else i.onsuccess&&i.onsuccess(i.value)}function l(n){return n&&(O.push(n),P.push(C)),o(new N("Error modifying one or more objects",O,j,P))}function h(){A&&j+O.length===E&&(O.length>0?l():i(j))}var y;if("function"==typeof e)y=u===x&&a===x?e:function(n){var r=g(n);if(e.call(this,n,this)===!1)return!1;if(t(this,"value")){var i=b(r,this.value),o=u.call(this,i,this.primKey,r,s);o&&(n=this.value,jn(o).forEach(function(t){p(n,t,o[t])}))}else a.call(this,this.primKey,n,s)};else if(u===x){var _=jn(e),w=_.length;y=function(n){for(var t=!1,r=0;r ErrorName + \"Error\"}\nexport var errnames = errorList.reduce(function (obj, name) {\n return obj[name] = name + \"Error\", obj;\n}, {});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nvar BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce(function (obj, name) {\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError(msgOrInner, inner) {\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = msgOrInner;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = msgOrInner.name + ' ' + msgOrInner.message;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name] = DexieError;\n return obj;\n}, {});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce(function (obj, name) {\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError(domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", { get: function () {\n return this.inner.stack;\n } });\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce(function (obj, name) {\n if ([\"Syntax\", \"Type\", \"Range\"].indexOf(name) === -1) obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;","import { keys, isArray, asap } from './utils';\nimport { nop, mirror, reverseStoppableEventChain } from './chaining-functions';\nimport { exceptions } from './errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length,\n args = new Array(i - 1);\n while (--i) {\n args[i - 1] = arguments[i];\n }evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof eventName === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n\n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n\n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) {\n return fn !== cb;\n });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length,\n args = new Array(i);\n while (i--) {\n args[i] = arguments[i];\n } // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}","import { doFakeAutoComplete, tryCatch, props, setProp, _global, getPropertyDescriptor, getArrayOf, extend } from './utils';\nimport { reverseStoppableEventChain, nop, callBoth, mirror } from './chaining-functions';\nimport Events from './Events';\nimport { debug, prettyStack, getErrorWithStack, deprecated } from './debug';\n\n//\n// Promise Class for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// Modifications needed to be done to support indexedDB because it wont accept setTimeout()\n// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) .\n// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45\n//\n// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since\n// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick\n// engine that is used instead of setImmediate() or setTimeout().\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Async static context support (Promise.PSD)\n// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nvar LONG_STACKS_CLIP_LIMIT = 100,\n\n// When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \nMAX_LONG_STACKS = 20,\n stack_being_generated = false;\n\n/* The default \"nextTick\" function used only for the very first promise in a promise chain.\r\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\r\n emulated in this module. For indexedDB compatibility, this means that every method needs to \r\n execute at least one promise before doing an indexedDB operation. Dexie will always call \r\n db.ready().then() for every operation to make sure the indexedDB event is started in an\r\n emulated micro tick.\r\n*/\nvar schedulePhysicalTick = _global.setImmediate ?\n// setImmediate supported. Those modern platforms also supports Function.bind().\nsetImmediate.bind(null, physicalTick) : _global.MutationObserver ?\n// MutationObserver supported\nfunction () {\n var hiddenDiv = document.createElement(\"div\");\n new MutationObserver(function () {\n physicalTick();\n hiddenDiv = null;\n }).observe(hiddenDiv, { attributes: true });\n hiddenDiv.setAttribute('i', '1');\n} :\n// No support for setImmediate or MutationObserver. No worry, setTimeout is only called\n// once time. Every tick that follows will be our emulated micro tick.\n// Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug \nfunction () {\n setTimeout(physicalTick, 0);\n};\n\n// Confifurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler (myFuncThatThrows exception)!\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true,\n // True when NOT in a virtual microTick.\nneedsNewPhysicalTick = true,\n // True when a push to microtickQueue must also schedulePhysicalTick()\nunhandledErrors = [],\n // Rejected promises that has occured. Used for firing unhandledrejection.\nrejectingErrors = [],\n // Tracks if errors are being re-rejected during onRejected callback.\ncurrentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n\nexport var globalPSD = {\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n //env: null, // Will be set whenever leaving a scope using wrappers.snapshot()\n finalize: function () {\n this.unhandleds.forEach(function (uh) {\n try {\n globalError(uh[0], uh[1]);\n } catch (e) {}\n });\n }\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\n// Wrappers are not being used yet. Their framework is functioning and can be used\n// to replace environment during a PSD scope (a.k.a. 'zone').\n/* **KEEP** export var wrappers = (() => {\r\n var wrappers = [];\r\n\r\n return {\r\n snapshot: () => {\r\n var i = wrappers.length,\r\n result = new Array(i);\r\n while (i--) result[i] = wrappers[i].snapshot();\r\n return result;\r\n },\r\n restore: values => {\r\n var i = wrappers.length;\r\n while (i--) wrappers[i].restore(values[i]);\r\n },\r\n wrap: () => wrappers.map(w => w.wrap()),\r\n add: wrapper => {\r\n wrappers.push(wrapper);\r\n }\r\n };\r\n})();\r\n*/\n\nexport default function Promise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');\n this._listeners = [];\n this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.\n\n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = this._PSD = PSD;\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n linkToPreviousPromise(this, currentFulfiller);\n }\n\n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n\n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\nprops(Promise.prototype, {\n\n then: function (onFulfilled, onRejected) {\n var _this = this;\n\n var rv = new Promise(function (resolve, reject) {\n propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject));\n });\n debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this);\n return rv;\n },\n\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected));\n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, function (err) {\n return (\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err)\n );\n }) : this.then(null, function (err) {\n return (\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err)\n );\n });\n },\n\n finally: function (onFinally) {\n return this.then(function (value) {\n onFinally();\n return value;\n }, function (err) {\n onFinally();\n return PromiseReject(err);\n });\n },\n\n // Deprecate in next major. Needed only for db.on.error.\n uncaught: function (uncaughtHandler) {\n var _this2 = this;\n\n // Be backward compatible and use \"onuncatched\" as the event name on this.\n // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops.\n this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler);\n // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not\n // a previous promise. Reason: the prevous promise may lack onuncatched handler. \n if (this._state === false && unhandledErrors.indexOf(this) === -1) {\n // Replace unhandled error's destinaion promise with this one!\n unhandledErrors.some(function (p, i, l) {\n return p._value === _this2._value && (l[i] = _this2);\n });\n // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could\n // take away this piece of code as well as the onuncatched and uncaught() method.\n }\n return this;\n },\n\n stack: {\n get: function () {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack(this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n }\n});\n\nfunction Listener(onFulfilled, onRejected, resolve, reject) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = PSD;\n}\n\n// Promise Static Properties\nprops(Promise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like.\n return new Promise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach(function (a, i) {\n return Promise.resolve(a).then(function (x) {\n values[i] = x;\n if (! --remaining) resolve(values);\n }, reject);\n });\n });\n },\n\n resolve: function (value) {\n if (value instanceof Promise) return value;\n if (value && typeof value.then === 'function') return new Promise(function (resolve, reject) {\n value.then(resolve, reject);\n });\n return new Promise(INTERNAL, true, value);\n },\n\n reject: PromiseReject,\n\n race: function () {\n var values = getArrayOf.apply(null, arguments);\n return new Promise(function (resolve, reject) {\n values.map(function (value) {\n return Promise.resolve(value).then(resolve, reject);\n });\n });\n },\n\n PSD: {\n get: function () {\n return PSD;\n },\n set: function (value) {\n return PSD = value;\n }\n },\n\n newPSD: newScope,\n\n usePSD: usePSD,\n\n scheduler: {\n get: function () {\n return asap;\n },\n set: function (value) {\n asap = value;\n }\n },\n\n rejectionMapper: {\n get: function () {\n return rejectionMapper;\n },\n set: function (value) {\n rejectionMapper = value;\n } // Map reject failures\n },\n\n follow: function (fn) {\n return new Promise(function (resolve, reject) {\n return newScope(function (resolve, reject) {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n var _this3 = this;\n\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(function () {\n _this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, resolve, reject);\n });\n },\n\n on: Events(null, { \"error\": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler\n })\n\n});\n\nvar PromiseOnError = Promise.on.error;\nPromiseOnError.subscribe = deprecated(\"Promise.on('error')\", PromiseOnError.subscribe);\nPromiseOnError.unsubscribe = deprecated(\"Promise.on('error').unsubscribe\", PromiseOnError.unsubscribe);\n\n/**\r\n* Take a potentially misbehaving resolver function and make sure\r\n* onFulfilled and onRejected are only called once.\r\n*\r\n* Makes no guarantees about asynchrony.\r\n*/\nfunction executePromiseTask(promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(function (value) {\n if (promise._state !== null) return;\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, function (resolve, reject) {\n value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection(promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () {\n var origProp = getPropertyDescriptor(reason, \"stack\");\n reason._promise = promise;\n setProp(reason, \"stack\", {\n get: function () {\n return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack;\n }\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners(promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(function () {\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject)(promise._value);\n }\n var psd = listener.psd;\n ++psd.ref;\n ++numScheduledCalls;\n asap(callListener, [cb, promise, listener]);\n}\n\nfunction callListener(cb, promise, listener) {\n var outerScope = PSD;\n var psd = listener.psd;\n try {\n if (psd !== outerScope) {\n // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment.\n PSD = psd;\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\n }\n\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n\n // Call callback and resolve our listener with it's return value.\n var value = promise._value,\n ret;\n if (promise._state) {\n ret = cb(value);\n } else {\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore PSD, env and currentFulfiller.\n if (psd !== outerScope) {\n PSD = outerScope;\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment\n }\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --psd.ref || psd.finalize();\n }\n}\n\nfunction getStack(promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n\n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) {\n // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with setImmediate() or setTimeout().\r\n It runs a virtual microtick and executes any callback registered in microtickQueue.\r\n */\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\n\nfunction beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\r\n This can be possible because we only use this internally and\r\n the registered functions are exception-safe (they do try..catch\r\n internally before calling any external method). If registering\r\n functions in the microtickQueue that are not exception-safe, this\r\n would destroy the framework and make it instable. So we don't export\r\n our asap method.\r\n*/\nfunction endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(function (p) {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) {\n finalizers[--i]();\n }\n}\n\nfunction run_at_end_of_this_or_next_physical_tick(fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(function () {\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(function (p) {\n return p._value === promise._value;\n })) unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) {\n if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n }\n}\n\n// By default, log uncaught errors to the console\nfunction defaultErrorHandler(e) {\n console.warn('Unhandled rejection: ' + (e.stack || e));\n}\n\nfunction PromiseReject(reason) {\n return new Promise(INTERNAL, false, reason);\n}\n\nexport function wrap(fn, errorCatcher) {\n var psd = PSD;\n return function () {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n if (outerScope !== psd) {\n // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment\n PSD = psd;\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\n }\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n if (outerScope !== psd) {\n PSD = outerScope;\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment\n }\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\nexport function newScope(fn, a1, a2, a3) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n // **KEEP** psd.env = wrappers.wrap(psd);\n\n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n };\n var rv = usePSD(psd, fn, a1, a2, a3);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\nexport function usePSD(psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n if (psd !== outerScope) {\n // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment.\n PSD = psd;\n // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.\n }\n return fn(a1, a2, a3);\n } finally {\n if (psd !== outerScope) {\n PSD = outerScope;\n // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment.\n }\n }\n}\n\nvar UNHANDLEDREJECTION = \"unhandledrejection\";\n\nfunction globalError(err, promise) {\n var rv;\n try {\n rv = promise.onuncatched(err);\n } catch (e) {}\n if (rv !== false) try {\n var event,\n eventData = { promise: promise, reason: err };\n if (_global.document && document.createEvent) {\n event = document.createEvent('Event');\n event.initEvent(UNHANDLEDREJECTION, true, true);\n extend(event, eventData);\n } else if (_global.CustomEvent) {\n event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData });\n extend(event, eventData);\n }\n if (event && _global.dispatchEvent) {\n dispatchEvent(event);\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\n // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.\n try {\n _global.onunhandledrejection(event);\n } catch (_) {}\n }\n if (!event.defaultPrevented) {\n // Backward compatibility: fire to events registered at Promise.on.error\n Promise.on.error.fire(err, promise);\n }\n } catch (e) {}\n}\n\n/* **KEEP** \r\n\r\nexport function wrapPromise(PromiseClass) {\r\n var proto = PromiseClass.prototype;\r\n var origThen = proto.then;\r\n \r\n wrappers.add({\r\n snapshot: () => proto.then,\r\n restore: value => {proto.then = value;},\r\n wrap: () => patchedThen\r\n });\r\n\r\n function patchedThen (onFulfilled, onRejected) {\r\n var promise = this;\r\n var onFulfilledProxy = wrap(function(value){\r\n var rv = value;\r\n if (onFulfilled) {\r\n rv = onFulfilled(rv);\r\n if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.\r\n }\r\n --PSD.ref || PSD.finalize();\r\n return rv;\r\n });\r\n var onRejectedProxy = wrap(function(err){\r\n promise._$err = err;\r\n var unhandleds = PSD.unhandleds;\r\n var idx = unhandleds.length,\r\n rv;\r\n while (idx--) if (unhandleds[idx]._$err === err) break;\r\n if (onRejected) {\r\n if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled.\r\n rv = onRejected(err);\r\n if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.\r\n } else {\r\n if (idx === -1) unhandleds.push(promise);\r\n rv = PromiseClass.reject(err);\r\n rv._$nointercept = true; // Prohibit eternal loop.\r\n }\r\n --PSD.ref || PSD.finalize();\r\n return rv;\r\n });\r\n \r\n if (this._$nointercept) return origThen.apply(this, arguments);\r\n ++PSD.ref;\r\n return origThen.call(this, onFulfilledProxy, onRejectedProxy);\r\n }\r\n}\r\n\r\n// Global Promise wrapper\r\nif (_global.Promise) wrapPromise(_global.Promise);\r\n\r\n*/\n\ndoFakeAutoComplete(function () {\n // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie.\n asap = function (fn, args) {\n setTimeout(function () {\n fn.apply(null, args);\n }, 0);\n };\n});","import Promise from './Promise';\n\nexport function rejection(err, uncaughtHandler) {\n // Get the call stack and return a rejected promise.\n var rv = Promise.reject(err);\n return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv;\n}","/*\r\n * Dexie.js - a minimalistic wrapper for IndexedDB\r\n * ===============================================\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n */\n\nimport { keys, setProp, isArray, extend, props, derive, slice, override, _global, doFakeAutoComplete, asap, trycatcher, tryCatch, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, getObjectDiff, assert, NO_CHAR_ARRAY, getArrayOf, arrayToObject, hasOwn, flatten } from './utils';\nimport { rejection } from './promise-utils';\nimport { ModifyError, BulkError, errnames, exceptions, fullNameExceptions, mapError } from './errors';\nimport Promise, { wrap, PSD, newScope, usePSD } from './Promise';\nimport Events from './Events';\nimport { nop, mirror, pureFunctionChain, hookCreatingChain, hookUpdatingChain, hookDeletingChain, promisableChain } from './chaining-functions';\nimport * as Debug from './debug';\n\nvar DEXIE_VERSION = '{version}',\n maxString = String.fromCharCode(65535),\n\n// maxKey is an Array if indexedDB implementations supports array keys (not supported by IE,Edge or Safari at the moment)\n// Otherwise maxKey is maxString. This is handy when needing an open upper border without limit.\nmaxKey = function () {\n try {\n IDBKeyRange.only([[]]);return [[]];\n } catch (e) {\n return maxString;\n }\n}(),\n INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\",\n STRING_EXPECTED = \"String expected.\",\n connections = [],\n isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent),\n hasIEDeleteObjectStoreBug = isIEOrEdge,\n hangsOnDeleteLargeKeyRange = isIEOrEdge,\n dexieStackFrameFilter = function (frame) {\n return !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\n};\n\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport default function Dexie(dbName, options) {\n /// Specify only if you wich to control which addons that should run on this instance\n var deps = Dexie.dependencies;\n var opts = extend({\n // Default Options\n addons: Dexie.addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env.\n IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env.\n }, options);\n var addons = opts.addons,\n autoOpen = opts.autoOpen,\n indexedDB = opts.indexedDB,\n IDBKeyRange = opts.IDBKeyRange;\n\n var globalSchema = this._dbSchema = {};\n var versions = [];\n var dbStoreNames = [];\n var allTables = {};\n ///\n var idbdb = null; // Instance of IDBDatabase\n var dbOpenError = null;\n var isBeingOpened = false;\n var openComplete = false;\n var READONLY = \"readonly\",\n READWRITE = \"readwrite\";\n var db = this;\n var dbReadyResolve,\n dbReadyPromise = new Promise(function (resolve) {\n dbReadyResolve = resolve;\n }),\n cancelOpen,\n openCanceller = new Promise(function (_, reject) {\n cancelOpen = reject;\n });\n var autoSchema = true;\n var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),\n hasGetAll;\n\n function init() {\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n db.on(\"versionchange\", function (ev) {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0) console.warn('Another connection wants to upgrade database \\'' + db.name + '\\'. Closing db now to resume the upgrade.');else console.warn('Another connection wants to delete database \\'' + db.name + '\\'. Closing db now to resume the delete request.');\n db.close();\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n db.on(\"blocked\", function (ev) {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn('Dexie.delete(\\'' + db.name + '\\') was blocked');else console.warn('Upgrade \\'' + db.name + '\\' blocked by other connection holding version ' + ev.oldVersion / 10);\n });\n }\n\n //\n //\n //\n // ------------------------- Versioning Framework---------------------------\n //\n //\n //\n\n this.version = function (versionNumber) {\n /// \n /// \n if (idbdb || isBeingOpened) throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n var versionInstance = versions.filter(function (v) {\n return v._cfg.version === versionNumber;\n })[0];\n if (versionInstance) return versionInstance;\n versionInstance = new Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n return versionInstance;\n };\n\n function Version(versionNumber) {\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n this.stores({}); // Derive earlier schemas by default.\n }\n\n extend(Version.prototype, {\n stores: function (stores) {\n /// \n /// Defines the schema for a particular version\n /// \n /// \n /// Example:
\n /// {users: \"id++,first,last,&username,*email\",
\n /// passwords: \"id++,&username\"}
\n ///
\n /// Syntax: {Table: \"[primaryKey][++],[&][*]index1,[&][*]index2,...\"}

\n /// Special characters:
\n /// \"&\" means unique key,
\n /// \"*\" means value is multiEntry,
\n /// \"++\" means auto-increment and only applicable for primary key
\n /// \n this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n var storesSpec = {};\n versions.forEach(function (version) {\n // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n });\n\n var dbschema = this._cfg.dbschema = {};\n this._parseStoresSpec(storesSpec, dbschema);\n // Update the latest schema to this version\n // Update API\n globalSchema = db._dbSchema = dbschema;\n removeTablesApi([allTables, db, Transaction.prototype]);\n setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema);\n dbStoreNames = keys(dbschema);\n return this;\n },\n upgrade: function (upgradeFunction) {\n /// Function that performs upgrading actions.\n var self = this;\n fakeAutoComplete(function () {\n upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear.\n });\n this._cfg.contentUpgrade = upgradeFunction;\n return this;\n },\n _parseStoresSpec: function (stores, outSchema) {\n keys(stores).forEach(function (tableName) {\n if (stores[tableName] !== null) {\n var instanceTemplate = {};\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);\n indexes.forEach(function (idx) {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () {\n return \"\";\n }) : \"\");\n });\n outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);\n }\n });\n }\n });\n\n function runUpgraders(oldVersion, idbtrans, reject) {\n var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);\n trans.create(idbtrans);\n trans._completion.catch(reject);\n var rejectTransaction = trans._reject.bind(trans);\n newScope(function () {\n PSD.trans = trans;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(function (tableName) {\n createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n Promise.follow(function () {\n return db.on.populate.fire(trans);\n }).catch(rejectTransaction);\n } else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);\n });\n }\n\n function updateTablesAndIndexes(oldVersion, trans, idbtrans) {\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n var queue = [];\n var oldVersionStruct = versions.filter(function (version) {\n return version._cfg.version === oldVersion;\n })[0];\n if (!oldVersionStruct) throw new exceptions.Upgrade(\"Dexie specification of currently installed DB version is missing\");\n globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;\n var anyContentUpgraderHasRun = false;\n\n var versToRun = versions.filter(function (v) {\n return v._cfg.version > oldVersion;\n });\n versToRun.forEach(function (version) {\n /// \n queue.push(function () {\n var oldSchema = globalSchema;\n var newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(oldSchema, idbtrans);\n adjustToExistingIndexNames(newSchema, idbtrans);\n globalSchema = db._dbSchema = newSchema;\n var diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(function (tuple) {\n createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(function (change) {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n var store = idbtrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(function (idx) {\n addIndex(store, idx);\n });\n // Update indexes\n change.change.forEach(function (idx) {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(function (idxName) {\n store.deleteIndex(idxName);\n });\n }\n });\n if (version._cfg.contentUpgrade) {\n anyContentUpgraderHasRun = true;\n return Promise.follow(function () {\n version._cfg.contentUpgrade(trans);\n });\n }\n });\n queue.push(function (idbtrans) {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) {\n // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n var newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n });\n });\n\n // Now, create a queue execution engine\n function runQueue() {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve();\n }\n\n return runQueue().then(function () {\n createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n }\n\n function getSchemaDiff(oldSchema, newSchema) {\n var diff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n for (var table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n var oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n var change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (oldDef.primKey.src !== newDef.primKey.src) {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n var oldIndexes = oldDef.idxByName;\n var newIndexes = newDef.idxByName;\n for (var idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n var oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n }\n\n function createTable(idbtrans, tableName, primKey, indexes) {\n /// \n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });\n indexes.forEach(function (idx) {\n addIndex(store, idx);\n });\n return store;\n }\n\n function createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(function (tableName) {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n }\n\n function deleteRemovedTables(newSchema, idbtrans) {\n for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {\n var storeName = idbtrans.db.objectStoreNames[i];\n if (newSchema[storeName] == null) {\n idbtrans.db.deleteObjectStore(storeName);\n }\n }\n }\n\n function addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n }\n\n function dbUncaught(err) {\n return db.on.error.fire(err);\n }\n\n //\n //\n // Dexie Protected API\n //\n //\n\n this._allTables = allTables;\n\n this._tableFactory = function createTable(mode, tableSchema) {\n /// \n if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection);else return new WriteableTable(tableSchema.name, tableSchema);\n };\n\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {\n return new Transaction(mode, storeNames, dbschema, parentTransaction);\n };\n\n /* Generate a temporary transaction when db operations are done outside a transactino scope.\r\n */\n function tempTransaction(mode, storeNames, fn) {\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n if (!openComplete && !PSD.letThrough) {\n if (!isBeingOpened) {\n if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught);\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return dbReadyPromise.then(function () {\n return tempTransaction(mode, storeNames, fn);\n });\n } else {\n var trans = db._createTransaction(mode, storeNames, globalSchema);\n return trans._promise(mode, function (resolve, reject) {\n newScope(function () {\n // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n fn(resolve, reject, trans);\n });\n }).then(function (result) {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n return trans._completion.then(function () {\n return result;\n });\n }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\r\n trans._reject(err);\r\n return rejection(err);\r\n });*/\n }\n }\n\n this._whenReady = function (fn) {\n return new Promise(fake || openComplete || PSD.letThrough ? fn : function (resolve, reject) {\n if (!isBeingOpened) {\n if (!autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n dbReadyPromise.then(function () {\n fn(resolve, reject);\n });\n }).uncaught(dbUncaught);\n };\n\n //\n //\n //\n //\n // Dexie API\n //\n //\n //\n\n this.verno = 0;\n\n this.open = function () {\n if (isBeingOpened || idbdb) return dbReadyPromise.then(function () {\n return dbOpenError ? rejection(dbOpenError, dbUncaught) : db;\n });\n Debug.debug && (openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n isBeingOpened = true;\n dbOpenError = null;\n openComplete = false;\n\n // Function pointers to call when the core opening process completes.\n var resolveDbReady = dbReadyResolve,\n\n // upgradeTransaction to abort on failure.\n upgradeTransaction = null;\n\n return Promise.race([openCanceller, new Promise(function (resolve, reject) {\n doFakeAutoComplete(function () {\n return resolve();\n });\n\n // Make sure caller has specified at least one version\n if (versions.length > 0) autoSchema = false;\n\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI(\"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \" + \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\n\n var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(\"IndexedDB API not available\"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = wrap(eventRejectHandler(reject));\n req.onblocked = wrap(fireOnBlocked);\n req.onupgradeneeded = wrap(function (e) {\n upgradeTransaction = req.transaction;\n if (autoSchema && !db._allowEmptyDB) {\n // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(function () {\n reject(new exceptions.NoSuchDatabase('Database ' + dbName + ' doesnt exist'));\n });\n } else {\n upgradeTransaction.onerror = wrap(eventRejectHandler(reject));\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n runUpgraders(oldVer / 10, upgradeTransaction, reject, req);\n }\n }, reject);\n\n req.onsuccess = wrap(function () {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n idbdb = req.result;\n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n\n if (autoSchema) readGlobalSchema();else if (idbdb.objectStoreNames.length > 0) {\n try {\n adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));\n } catch (e) {\n // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n }\n }\n\n idbdb.onversionchange = wrap(function (ev) {\n db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n\n if (!hasNativeGetDatabaseNames) {\n // Update localStorage with list of database names\n globalDatabaseList(function (databaseNames) {\n if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName);\n });\n }\n\n resolve();\n }, reject);\n })]).then(function () {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n return Dexie.vip(db.on.ready.fire);\n }).then(function () {\n // Resolve the db.open() with the db instance.\n isBeingOpened = false;\n return db;\n }).catch(function (err) {\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch (e) {}\n isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).\n db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.\n dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught().\n }).finally(function () {\n openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n });\n };\n\n this.close = function () {\n var idx = connections.indexOf(db);\n if (idx >= 0) connections.splice(idx, 1);\n if (idbdb) {\n try {\n idbdb.close();\n } catch (e) {}\n idbdb = null;\n }\n autoOpen = false;\n dbOpenError = new exceptions.DatabaseClosed();\n if (isBeingOpened) cancelOpen(dbOpenError);\n // Reset dbReadyPromise promise:\n dbReadyPromise = new Promise(function (resolve) {\n dbReadyResolve = resolve;\n });\n openCanceller = new Promise(function (_, reject) {\n cancelOpen = reject;\n });\n };\n\n this.delete = function () {\n var hasArguments = arguments.length > 0;\n return new Promise(function (resolve, reject) {\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (isBeingOpened) {\n dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n function doDelete() {\n db.close();\n var req = indexedDB.deleteDatabase(dbName);\n req.onsuccess = wrap(function () {\n if (!hasNativeGetDatabaseNames) {\n globalDatabaseList(function (databaseNames) {\n var pos = databaseNames.indexOf(dbName);\n if (pos >= 0) return databaseNames.splice(pos, 1);\n });\n }\n resolve();\n });\n req.onerror = wrap(eventRejectHandler(reject));\n req.onblocked = fireOnBlocked;\n }\n }).uncaught(dbUncaught);\n };\n\n this.backendDB = function () {\n return idbdb;\n };\n\n this.isOpen = function () {\n return idbdb !== null;\n };\n this.hasFailed = function () {\n return dbOpenError !== null;\n };\n this.dynamicallyOpened = function () {\n return autoSchema;\n };\n\n //\n // Properties\n //\n this.name = dbName;\n\n // db.tables - an array of all Table instances.\n setProp(this, \"tables\", {\n get: function () {\n /// \n return keys(allTables).map(function (name) {\n return allTables[name];\n });\n }\n });\n\n //\n // Events\n //\n this.on = Events(this, \"error\", \"populate\", \"blocked\", \"versionchange\", { ready: [promisableChain, nop] });\n this.on.error.subscribe = Debug.deprecated(\"Dexie.on.error\", this.on.error.subscribe);\n this.on.error.unsubscribe = Debug.deprecated(\"Dexie.on.error.unsubscribe\", this.on.error.unsubscribe);\n\n this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {\n return function (subscriber, bSticky) {\n Dexie.vip(function () {\n if (openComplete) {\n // Database already open. Call subscriber asap.\n if (!dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n };\n });\n\n fakeAutoComplete(function () {\n db.on(\"populate\").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema));\n db.on(\"error\").fire(new Error());\n });\n\n this.transaction = function (mode, tableInstances, scopeFunc) {\n /// \n ///\n /// \n /// \"r\" for readonly, or \"rw\" for readwrite\n /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction\n /// Function to execute with transaction\n\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) {\n args[i - 1] = arguments[i];\n } // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n var parentTransaction = PSD.trans;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;\n var onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n var storeNames = tables.map(function (table) {\n var storeName = table instanceof Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode == READONLY) mode = READONLY;else if (mode == \"rw\" || mode == READWRITE) mode = READWRITE;else throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && mode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null;\n } else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(function (storeName) {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null;\n } else throw new exceptions.SubTransaction(\"Table \" + storeName + \" not included in parent transaction.\");\n }\n });\n }\n }\n } catch (e) {\n return parentTransaction ? parentTransaction._promise(null, function (_, reject) {\n reject(e);\n }) : rejection(e, dbUncaught);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n return parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, \"lock\") : db._whenReady(enterTransactionScope);\n\n function enterTransactionScope(resolve) {\n var parentPSD = PSD;\n resolve(Promise.resolve().then(function () {\n return newScope(function () {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n PSD.transless = PSD.transless || parentPSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n PSD.trans = trans;\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.\n }\n\n // Provide arguments to the scope function (for backward compatibility)\n var tableArgs = storeNames.map(function (name) {\n return allTables[name];\n });\n tableArgs.push(trans);\n\n var returnValue;\n return Promise.follow(function () {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func.\n if (returnValue) {\n if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) {\n throw new exceptions.IncompatiblePromise(\"Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: \" + scopeFunc.toString());\n }\n }\n }).uncaught(dbUncaught).then(function () {\n if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion.\n return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well.\n }).then(function () {\n return returnValue;\n }).catch(function (e) {\n //reject(e);\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n //});\n });\n }));\n }\n };\n\n this.table = function (tableName) {\n /// \n if (fake && autoSchema) return new WriteableTable(tableName);\n if (!hasOwn(allTables, tableName)) {\n throw new exceptions.InvalidTable('Table ' + tableName + ' does not exist');\n }\n return allTables[tableName];\n };\n\n //\n //\n //\n // Table Class\n //\n //\n //\n function Table(name, tableSchema, collClass) {\n /// \n this.name = name;\n this.schema = tableSchema;\n this.hook = allTables[name] ? allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n this._collClass = collClass || Collection;\n }\n\n props(Table.prototype, {\n\n //\n // Table Protected Methods\n //\n\n _trans: function getTransaction(mode, fn, writeLocked) {\n var trans = PSD.trans;\n return trans && trans.db === db ? trans._promise(mode, fn, writeLocked) : tempTransaction(mode, [this.name], fn);\n },\n _idbstore: function getIDBObjectStore(mode, fn, writeLocked) {\n if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion.\n var trans = PSD.trans,\n tableName = this.name;\n function supplyIdbStore(resolve, reject, trans) {\n fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);\n }\n return trans && trans.db === db ? trans._promise(mode, supplyIdbStore, writeLocked) : tempTransaction(mode, [this.name], supplyIdbStore);\n },\n\n //\n // Table Public Methods\n //\n get: function (key, cb) {\n var self = this;\n return this._idbstore(READONLY, function (resolve, reject, idbstore) {\n fake && resolve(self.schema.instanceTemplate);\n var req = idbstore.get(key);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(self.hook.reading.fire(req.result));\n }, reject);\n }).then(cb);\n },\n where: function (indexName) {\n return new WhereClause(this, indexName);\n },\n count: function (cb) {\n return this.toCollection().count(cb);\n },\n offset: function (offset) {\n return this.toCollection().offset(offset);\n },\n limit: function (numRows) {\n return this.toCollection().limit(numRows);\n },\n reverse: function () {\n return this.toCollection().reverse();\n },\n filter: function (filterFunction) {\n return this.toCollection().and(filterFunction);\n },\n each: function (fn) {\n return this.toCollection().each(fn);\n },\n toArray: function (cb) {\n return this.toCollection().toArray(cb);\n },\n orderBy: function (index) {\n return new this._collClass(new WhereClause(this, index));\n },\n\n toCollection: function () {\n return new this._collClass(new WhereClause(this));\n },\n\n mapToClass: function (constructor, structure) {\n /// \n /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making\n /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.\n /// \n /// Constructor function representing the class.\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], password}\n this.schema.mappedClass = constructor;\n var instanceTemplate = Object.create(constructor.prototype);\n if (structure) {\n // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.\n applyStructure(instanceTemplate, structure);\n }\n this.schema.instanceTemplate = instanceTemplate;\n\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n var readHook = function (obj) {\n if (!obj) return obj; // No valid object. (Value is null). Return as is.\n // Create a new object that derives from constructor:\n var res = Object.create(constructor.prototype);\n // Clone members:\n for (var m in obj) {\n if (hasOwn(obj, m)) try {\n res[m] = obj[m];\n } catch (_) {}\n }return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n },\n defineClass: function (structure) {\n /// \n /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database\n /// as well as making it possible to extend the prototype of the returned constructor function.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n return this.mapToClass(Dexie.defineClass(structure), structure);\n }\n });\n\n //\n //\n //\n // WriteableTable Class (extends Table)\n //\n //\n //\n function WriteableTable(name, tableSchema, collClass) {\n Table.call(this, name, tableSchema, collClass || WriteableCollection);\n }\n\n function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) {\n errorList.push(e);\n done && done();\n });\n }\n\n function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {\n // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],\n // else keysOrTuples must be just an array of keys: [key1, key2, ...].\n return new Promise(function (resolve, reject) {\n var len = keysOrTuples.length,\n lastItem = len - 1;\n if (len === 0) return resolve();\n if (!hasDeleteHook) {\n for (var i = 0; i < len; ++i) {\n var req = idbstore.delete(keysOrTuples[i]);\n req.onerror = wrap(eventRejectHandler(reject));\n if (i === lastItem) req.onsuccess = wrap(function () {\n return resolve();\n });\n }\n } else {\n var hookCtx,\n errorHandler = hookedEventRejectHandler(reject),\n successHandler = hookedEventSuccessHandler(null);\n tryCatch(function () {\n for (var i = 0; i < len; ++i) {\n hookCtx = { onsuccess: null, onerror: null };\n var tuple = keysOrTuples[i];\n deletingHook.call(hookCtx, tuple[0], tuple[1], trans);\n var req = idbstore.delete(tuple[0]);\n req._hookCtx = hookCtx;\n req.onerror = errorHandler;\n if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve);else req.onsuccess = successHandler;\n }\n }, function (err) {\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n }\n }).uncaught(dbUncaught);\n }\n\n derive(WriteableTable).from(Table).extend({\n bulkDelete: function (keys) {\n if (this.hook.deleting.fire === nop) {\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n resolve(bulkDelete(idbstore, trans, keys, false, nop));\n });\n } else {\n return this.where(':id').anyOf(keys).delete().then(function () {}); // Resolve with undefined.\n }\n },\n bulkPut: function (objects, keys) {\n var _this = this;\n\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys) throw new exceptions.InvalidArgument(\"bulkPut() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys) throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length) throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n var done = function (result) {\n if (errorList.length === 0) resolve(result);else reject(new BulkError(_this.name + '.bulkPut(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));\n };\n var req,\n errorList = [],\n errorHandler,\n numObjs = objects.length,\n table = _this;\n if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) {\n //\n // Standard Bulk (no 'creating' or 'updating' hooks to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n } else {\n var effectiveKeys = keys || idbstore.keyPath && objects.map(function (o) {\n return getByKeyPath(o, idbstore.keyPath);\n });\n // Generate map of {[key]: object}\n var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) {\n return key != null && [key, objects[i]];\n });\n var promise = !effectiveKeys ?\n\n // Auto-incremented key-less objects only without any keys argument.\n table.bulkAdd(objects) :\n\n // Keys provided. Either as inbound in provided objects, or as a keys argument.\n // Begin with updating those that exists in DB:\n table.where(':id').anyOf(effectiveKeys.filter(function (key) {\n return key != null;\n })).modify(function () {\n this.value = objectLookup[this.primKey];\n objectLookup[this.primKey] = null; // Mark as \"don't add this\"\n }).catch(ModifyError, function (e) {\n errorList = e.failures; // No need to concat here. These are the first errors added.\n }).then(function () {\n // Now, let's examine which items didnt exist so we can add them:\n var objsToAdd = [],\n keysToAdd = keys && [];\n // Iterate backwards. Why? Because if same key was used twice, just add the last one.\n for (var i = effectiveKeys.length - 1; i >= 0; --i) {\n var key = effectiveKeys[i];\n if (key == null || objectLookup[key]) {\n objsToAdd.push(objects[i]);\n keys && keysToAdd.push(key);\n if (key != null) objectLookup[key] = null; // Mark as \"dont add again\"\n }\n }\n // The items are in reverse order so reverse them before adding.\n // Could be important in order to get auto-incremented keys the way the caller\n // would expect. Could have used unshift instead of push()/reverse(),\n // but: http://jsperf.com/unshift-vs-reverse\n objsToAdd.reverse();\n keys && keysToAdd.reverse();\n return table.bulkAdd(objsToAdd, keysToAdd);\n }).then(function (lastAddedKey) {\n // Resolve with key of the last object in given arguments to bulkPut():\n var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.\n return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;\n });\n\n promise.then(done).catch(BulkError, function (e) {\n // Concat failure from ModifyError and reject using our 'done' method.\n errorList = errorList.concat(e.failures);\n done();\n }).catch(reject);\n }\n }, \"locked\"); // If called from transaction scope, lock transaction til all steps are done.\n },\n bulkAdd: function (objects, keys) {\n var self = this,\n creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n if (!idbstore.keyPath && !self.schema.primKey.auto && !keys) throw new exceptions.InvalidArgument(\"bulkAdd() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys) throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length) throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n function done(result) {\n if (errorList.length === 0) resolve(result);else reject(new BulkError(self.name + '.bulkAdd(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));\n }\n var req,\n errorList = [],\n errorHandler,\n successHandler,\n numObjs = objects.length;\n if (creatingHook !== nop) {\n //\n // There are subscribers to hook('creating')\n // Must behave as documented.\n //\n var keyPath = idbstore.keyPath,\n hookCtx;\n errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);\n successHandler = hookedEventSuccessHandler(null);\n\n tryCatch(function () {\n for (var i = 0, l = objects.length; i < l; ++i) {\n hookCtx = { onerror: null, onsuccess: null };\n var key = keys && keys[i];\n var obj = objects[i],\n effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,\n keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);\n if (effectiveKey == null && keyToUse != null) {\n if (keyPath) {\n obj = deepClone(obj);\n setByKeyPath(obj, keyPath, keyToUse);\n } else {\n key = keyToUse;\n }\n }\n req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n if (i < l - 1) {\n req.onerror = errorHandler;\n if (hookCtx.onsuccess) req.onsuccess = successHandler;\n }\n }\n }, function (err) {\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n\n req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);\n req.onsuccess = hookedEventSuccessHandler(done);\n } else {\n //\n // Standard Bulk (no 'creating' hook to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n }\n });\n },\n add: function (obj, key) {\n /// \n /// Add an object to the database. In case an object with same primary key already exists, the object will not be added.\n /// \n /// A javascript object to insert\n /// Primary key\n var creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n var hookCtx = { onsuccess: null, onerror: null };\n if (creatingHook !== nop) {\n var effectiveKey = key != null ? key : idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined;\n var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when(\"creating\") to generate the key.\n if (effectiveKey == null && keyToUse != null) {\n // Using \"==\" and \"!=\" to check for either null or undefined!\n if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse);else key = keyToUse;\n }\n }\n try {\n var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n req.onerror = hookedEventRejectHandler(reject);\n req.onsuccess = hookedEventSuccessHandler(function (result) {\n // TODO: Remove these two lines in next major release (2.0?)\n // It's no good practice to have side effects on provided parameters\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, result);\n resolve(result);\n });\n } catch (e) {\n if (hookCtx.onerror) hookCtx.onerror(e);\n throw e;\n }\n });\n },\n\n put: function (obj, key) {\n /// \n /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.\n /// \n /// A javascript object to insert or update\n /// Primary key\n var self = this,\n creatingHook = this.hook.creating.fire,\n updatingHook = this.hook.updating.fire;\n if (creatingHook !== nop || updatingHook !== nop) {\n //\n // People listens to when(\"creating\") or when(\"updating\") events!\n // We must know whether the put operation results in an CREATE or UPDATE.\n //\n return this._trans(READWRITE, function (resolve, reject, trans) {\n // Since key is optional, make sure we get it from obj if not provided\n var effectiveKey = key !== undefined ? key : self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath);\n if (effectiveKey == null) {\n // \"== null\" means checking for either null or undefined.\n // No primary key. Must use add().\n self.add(obj).then(resolve, reject);\n } else {\n // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().\n trans._lock(); // Needed because operation is splitted into modify() and add().\n // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.\n obj = deepClone(obj);\n self.where(\":id\").equals(effectiveKey).modify(function () {\n // Replace extisting value with our object\n // CRUD event firing handled in WriteableCollection.modify()\n this.value = obj;\n }).then(function (count) {\n if (count === 0) {\n // Object's key was not found. Add the object instead.\n // CRUD event firing will be done in add()\n return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key.\n } else {\n return effectiveKey; // Resolve with the provided key.\n }\n }).finally(function () {\n trans._unlock();\n }).then(resolve, reject);\n }\n });\n } else {\n // Use the standard IDB put() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function (ev) {\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);\n resolve(req.result);\n };\n });\n }\n },\n\n 'delete': function (key) {\n /// Primary key of the object to delete\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using WriteableCollection.delete() that will\n // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted.\n return this.where(\":id\").equals(key).delete();\n } else {\n // No one listens. Use standard IDB delete() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.delete(key);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function () {\n resolve(req.result);\n };\n });\n }\n },\n\n clear: function () {\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using WriteableCollection.delete() that will\n // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted.\n return this.toCollection().delete();\n } else {\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.clear();\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function () {\n resolve(req.result);\n };\n });\n }\n },\n\n update: function (keyOrObject, modifications) {\n if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument(\"Modifications must be an object.\");\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n // object to modify. Also modify given object with the modifications:\n keys(modifications).forEach(function (keyPath) {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\"Given object does not contain its primary key\"), dbUncaught);\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n });\n\n //\n //\n //\n // Transaction Class\n //\n //\n //\n function Transaction(mode, storeNames, dbschema, parent) {\n var _this2 = this;\n\n /// \n /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.\n /// \n /// Any of \"readwrite\" or \"readonly\"\n /// Array of table names to operate on\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._tables = null;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._psd = null;\n this._dbschema = dbschema;\n this._resolve = null;\n this._reject = null;\n this._completion = new Promise(function (resolve, reject) {\n _this2._resolve = resolve;\n _this2._reject = reject;\n }).uncaught(dbUncaught);\n\n this._completion.then(function () {\n _this2.on.complete.fire();\n }, function (e) {\n _this2.on.error.fire(e);\n _this2.parent ? _this2.parent._reject(e) : _this2.active && _this2.idbtrans && _this2.idbtrans.abort();\n _this2.active = false;\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n }\n\n props(Transaction.prototype, {\n //\n // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n _lock: function () {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n },\n _unlock: function () {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fn = this._blockedFuncs.shift();\n try {\n fn();\n } catch (e) {}\n }\n }\n return this;\n },\n _locked: function () {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n },\n create: function (idbtrans) {\n var _this3 = this;\n\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);\n idbtrans.onerror = wrap(function (ev) {\n preventDefault(ev); // Prohibit default bubbling to window.error\n _this3._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(function (ev) {\n preventDefault(ev);\n _this3.active && _this3._reject(new exceptions.Abort());\n _this3.active = false;\n _this3.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(function () {\n _this3.active = false;\n _this3._resolve();\n });\n return this;\n },\n _promise: function (mode, fn, bWriteLock) {\n var self = this;\n return newScope(function () {\n var p;\n // Read lock always\n if (!self._locked()) {\n p = self.active ? new Promise(function (resolve, reject) {\n if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly(\"Transaction is readonly\");\n if (!self.idbtrans && mode) self.create();\n if (bWriteLock) self._lock(); // Write lock if write operation is requested\n fn(resolve, reject, self);\n }) : rejection(new exceptions.TransactionInactive());\n if (self.active && bWriteLock) p.finally(function () {\n self._unlock();\n });\n } else {\n // Transaction is write-locked. Wait for mutex.\n p = new Promise(function (resolve, reject) {\n self._blockedFuncs.push(function () {\n self._promise(mode, fn, bWriteLock).then(resolve, reject);\n });\n });\n }\n p._lib = true;\n return p.uncaught(dbUncaught);\n });\n },\n\n //\n // Transaction Public Properties and Methods\n //\n abort: function () {\n this.active && this._reject(new exceptions.Abort());\n this.active = false;\n },\n\n tables: {\n get: Debug.deprecated(\"Transaction.tables\", function () {\n return arrayToObject(this.storeNames, function (name) {\n return [name, allTables[name]];\n });\n }, \"Use db.tables()\")\n },\n\n complete: Debug.deprecated(\"Transaction.complete()\", function (cb) {\n return this.on(\"complete\", cb);\n }),\n\n error: Debug.deprecated(\"Transaction.error()\", function (cb) {\n return this.on(\"error\", cb);\n }),\n\n table: Debug.deprecated(\"Transaction.table()\", function (name) {\n if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable(\"Table \" + name + \" not in transaction\");\n return allTables[name];\n })\n\n });\n\n //\n //\n //\n // WhereClause\n //\n //\n //\n function WhereClause(table, index, orCollection) {\n /// \n /// \n /// \n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n collClass: table._collClass,\n or: orCollection\n };\n }\n\n props(WhereClause.prototype, function () {\n\n // WhereClause private methods\n\n function fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause;\n\n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n }\n\n function emptyCollection(whereClause) {\n return new whereClause._ctx.collClass(whereClause, function () {\n return IDBKeyRange.only(\"\");\n }).limit(0);\n }\n\n function upperFactory(dir) {\n return dir === \"next\" ? function (s) {\n return s.toUpperCase();\n } : function (s) {\n return s.toLowerCase();\n };\n }\n function lowerFactory(dir) {\n return dir === \"next\" ? function (s) {\n return s.toLowerCase();\n } : function (s) {\n return s.toUpperCase();\n };\n }\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1);\n }\n\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n /// \n var upper,\n lower,\n compare,\n upperNeedles,\n lowerNeedles,\n direction,\n nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(function (s) {\n return typeof s === 'string';\n })) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = dir === \"next\" ? simpleCompare : simpleCompareReverse;\n var needleBounds = needles.map(function (needle) {\n return { lower: lower(needle), upper: upper(needle) };\n }).sort(function (a, b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb) {\n return nb.upper;\n });\n lowerNeedles = needleBounds.map(function (nb) {\n return nb.lower;\n });\n direction = dir;\n nextKeySuffix = dir === \"next\" ? \"\" : suffix;\n }\n initDirection(\"next\");\n\n var c = new whereClause._ctx.collClass(whereClause, function () {\n return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix);\n });\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i = firstPossibleNeedle; i < needlesLen; ++i) {\n var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction);\n if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1;else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () {\n cursor.continue(lowestPossibleCasing + nextKeySuffix);\n });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n }\n\n //\n // WhereClause public methods\n //\n return {\n between: function (lower, upper, includeLower, includeUpper) {\n /// \n /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.\n /// \n /// \n /// \n /// Whether items that equals lower should be included. Default true.\n /// Whether items that equals upper should be included. Default false.\n /// \n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if (cmp(lower, upper) > 0 || cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper);\n });\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n },\n equals: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.only(value);\n });\n },\n above: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.lowerBound(value, true);\n });\n },\n aboveOrEqual: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.lowerBound(value);\n });\n },\n below: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.upperBound(value, true);\n });\n },\n belowOrEqual: function (value) {\n return new this._ctx.collClass(this, function () {\n return IDBKeyRange.upperBound(value);\n });\n },\n startsWith: function (str) {\n /// \n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n },\n startsWithIgnoreCase: function (str) {\n /// \n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return x.indexOf(a[0]) === 0;\n }, [str], maxString);\n },\n equalsIgnoreCase: function (str) {\n /// \n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return x === a[0];\n }, [str], \"\");\n },\n anyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return a.indexOf(x) !== -1;\n }, set, \"\");\n },\n startsWithAnyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return a.some(function (n) {\n return x.indexOf(n) === 0;\n });\n }, set, maxString);\n },\n anyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n var compare = ascending;\n try {\n set.sort(compare);\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n if (set.length === 0) return emptyCollection(this);\n var c = new this._ctx.collClass(this, function () {\n return IDBKeyRange.bound(set[0], set[set.length - 1]);\n });\n\n c._ondirectionchange = function (direction) {\n compare = direction === \"next\" ? ascending : descending;\n set.sort(compare);\n };\n var i = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function () {\n cursor.continue(set[i]);\n });\n return false;\n }\n });\n return c;\n },\n\n notEqual: function (value) {\n return this.inAnyRange([[-Infinity, value], [value, maxKey]], { includeLowers: false, includeUppers: false });\n },\n\n noneOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection.\n try {\n set.sort(ascending);\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[-Infinity,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n var ranges = set.reduce(function (res, val) {\n return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]];\n }, null);\n ranges.push([set[set.length - 1], maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n },\n\n /** Filter out values withing given set of ranges.\r\n * Example, give children and elders a rebate of 50%:\r\n *\r\n * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});\r\n *\r\n * @param {(string|number|Date|Array)[][]} ranges\r\n * @param {{includeLowers: boolean, includeUppers: boolean}} options\r\n */\n inAnyRange: function (ranges, options) {\n var ctx = this._ctx;\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(function (range) {\n return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;\n })) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n var includeLowers = !options || options.includeLowers !== false; // Default to true\n var includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n for (var i = 0, l = ranges.length; i < l; ++i) {\n var range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l) ranges.push(newRange);\n return ranges;\n }\n\n var sortDirection = ascending;\n function rangeSorter(a, b) {\n return sortDirection(a[0], b[0]);\n }\n\n // Join overlapping ranges\n var set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n var i = 0;\n var keyIsBeyondCurrentEntry = includeUppers ? function (key) {\n return ascending(key, set[i][1]) > 0;\n } : function (key) {\n return ascending(key, set[i][1]) >= 0;\n };\n\n var keyIsBeforeCurrentEntry = includeLowers ? function (key) {\n return descending(key, set[i][0]) > 0;\n } : function (key) {\n return descending(key, set[i][0]) >= 0;\n };\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n var checkKey = keyIsBeyondCurrentEntry;\n\n var c = new ctx.collClass(this, function () {\n return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);\n });\n\n c._ondirectionchange = function (direction) {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function () {\n if (sortDirection === ascending) cursor.continue(set[i][0]);else cursor.continue(set[i][1]);\n });\n return false;\n }\n });\n return c;\n },\n startsWithAnyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(function (s) {\n return typeof s === 'string';\n })) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map(function (str) {\n return [str, str + maxString];\n }));\n }\n };\n });\n\n //\n //\n //\n // Collection Class\n //\n //\n //\n function Collection(whereClause, keyRangeGenerator) {\n /// \n ///\n /// \n /// Where clause instance\n /// \n var keyRange = null,\n error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n var whereCtx = whereClause._ctx,\n table = whereCtx.table;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name,\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: table.hook.reading.fire\n };\n }\n\n function isPlainKeyRange(ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n }\n\n props(Collection.prototype, function () {\n\n //\n // Collection Private Functions\n //\n\n function addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n }\n\n function addReplayFilter(ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? function () {\n return combine(curr(), factory());\n } : factory;\n ctx.justLimit = isLimitFilter && !curr;\n }\n\n function addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n }\n\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string\r\n * }\r\n * @param store IDBObjectStore\r\n **/\n function getIndexOrStore(ctx, store) {\n if (ctx.isPrimKey) return store;\n var indexSpec = ctx.table.schema.idxByName[ctx.index];\n if (!indexSpec) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + store.name + \" is not indexed\");\n return store.index(indexSpec.name);\n }\n\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string,\r\n * keysOnly: boolean,\r\n * range?: IDBKeyRange,\r\n * dir: \"next\" | \"prev\"\r\n * }\r\n */\n function openCursor(ctx, store) {\n var idxOrStore = getIndexOrStore(ctx, store);\n return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);\n }\n\n function iter(ctx, fn, resolve, reject, idbstore) {\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);\n } else (function () {\n var set = {};\n var resolved = 0;\n\n function resolveboth() {\n if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.\n }\n\n function union(item, cursor, advance) {\n if (!filter || filter(cursor, advance, resolveboth, reject)) {\n var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n ctx.or._iterate(union, resolveboth, reject, idbstore);\n iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);\n })();\n }\n function getInstanceTemplate(ctx) {\n return ctx.table.schema.instanceTemplate;\n }\n\n return {\n\n //\n // Collection Protected Functions\n //\n\n _read: function (fn, cb) {\n var ctx = this._ctx;\n if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {\n reject(ctx.error);\n });else return ctx.table._idbstore(READONLY, fn).then(cb);\n },\n _write: function (fn) {\n var ctx = this._ctx;\n if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {\n reject(ctx.error);\n });else return ctx.table._idbstore(READWRITE, fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n },\n _addAlgorithm: function (fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n },\n\n _iterate: function (fn, resolve, reject, idbstore) {\n return iter(this._ctx, fn, resolve, reject, idbstore);\n },\n\n clone: function (props) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n },\n\n raw: function () {\n this._ctx.valueMapper = null;\n return this;\n },\n\n //\n // Collection Public methods\n //\n\n each: function (fn) {\n var ctx = this._ctx;\n\n if (fake) {\n var item = getInstanceTemplate(ctx),\n primKeyPath = ctx.table.schema.primKey.keyPath,\n key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath),\n primaryKey = getByKeyPath(item, primKeyPath);\n fn(item, { key: key, primaryKey: primaryKey });\n }\n\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, fn, resolve, reject, idbstore);\n });\n },\n\n count: function (cb) {\n if (fake) return Promise.resolve(0).then(cb);\n var ctx = this._ctx;\n\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return this._read(function (resolve, reject, idbstore) {\n var idx = getIndexOrStore(ctx, idbstore);\n var req = ctx.range ? idx.count(ctx.range) : idx.count();\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function (e) {\n resolve(Math.min(e.target.result, ctx.limit));\n };\n }, cb);\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, function () {\n ++count;return false;\n }, function () {\n resolve(count);\n }, reject, idbstore);\n }, cb);\n }\n },\n\n sortBy: function (keyPath, cb) {\n /// \n var parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n },\n\n toArray: function (cb) {\n var ctx = this._ctx;\n return this._read(function (resolve, reject, idbstore) {\n fake && resolve([getInstanceTemplate(ctx)]);\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n var readingHook = ctx.table.hook.reading.fire;\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(function (res) {\n try {\n resolve(res.map(readingHook));\n } catch (e) {\n reject(e);\n }\n }));\n } else {\n // Getting array through a cursor.\n var a = [];\n iter(ctx, function (item) {\n a.push(item);\n }, function arrayComplete() {\n resolve(a);\n }, reject, idbstore);\n }\n }, cb);\n },\n\n offset: function (offset) {\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, function () {\n var offsetLeft = offset;\n return function (cursor, advance) {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) {\n --offsetLeft;return false;\n }\n advance(function () {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, function () {\n var offsetLeft = offset;\n return function () {\n return --offsetLeft < 0;\n };\n });\n }\n return this;\n },\n\n limit: function (numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, function () {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n },\n\n until: function (filterFunction, bIncludeStopEntry) {\n var ctx = this._ctx;\n fake && filterFunction(getInstanceTemplate(ctx));\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n },\n\n first: function (cb) {\n return this.limit(1).toArray(function (a) {\n return a[0];\n }).then(cb);\n },\n\n last: function (cb) {\n return this.reverse().first(cb);\n },\n\n filter: function (filterFunction) {\n /// function(val){return true/false}\n fake && filterFunction(getInstanceTemplate(this._ctx));\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction);\n return this;\n },\n\n and: function (filterFunction) {\n return this.filter(filterFunction);\n },\n\n or: function (indexName) {\n return new WhereClause(this._ctx.table, indexName, this);\n },\n\n reverse: function () {\n this._ctx.dir = this._ctx.dir === \"prev\" ? \"next\" : \"prev\";\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n },\n\n desc: function () {\n return this.reverse();\n },\n\n eachKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) {\n cb(cursor.key, cursor);\n });\n },\n\n eachUniqueKey: function (cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n },\n\n eachPrimaryKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) {\n cb(cursor.primaryKey, cursor);\n });\n },\n\n keys: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n },\n\n primaryKeys: function (cb) {\n var ctx = this._ctx;\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read(function (resolve, reject, idbstore) {\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = eventSuccessHandler(resolve);\n }).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n },\n\n uniqueKeys: function (cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n },\n\n firstKey: function (cb) {\n return this.limit(1).keys(function (a) {\n return a[0];\n }).then(cb);\n },\n\n lastKey: function (cb) {\n return this.reverse().firstKey(cb);\n },\n\n distinct: function () {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n };\n });\n\n //\n //\n // WriteableCollection Class\n //\n //\n function WriteableCollection() {\n Collection.apply(this, arguments);\n }\n\n derive(WriteableCollection).from(Collection).extend({\n\n //\n // WriteableCollection Public Methods\n //\n\n modify: function (changes) {\n var self = this,\n ctx = this._ctx,\n hook = ctx.table.hook,\n updatingHook = hook.updating.fire,\n deletingHook = hook.deleting.fire;\n\n fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate);\n\n return this._write(function (resolve, reject, idbstore, trans) {\n var modifyer;\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n if (updatingHook === nop && deletingHook === nop) {\n // Noone cares about what is being changed. Just let the modifier function be the given argument as is.\n modifyer = changes;\n } else {\n // People want to know exactly what is being modified or deleted.\n // Let modifyer be a proxy function that finds out what changes the caller is actually doing\n // and call the hooks accordingly!\n modifyer = function (item) {\n var origItem = deepClone(item); // Clone the item first so we can compare laters.\n if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)\n if (!hasOwn(this, \"value\")) {\n // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.\n deletingHook.call(this, this.primKey, item, trans);\n } else {\n // No deletion. Check what was changed\n var objectDiff = getObjectDiff(origItem, this.value);\n var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);\n if (additionalChanges) {\n // Hook want to apply additional modifications. Make sure to fullfill the will of the hook.\n item = this.value;\n keys(additionalChanges).forEach(function (keyPath) {\n setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n });\n }\n }\n };\n }\n } else if (updatingHook === nop) {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i],\n val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n } else {\n // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and\n // allow it to add additional modifications to make.\n var origChanges = changes;\n changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.\n modifyer = function (item) {\n var anythingModified = false;\n var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);\n if (additionalChanges) extend(changes, additionalChanges);\n keys(changes).forEach(function (keyPath) {\n var val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n });\n if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration\n return anythingModified;\n };\n }\n\n var count = 0;\n var successCount = 0;\n var iterationComplete = false;\n var failures = [];\n var failKeys = [];\n var currentKey = null;\n\n function modifyItem(item, cursor) {\n currentKey = cursor.primaryKey;\n var thisContext = {\n primKey: cursor.primaryKey,\n value: item,\n onsuccess: null,\n onerror: null\n };\n\n function onerror(e) {\n failures.push(e);\n failKeys.push(thisContext.primKey);\n checkFinished();\n return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction\n }\n\n if (modifyer.call(thisContext, item, thisContext) !== false) {\n // If a callback explicitely returns false, do not perform the update!\n var bDelete = !hasOwn(thisContext, \"value\");\n ++count;\n tryCatch(function () {\n var req = bDelete ? cursor.delete() : cursor.update(thisContext.value);\n req._hookCtx = thisContext;\n req.onerror = hookedEventRejectHandler(onerror);\n req.onsuccess = hookedEventSuccessHandler(function () {\n ++successCount;\n checkFinished();\n });\n }, onerror);\n } else if (thisContext.onsuccess) {\n // Hook will expect either onerror or onsuccess to always be called!\n thisContext.onsuccess(thisContext.value);\n }\n }\n\n function doReject(e) {\n if (e) {\n failures.push(e);\n failKeys.push(currentKey);\n }\n return reject(new ModifyError(\"Error modifying one or more objects\", failures, successCount, failKeys));\n }\n\n function checkFinished() {\n if (iterationComplete && successCount + failures.length === count) {\n if (failures.length > 0) doReject();else resolve(successCount);\n }\n }\n self.clone().raw()._iterate(modifyItem, function () {\n iterationComplete = true;\n checkFinished();\n }, doReject, idbstore);\n });\n },\n\n 'delete': function () {\n var _this4 = this;\n\n var ctx = this._ctx,\n range = ctx.range,\n deletingHook = ctx.table.hook.deleting.fire,\n hasDeleteHook = deletingHook !== nop;\n if (!hasDeleteHook && isPlainKeyRange(ctx) && (ctx.isPrimKey && !hangsOnDeleteLargeKeyRange || !range)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write(function (resolve, reject, idbstore) {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n var onerror = eventRejectHandler(reject),\n countReq = range ? idbstore.count(range) : idbstore.count();\n countReq.onerror = onerror;\n countReq.onsuccess = function () {\n var count = countReq.result;\n tryCatch(function () {\n var delReq = range ? idbstore.delete(range) : idbstore.clear();\n delReq.onerror = onerror;\n delReq.onsuccess = function () {\n return resolve(count);\n };\n }, function (err) {\n return reject(err);\n });\n };\n });\n }\n\n // Default version to use when collection is not a vanilla IDBKeyRange on the primary key.\n // Divide into chunks to not starve RAM.\n // If has delete hook, we will have to collect not just keys but also objects, so it will use\n // more memory and need lower chunk size.\n var CHUNKSIZE = hasDeleteHook ? 2000 : 10000;\n\n return this._write(function (resolve, reject, idbstore, trans) {\n var totalCount = 0;\n // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.\n var collection = _this4.clone({\n keysOnly: !ctx.isMatch && !hasDeleteHook }) // load just keys (unless filter() or and() or deleteHook has subscribers)\n .distinct() // In case multiEntry is used, never delete same key twice because resulting count\n // would become larger than actual delete count.\n .limit(CHUNKSIZE).raw(); // Don't filter through reading-hooks (like mapped classes etc)\n\n var keysOrTuples = [];\n\n // We're gonna do things on as many chunks that are needed.\n // Use recursion of nextChunk function:\n var nextChunk = function () {\n return collection.each(hasDeleteHook ? function (val, cursor) {\n // Somebody subscribes to hook('deleting'). Collect all primary keys and their values,\n // so that the hook can be called with its values in bulkDelete().\n keysOrTuples.push([cursor.primaryKey, cursor.value]);\n } : function (val, cursor) {\n // No one subscribes to hook('deleting'). Collect only primary keys:\n keysOrTuples.push(cursor.primaryKey);\n }).then(function () {\n // Chromium deletes faster when doing it in sort order.\n hasDeleteHook ? keysOrTuples.sort(function (a, b) {\n return ascending(a[0], b[0]);\n }) : keysOrTuples.sort(ascending);\n return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);\n }).then(function () {\n var count = keysOrTuples.length;\n totalCount += count;\n keysOrTuples = [];\n return count < CHUNKSIZE ? totalCount : nextChunk();\n });\n };\n\n resolve(nextChunk());\n });\n }\n });\n\n //\n //\n //\n // ------------------------- Help functions ---------------------------\n //\n //\n //\n\n function lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n }\n\n function setApiOnPlace(objs, tableNames, mode, dbschema) {\n tableNames.forEach(function (tableName) {\n var tableInstance = db._tableFactory(mode, dbschema[tableName]);\n objs.forEach(function (obj) {\n tableName in obj || (obj[tableName] = tableInstance);\n });\n });\n }\n\n function removeTablesApi(objs) {\n objs.forEach(function (obj) {\n for (var key in obj) {\n if (obj[key] instanceof Table) delete obj[key];\n }\n });\n }\n\n function iterate(req, filter, fn, resolve, reject, valueMapper) {\n\n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? function (x, c, a) {\n return fn(valueMapper(x), c, a);\n } : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn, reject);\n\n if (!req.onerror) req.onerror = eventRejectHandler(reject);\n if (filter) {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () {\n cursor.continue();\n };\n if (filter(cursor, function (advancer) {\n c = advancer;\n }, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) {\n c = advancer;\n });\n c();\n } else {\n resolve();\n }\n }, reject);\n } else {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () {\n cursor.continue();\n };\n wrappedFn(cursor.value, cursor, function (advancer) {\n c = advancer;\n });\n c();\n } else {\n resolve();\n }\n }, reject);\n }\n }\n\n function parseIndexSyntax(indexes) {\n /// \n /// \n var rv = [];\n indexes.split(',').forEach(function (index) {\n index = index.trim();\n var name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n rv.push(new IndexSpec(name, keyPath || null, /\\&/.test(index), /\\*/.test(index), /\\+\\+/.test(index), isArray(keyPath), /\\./.test(index)));\n });\n return rv;\n }\n\n function cmp(key1, key2) {\n return indexedDB.cmp(key1, key2);\n }\n\n function min(a, b) {\n return cmp(a, b) < 0 ? a : b;\n }\n\n function max(a, b) {\n return cmp(a, b) > 0 ? a : b;\n }\n\n function ascending(a, b) {\n return indexedDB.cmp(a, b);\n }\n\n function descending(a, b) {\n return indexedDB.cmp(b, a);\n }\n\n function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n }\n\n function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n }\n\n function combine(filter1, filter2) {\n return filter1 ? filter2 ? function () {\n return filter1.apply(this, arguments) && filter2.apply(this, arguments);\n } : filter1 : filter2;\n }\n\n function readGlobalSchema() {\n db.verno = idbdb.version / 10;\n db._dbSchema = globalSchema = {};\n dbStoreNames = slice(idbdb.objectStoreNames, 0);\n if (dbStoreNames.length === 0) return; // Database contains no stores.\n var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');\n dbStoreNames.forEach(function (storeName) {\n var store = trans.objectStore(storeName),\n keyPath = store.keyPath,\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var primKey = new IndexSpec(keyPath, keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);\n var indexes = [];\n for (var j = 0; j < store.indexNames.length; ++j) {\n var idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);\n indexes.push(index);\n }\n globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});\n });\n setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema);\n }\n\n function adjustToExistingIndexNames(schema, idbtrans) {\n /// \n /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n /// \n /// Map between name and TableSchema\n /// \n var storeNames = idbtrans.db.objectStoreNames;\n for (var i = 0; i < storeNames.length; ++i) {\n var storeName = storeNames[i];\n var store = idbtrans.objectStore(storeName);\n hasGetAll = 'getAll' in store;\n for (var j = 0; j < store.indexNames.length; ++j) {\n var indexName = store.indexNames[j];\n var keyPath = store.index(indexName).keyPath;\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n var indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) indexSpec.name = indexName;\n }\n }\n }\n }\n\n function fireOnBlocked(ev) {\n db.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections.filter(function (c) {\n return c.name === db.name && c !== db && !c._vcFired;\n }).map(function (c) {\n return c.on(\"versionchange\").fire(ev);\n });\n }\n\n extend(this, {\n Collection: Collection,\n Table: Table,\n Transaction: Transaction,\n Version: Version,\n WhereClause: WhereClause,\n WriteableCollection: WriteableCollection,\n WriteableTable: WriteableTable\n });\n\n init();\n\n addons.forEach(function (fn) {\n fn(db);\n });\n}\n\nvar fakeAutoComplete = function () {}; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\nvar fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\n\nfunction parseType(type) {\n if (typeof type === 'function') {\n return new type();\n } else if (isArray(type)) {\n return [parseType(type[0])];\n } else if (type && typeof type === 'object') {\n var rv = {};\n applyStructure(rv, type);\n return rv;\n } else {\n return type;\n }\n}\n\nfunction applyStructure(obj, structure) {\n keys(structure).forEach(function (member) {\n var value = parseType(structure[member]);\n obj[member] = value;\n });\n return obj;\n}\n\nfunction eventSuccessHandler(done) {\n return function (ev) {\n done(ev.target.result);\n };\n}\n\nfunction hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function (event) {\n var req = event.target,\n result = req.result,\n ctx = req._hookCtx,\n // Contains the hook error handler. Put here instead of closure to boost performance.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\nfunction eventRejectHandler(reject) {\n return function (event) {\n preventDefault(event);\n reject(event.target.error);\n return false;\n };\n}\n\nfunction hookedEventRejectHandler(reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n\n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,\n // Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject(err);\n return false;\n });\n}\n\nfunction preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nfunction globalDatabaseList(cb) {\n var val,\n localStorage = Dexie.dependencies.localStorage;\n if (!localStorage) return cb([]); // Envs without localStorage support\n try {\n val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || \"[]\");\n } catch (e) {\n val = [];\n }\n if (cb(val)) {\n localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val));\n }\n}\n\nfunction awaitIterator(iterator) {\n var callNext = function (result) {\n return iterator.next(result);\n },\n doThrow = function (error) {\n return iterator.throw(error);\n },\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext) {\n return function (val) {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value : !value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError);\n };\n }\n\n return step(callNext)();\n}\n\n//\n// IndexSpec struct\n//\nfunction IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n this.name = name;\n this.keyPath = keyPath;\n this.unique = unique;\n this.multi = multi;\n this.auto = auto;\n this.compound = compound;\n this.dotted = dotted;\n var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && '[' + [].join.call(keyPath, '+') + ']';\n this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + keyPathSrc;\n}\n\n//\n// TableSchema struct\n//\nfunction TableSchema(name, primKey, indexes, instanceTemplate) {\n /// \n /// \n /// \n /// \n this.name = name;\n this.primKey = primKey || new IndexSpec();\n this.indexes = indexes || [new IndexSpec()];\n this.instanceTemplate = instanceTemplate;\n this.mappedClass = null;\n this.idxByName = arrayToObject(indexes, function (index) {\n return [index.name, index];\n });\n}\n\n// Used in when defining dependencies later...\n// (If IndexedDBShim is loaded, prefer it before standard indexedDB)\nvar idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {};\n\nfunction safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nfunction getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\n// Export Error classes\nprops(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};\n\n//\n// Static methods and properties\n// \nprops(Dexie, {\n\n //\n // Static delete() method.\n //\n delete: function (databaseName) {\n var db = new Dexie(databaseName),\n promise = db.delete();\n promise.onblocked = function (fn) {\n db.on(\"blocked\", fn);\n return this;\n };\n return promise;\n },\n\n //\n // Static exists() method.\n //\n exists: function (name) {\n return new Dexie(name).open().then(function (db) {\n db.close();\n return true;\n }).catch(Dexie.NoSuchDatabaseError, function () {\n return false;\n });\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames: function (cb) {\n return new Promise(function (resolve, reject) {\n var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB);\n if (getDatabaseNames) {\n // In case getDatabaseNames() becomes standard, let's prepare to support it:\n var req = getDatabaseNames();\n req.onsuccess = function (event) {\n resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array\n };\n req.onerror = eventRejectHandler(reject);\n } else {\n globalDatabaseList(function (val) {\n resolve(val);\n return false;\n });\n }\n }).then(cb);\n },\n\n defineClass: function (structure) {\n /// \n /// Create a javascript constructor based on given template for which properties to expect in the class.\n /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n\n // Default constructor able to copy given properties into this object.\n function Class(properties) {\n /// Properties to initialize object with.\n /// \n properties ? extend(this, properties) : fake && applyStructure(this, structure);\n }\n return Class;\n },\n\n applyStructure: applyStructure,\n\n ignoreTransaction: function (scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n\n vip: function (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n },\n\n async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n\n // Dexie.currentTransaction property\n currentTransaction: {\n get: function () {\n return PSD.trans || null;\n }\n },\n\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n\n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: function () {\n return Debug.debug;\n },\n set: function (value) {\n Debug.setDebug(value, value === 'dexie' ? function () {\n return true;\n } : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive,\n extend: extend,\n props: props,\n override: override,\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n events: { get: Debug.deprecated(function () {\n return Events;\n }) }, // Backward compatible lowercase version.\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n asap: asap,\n maxKey: maxKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.\n errnames: errnames,\n\n // Export other static classes\n IndexSpec: IndexSpec,\n TableSchema: TableSchema,\n\n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: {\n // Required:\n indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange\n },\n\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.').map(function (n) {\n return parseInt(n);\n }).reduce(function (p, c, i) {\n return p + c / Math.pow(10, i * 2);\n }),\n fakeAutoComplete: fakeAutoComplete,\n\n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n default: Dexie\n});\n\ntryCatch(function () {\n // Optional dependencies\n // localStorage\n Dexie.dependencies.localStorage = (typeof chrome !== \"undefined\" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage;\n});\n\n// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.\nPromise.rejectionMapper = mapError;\n\n// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015.\ndoFakeAutoComplete(function () {\n Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete;\n Dexie.fake = fake = true;\n});"]} \ No newline at end of file diff --git a/test/bundle.js b/test/bundle.js new file mode 100644 index 000000000..ca069abc5 --- /dev/null +++ b/test/bundle.js @@ -0,0 +1,7868 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('dexie'), require('QUnit')) : + typeof define === 'function' && define.amd ? define(['dexie', 'QUnit'], factory) : + (factory(global.Dexie,global.QUnit)); +}(this, (function (Dexie,QUnit) { 'use strict'; + +Dexie = 'default' in Dexie ? Dexie['default'] : Dexie; + +Dexie.debug = window.location.search.indexOf('longstacks=true') !== -1 ? 'dexie' : false; +if (window.location.search.indexOf('longstacks=tests') !== -1) Dexie.debug = true; // Don't include stuff from dexie.js. + +var no_optimize = window.no_optimize || window.location.search.indexOf('dontoptimize=true') !== -1; + +function resetDatabase(db) { + /// + var Promise = Dexie.Promise; + return no_optimize || !db._hasBeenCreated ? + // Full Database recreation. Takes much time! + db.delete().then(function () { + return db.open().then(function () { + if (!no_optimize) { + db._hasBeenCreated = true; + var initialState = db._initialState = {}; + // Now, snapshot the database how it looks like initially (what on.populate did) + return db.transaction('r', db.tables, function () { + var trans = Dexie.currentTransaction; + return Promise.all(trans.storeNames.filter(function (tableName) { + // Don't clear 'meta tables' + return tableName[0] != '_' && tableName[0] != '$'; + }).map(function (tableName) { + var items = {}; + initialState[tableName] = items; + return db.table(tableName).each(function (item, cursor) { + items[cursor.primaryKey] = { key: cursor.primaryKey, value: item }; + }); + })); + }); + } + }); + }) : + + // Optimize: Don't delete and recreate database. Instead, just clear all object stores, + // and manually run db.on.populate + db.transaction('rw!', db.tables, function () { + // Got to do an operation in order for backend transaction to be created. + var trans = Dexie.currentTransaction; + var initialState = db._initialState; + return Promise.all(trans.storeNames.filter(function (tableName) { + // Don't clear 'meta tables' + return tableName[0] != '_' && tableName[0] != '$'; + }).map(function (tableName) { + // Read current state + var items = {}; + return db.table(tableName).each(function (item, cursor) { + items[cursor.primaryKey] = { key: cursor.primaryKey, value: item }; + }).then(function () { + // Diff from initialState + // Go through initialState and diff with current state + var initialItems = initialState[tableName]; + return Promise.all(Object.keys(initialItems).map(function (key) { + var item = items[key]; + var initialItem = initialItems[key]; + if (!item || JSON.stringify(item.value) != JSON.stringify(initialItem.value)) return db.table(tableName).schema.primKey.keyPath ? db.table(tableName).put(initialItem.value) : db.table(tableName).put(initialItem.value, initialItem.key); + return Promise.resolve(); + })); + }).then(function () { + // Go through current state and diff with initialState + var initialItems = initialState[tableName]; + return Promise.all(Object.keys(items).map(function (key) { + var item = items[key]; + var initialItem = initialItems[key]; + if (!initialItem) return db.table(tableName).delete(item.key); + return Promise.resolve(); + })); + }); + })); + }); +} + + + +var isIE = !window.ActiveXObject && "ActiveXObject" in window; +var isEdge = /Edge\/\d+/.test(navigator.userAgent); +var hasPolyfillIE = [].slice.call(document.getElementsByTagName("script")).some(function (s) { + return s.src.indexOf("idb-iegap") !== -1; +}); + +function supports(features) { + return features.split('+').reduce(function (result, feature) { + switch (feature.toLowerCase()) { + case "compound": + return result && (hasPolyfillIE || !isIE && !isEdge); // Should add Safari to + case "multientry": + return result && (hasPolyfillIE || !isIE && !isEdge); // Should add Safari to + case "versionchange": + return true; + //return result && (!isIE && !isEdge); // Should add Safari to + default: + throw new Error("Unknown feature: " + feature); + } + }, true); +} + +function spawnedTest(name, num, promiseGenerator) { + if (!promiseGenerator) { + promiseGenerator = num; + QUnit.asyncTest(name, function () { + Dexie.spawn(promiseGenerator).catch(function (e) { + return QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); + }); + } else { + QUnit.asyncTest(name, num, function () { + Dexie.spawn(promiseGenerator).catch(function (e) { + return QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); + }); + } +} + +/** + * Created by David on 3/31/2016. + */ +var Promise$1 = Dexie.Promise; +var all = Promise$1.all; +var async = Dexie.async; + +var db = new Dexie("TestDBCrudHooks"); +db.version(1).stores({ + table1: "id,idx", + table2: ",&idx", + table3: "++id,&idx", + table4: "++,&idx", + table5: "" +}); + +var ourTables = [db.table1, db.table2, db.table3, db.table4, db.table5]; + +var opLog = []; +var successLog = []; +var errorLog = []; +var watchSuccess = false; +var watchError = false; +var deliverKeys = []; +var deliverModifications = null; +var deliverKeys2 = []; +var deliverModifications2 = null; +var opLog2 = []; +var successLog2 = []; +var errorLog2 = []; +var transLog = []; + +function unsubscribeHooks() { + ourTables.forEach(function (table) { + table.hook('creating').unsubscribe(creating2); + table.hook('creating').unsubscribe(creating1); + table.hook('reading').unsubscribe(reading1); + table.hook('reading').unsubscribe(reading2); + table.hook('updating').unsubscribe(updating1); + table.hook('updating').unsubscribe(updating2); + table.hook('deleting').unsubscribe(deleting2); + table.hook('deleting').unsubscribe(deleting1); + }); +} + +function subscrubeHooks() { + ourTables.forEach(function (table) { + table.hook('creating', creating1); + table.hook('creating', creating2); + table.hook('reading', reading1); + table.hook('reading', reading2); + table.hook('updating', updating1); + table.hook('updating', updating2); + table.hook('deleting', deleting1); + table.hook('deleting', deleting2); + }); +} +var reset = async(regeneratorRuntime.mark(function reset() { + return regeneratorRuntime.wrap(function reset$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + unsubscribeHooks(); + _context.next = 3; + return all(ourTables.map(function (table) { + return table.clear(); + })); + + case 3: + subscrubeHooks(); + opLog = []; + successLog = []; + errorLog = []; + watchSuccess = false; + watchError = false; + deliverKeys = []; + deliverModifications = null; + deliverKeys2 = []; + deliverModifications2 = null; + opLog2 = []; + successLog2 = []; + errorLog2 = []; + transLog = []; + + case 17: + case 'end': + return _context.stop(); + } + } + }, reset, this); +})); + +/*function stack() { + if (Error.captureStackTrace) { + let obj = {}; + Error.captureStackTrace(obj, stack); + return obj.stack; + } + var e = new Error(""); + if (e.stack) return e.stack; + try{throw e}catch(ex){return ex.stack || "";} +}*/ + +function nop() {} + +function creating1(primKey, obj, transaction) { + // You may do additional database operations using given transaction object. + // You may also modify given obj + // You may set this.onsuccess = function (primKey){}. Called when autoincremented key is known. + // You may set this.onerror = callback if create operation fails. + // If returning any value other than undefined, the returned value will be used as primary key + transLog.push({ trans: transaction, current: Dexie.currentTransaction }); + var op = { + op: "create", + key: primKey, + value: Dexie.deepClone(obj) + }; + opLog.push(op); + + if (watchSuccess) { + this.onsuccess = function (primKey) { + return successLog.push(primKey); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog.push(e); + }; + } + if (deliverKeys[opLog.length - 1]) return deliverKeys[opLog.length - 1]; +} + +// Check that chaining several hooks works +function creating2(primKey, obj, transaction) { + var op = { + op: "create", + key: primKey, + value: Dexie.deepClone(obj) + }; + opLog2.push(op); + + if (watchSuccess) { + this.onsuccess = function (primKey) { + return successLog2.push(primKey); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog2.push(e); + }; + } + if (deliverKeys2[opLog2.length - 1]) return deliverKeys2[opLog2.length - 1]; +} + +function reading1(obj) { + opLog.push({ + op: "read", + obj: Dexie.deepClone(obj) + }); + return { theObject: obj }; +} + +function reading2(obj) { + opLog2.push({ + op: "read", + obj: Dexie.deepClone(obj) + }); + return obj.theObject; +} + +function updating1(modifications, primKey, obj, transaction) { + // You may use transaction to do additional database operations. + // You may not do any modifications on any of the given arguments. + // You may set this.onsuccess = callback when update operation completes. + // You may set this.onerror = callback if update operation fails. + // If you want to make additional modifications, return another modifications object + // containing the additional or overridden modifications to make. Any returned + // object will be merged to the given modifications object. + transLog.push({ trans: transaction, current: Dexie.currentTransaction }); + var op = { + op: "update", + key: primKey, + obj: Dexie.deepClone(obj), + mods: Dexie.shallowClone(modifications) + }; + opLog.push(op); + + if (watchSuccess) { + this.onsuccess = function () { + return successLog.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog.push(e); + }; + } + if (deliverModifications) return deliverModifications; +} + +// Chaining: +function updating2(modifications, primKey, obj, transaction) { + // You may use transaction to do additional database operations. + // You may not do any modifications on any of the given arguments. + // You may set this.onsuccess = callback when update operation completes. + // You may set this.onerror = callback if update operation fails. + // If you want to make additional modifications, return another modifications object + // containing the additional or overridden modifications to make. Any returned + // object will be merged to the given modifications object. + var op = { + op: "update", + key: primKey, + obj: Dexie.deepClone(obj), + mods: Dexie.shallowClone(modifications) + }; + opLog2.push(op); + + if (watchSuccess) { + this.onsuccess = function () { + return successLog2.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog2.push(e); + }; + } + if (deliverModifications2) return deliverModifications2; +} + +function deleting1(primKey, obj, transaction) { + // You may do additional database operations using given transaction object. + // You may set this.onsuccess = callback when delete operation completes. + // You may set this.onerror = callback if delete operation fails. + // Any modification to obj is ignored. + // Any return value is ignored. + // throwing exception will make the db operation fail. + transLog.push({ trans: transaction, current: Dexie.currentTransaction }); + var op = { + op: "delete", + key: primKey, + obj: obj + }; + opLog.push(op); + if (watchSuccess) { + this.onsuccess = function () { + return successLog.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog.push(e); + }; + } +} + +// Chaining: +function deleting2(primKey, obj, transaction) { + // You may do additional database operations using given transaction object. + // You may set this.onsuccess = callback when delete operation completes. + // You may set this.onerror = callback if delete operation fails. + // Any modification to obj is ignored. + // Any return value is ignored. + // throwing exception will make the db operation fail. + var op = { + op: "delete", + key: primKey, + obj: obj + }; + opLog2.push(op); + if (watchSuccess) { + this.onsuccess = function () { + return successLog2.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog2.push(e); + }; + } +} + +QUnit.module("crud-hooks", { + setup: function () { + QUnit.stop(); + resetDatabase(db).then(function () { + return reset(); + }).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + unsubscribeHooks(); + } +}); + +var expect = async(regeneratorRuntime.mark(function _callee(expected, modifyer) { + return regeneratorRuntime.wrap(function _callee$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return reset(); + + case 2: + _context2.next = 4; + return modifyer(); + + case 4: + QUnit.equal(JSON.stringify(opLog, null, 2), JSON.stringify(expected, null, 2), "Expected oplog: " + JSON.stringify(expected)); + QUnit.ok(transLog.every(function (x) { + return x.trans && x.current === x.trans; + }), "transaction argument is valid and same as Dexie.currentTransaction"); + _context2.next = 8; + return reset(); + + case 8: + watchSuccess = true; + watchError = true; + _context2.next = 12; + return modifyer(); + + case 12: + QUnit.equal(errorLog.length + errorLog2.length, 0, "No errors should have been registered"); + QUnit.equal(successLog.length, expected.filter(function (op) { + return op.op !== 'read'; + }).length, "First hook got success events"); + QUnit.equal(successLog2.length, expected.filter(function (op) { + return op.op !== 'read'; + }).length, "Second hook got success events"); + expected.forEach(function (x, i) { + if (x.op === "create" && x.key !== undefined) { + QUnit.equal(successLog[i], x.key, "Success events got the correct key"); + QUnit.equal(successLog2[i], x.key, "Success events got the correct key (2)"); + } + }); + + if (!expected.some(function (x) { + return x.op === "create" && x.key === undefined; + })) { + _context2.next = 27; + break; + } + + _context2.next = 19; + return reset(); + + case 19: + deliverKeys = expected.map(function (x, i) { + return "Hook1Key" + i; + }); + deliverKeys2 = expected.map(function (x, i) { + return "Hook2Key" + i; + }); + watchSuccess = true; + watchError = true; + _context2.next = 25; + return modifyer(); + + case 25: + QUnit.equal(errorLog.length + errorLog2.length, 0, "No errors should have been registered"); + expected.forEach(function (x, i) { + if (x.op === "create" && x.key === undefined) { + QUnit.equal(opLog[i].key, expected[i].key, "First hook got expected key delivered"); + QUnit.equal(opLog2[i].key, deliverKeys[i], "Second hook got key delivered from first hook"); + QUnit.equal(successLog[i], deliverKeys2[i], "Success event got delivered key from hook2"); + QUnit.equal(successLog2[i], deliverKeys2[i], "Success event got delivered key from hook2 (2)"); + } + }); + + case 27: + if (!expected.some(function (x) { + return x.op === "update"; + })) { + _context2.next = 34; + break; + } + + _context2.next = 30; + return reset(); + + case 30: + deliverModifications = { "someProp.someSubProp": "someValue" }; + _context2.next = 33; + return modifyer(); + + case 33: + expected.forEach(function (x, i) { + if (x.op === "update") { + QUnit.equal(JSON.stringify(opLog[i].obj), JSON.stringify(opLog2[i].obj), "Object has not yet been changed in hook2"); + QUnit.ok(Object.keys(opLog[i].mods).every(function (prop) { + return JSON.stringify(opLog[i].mods[prop]) === JSON.stringify(opLog2[i].mods[prop]); + }), "All mods that were originally sent to hook1, are also sent to hook2"); + QUnit.ok("someProp.someSubProp" in opLog2[i].mods, "oplog2 got first hook's additional modifications"); + } + }); + + case 34: + case 'end': + return _context2.stop(); + } + } + }, _callee, this); +})); + +var verifyErrorFlows = async(regeneratorRuntime.mark(function _callee2(modifyer) { + return regeneratorRuntime.wrap(function _callee2$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return reset(); + + case 2: + QUnit.ok(true, "Verifying ERROR flows"); + watchSuccess = true; + watchError = true; + _context3.next = 7; + return modifyer(); + + case 7: + QUnit.equal(opLog.length, opLog2.length, "Number of ops same for hook1 and hook2: " + opLog.length); + QUnit.equal(successLog.length + errorLog.length, opLog.length, "Either onerror or onsuccess must have been called for every op. onerror: " + errorLog.length + ". onsuccess: " + successLog.length + ". opLog: " + JSON.stringify(opLog)); + QUnit.equal(successLog2.length + errorLog2.length, opLog2.length, "Either onerror or onsuccess must have been called for every op (hook2). onerror: " + errorLog2.length + ". onsuccess: " + successLog2.length + ". opLog: " + JSON.stringify(opLog2)); + + case 10: + case 'end': + return _context3.stop(); + } + } + }, _callee2, this); +})); + +// +// +// Tests goes here... +// +// + +// +// CREATING hook tests... +// +// Ways to produce CREATEs: +// Table.add() +// Table.put() +// Table.bulkAdd() +// Table.bulkPut() + +spawnedTest("creating using Table.add()", regeneratorRuntime.mark(function _callee4() { + return regeneratorRuntime.wrap(function _callee4$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 14 } + }], function () { + return db.transaction('rw', db.tables, function () { + db.table1.add({ id: 1, idx: 11 }); + db.table2.add({ idx: 12 }, 2); + db.table3.add({ idx: 13 }); + db.table4.add({ idx: 14 }); + }); + }); + + case 2: + _context5.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee3() { + return regeneratorRuntime.wrap(function _callee3$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return db.table1.add({ id: 1 }); + + case 2: + _context4.next = 4; + return db.table1.add({ id: 1 }).catch(nop); + + case 4: + _context4.next = 6; + return db.table2.add({}, 1); + + case 6: + _context4.next = 8; + return db.table2.add({}, 1).catch(nop); + + case 8: + _context4.next = 10; + return db.table1.add({ id: {} }).catch(nop); + + case 10: + case 'end': + return _context4.stop(); + } + } + }, _callee3, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context5.stop(); + } + } + }, _callee4, this); +})); + +spawnedTest("creating using Table.put()", regeneratorRuntime.mark(function _callee6() { + return regeneratorRuntime.wrap(function _callee6$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 14 } + }], function () { + return db.transaction('rw', db.tables, function () { + db.table1.put({ id: 1, idx: 11 }); + db.table2.put({ idx: 12 }, 2); + db.table3.put({ idx: 13 }); + db.table4.put({ idx: 14 }); + }); + }); + + case 2: + _context7.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee5() { + return regeneratorRuntime.wrap(function _callee5$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return db.table3.put({ idx: 1 }); + + case 2: + _context6.next = 4; + return db.table3.put({ idx: 1 }).catch(nop); + + case 4: + _context6.next = 6; + return db.table2.put({}, 1); + + case 6: + _context6.next = 8; + return db.table2.put({}, 1).catch(nop); + + case 8: + _context6.next = 10; + return db.table3.put({ id: {} }).catch(nop); + + case 10: + case 'end': + return _context6.stop(); + } + } + }, _callee5, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context7.stop(); + } + } + }, _callee6, this); +})); + +spawnedTest("creating using Table.bulkAdd()", regeneratorRuntime.mark(function _callee9() { + return regeneratorRuntime.wrap(function _callee9$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + _context10.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 1.2, + value: { id: 1.2, idx: 11.2 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + key: 2.2, + value: { idx: 12.2 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 13.2 } + }, { + op: "create", + value: { idx: 14 } + }, { + op: "create", + value: { idx: 14.2 } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee7() { + return regeneratorRuntime.wrap(function _callee7$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + db.table1.bulkAdd([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }]); + db.table2.bulkAdd([{ idx: 12 }, { idx: 12.2 }], [2, 2.2]); + db.table3.bulkAdd([{ idx: 13 }, { idx: 13.2 }]); + db.table4.bulkAdd([{ idx: 14 }, { idx: 14.2 }]); + + case 4: + case 'end': + return _context8.stop(); + } + } + }, _callee7, this); + })); + }); + + case 2: + _context10.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee8() { + return regeneratorRuntime.wrap(function _callee8$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return db.table1.bulkAdd([{ id: 1 }, { id: 1 }]).catch(nop); + + case 2: + _context9.next = 4; + return db.table1.bulkAdd([{ id: 2 }, { id: 2 }, { id: 3 }]).catch(nop); + + case 4: + _context9.next = 6; + return db.table2.bulkAdd([{}, {}], [1, 1]).catch(nop); + + case 6: + _context9.next = 8; + return db.table2.bulkAdd([{}, {}, {}], [2, 2, 3]).catch(nop); + + case 8: + _context9.next = 10; + return db.table1.bulkAdd([{ id: {} }]).catch(nop); + + case 10: + case 'end': + return _context9.stop(); + } + } + }, _callee8, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context10.stop(); + } + } + }, _callee9, this); +})); + +spawnedTest("creating using Table.bulkPut()", regeneratorRuntime.mark(function _callee12() { + return regeneratorRuntime.wrap(function _callee12$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + _context13.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 1.2, + value: { id: 1.2, idx: 11.2 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + key: 2.2, + value: { idx: 12.2 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 13.2 } + }, { + op: "create", + value: { idx: 14 } + }, { + op: "create", + value: { idx: 14.2 } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee10() { + return regeneratorRuntime.wrap(function _callee10$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + _context11.next = 2; + return db.table1.bulkPut([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }]); + + case 2: + _context11.next = 4; + return db.table2.bulkPut([{ idx: 12 }, { idx: 12.2 }], [2, 2.2]); + + case 4: + _context11.next = 6; + return db.table3.bulkPut([{ idx: 13 }, { idx: 13.2 }]); + + case 6: + _context11.next = 8; + return db.table4.bulkPut([{ idx: 14 }, { idx: 14.2 }]); + + case 8: + case 'end': + return _context11.stop(); + } + } + }, _callee10, this); + })); + }); + + case 2: + _context13.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee11() { + return regeneratorRuntime.wrap(function _callee11$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return db.table3.bulkPut([{ idx: 1 }, { idx: 1 }]).catch(nop); + + case 2: + _context12.next = 4; + return db.table3.bulkPut([{ idx: 2 }, { idx: 2 }, { idx: 3 }]).catch(nop); + + case 4: + _context12.next = 6; + return db.table1.bulkPut([{ id: {} }]).catch(nop); + + case 6: + case 'end': + return _context12.stop(); + } + } + }, _callee11, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context13.stop(); + } + } + }, _callee12, this); +})); + +// +// READING hooks test +// Ways to produce READs: +// Table.get() +// Collection.toArray() +// Collection.each() +// Collection.first() +// Collection.last() +// But not: +// Table.filter() / Collection.and() + +spawnedTest("reading tests", regeneratorRuntime.mark(function _callee14() { + var readOps, readOps2; + return regeneratorRuntime.wrap(function _callee14$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + _context15.next = 2; + return expect([{ + op: "create", + key: 1, + value: { foo: "bar" } + }, { + op: "create", + key: 2, + value: { fee: "bore" } + }, { + op: "read", // toArray() (1) + obj: { foo: "bar" } + }, { + op: "read", // toArray() (2) + obj: { fee: "bore" } + }, { + op: "read", // reverse.each() (1) + obj: { fee: "bore" } + }, { + op: "read", // reverse.each() (2) + obj: { foo: "bar" } + }, { + op: "read", // first() + obj: { foo: "bar" } + }, { + op: "read", // last() + obj: { fee: "bore" } + }], function () { + return db.transaction('rw', 'table5', regeneratorRuntime.mark(function _callee13() { + return regeneratorRuntime.wrap(function _callee13$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return db.table5.bulkAdd([{ foo: "bar" }, { fee: "bore" }], [1, 2]); + + case 2: + _context14.next = 4; + return db.table5.toArray(); + + case 4: + _context14.next = 6; + return db.table5.reverse().each(function (x) {}); + + case 6: + _context14.next = 8; + return db.table5.orderBy(':id').first(); + + case 8: + _context14.next = 10; + return db.table5.orderBy(':id').last(); + + case 10: + _context14.next = 12; + return db.table5.filter(function (x) { + return false; + }).toArray(); + + case 12: + case 'end': + return _context14.stop(); + } + } + }, _callee13, this); + })); + }); + + case 2: + readOps = opLog.filter(function (o) { + return o.op === 'read'; + }), readOps2 = opLog2.filter(function (o) { + return o.op === 'read'; + }); + + + QUnit.ok(readOps.every(function (o, i) { + return JSON.stringify(readOps2[i].obj.theObject) === JSON.stringify(o.obj); + }), "hook2 should have got hook1's return value"); + + case 4: + case 'end': + return _context15.stop(); + } + } + }, _callee14, this); +})); + +// +// UPDATING hooks test +// Ways to produce UPDATEs: +// Table.put() +// Table.bulkPut() +// Table.update() +// Collection.modify() + +spawnedTest("updating using Table.put()", regeneratorRuntime.mark(function _callee17() { + return regeneratorRuntime.wrap(function _callee17$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + _context18.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee15() { + return regeneratorRuntime.wrap(function _callee15$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + db.table1.put({ id: 1, address: { city: 'A' } }); // create + db.table1.put({ id: 1, address: { city: 'B' } }); // update + + case 2: + case 'end': + return _context16.stop(); + } + } + }, _callee15, this); + })); + }); + + case 2: + _context18.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee16() { + return regeneratorRuntime.wrap(function _callee16$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + _context17.next = 2; + return db.table3.add({ id: 1, idx: 1 }); + + case 2: + _context17.next = 4; + return db.table3.put({ id: 2, idx: 1 }).catch(nop); + + case 4: + _context17.next = 6; + return db.table3.put({ id: {} }).catch(nop); + + case 6: + case 'end': + return _context17.stop(); + } + } + }, _callee16, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context18.stop(); + } + } + }, _callee17, this); +})); + +spawnedTest("updating using Table.bulkPut()", regeneratorRuntime.mark(function _callee20() { + return regeneratorRuntime.wrap(function _callee20$(_context21) { + while (1) { + switch (_context21.prev = _context21.next) { + case 0: + _context21.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee18() { + return regeneratorRuntime.wrap(function _callee18$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + db.table1.put({ id: 1, address: { city: 'A' } }); // create + db.table1.put({ id: 1, address: { city: 'B' } }); // update + + case 2: + case 'end': + return _context19.stop(); + } + } + }, _callee18, this); + })); + }); + + case 2: + _context21.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee19() { + return regeneratorRuntime.wrap(function _callee19$(_context20) { + while (1) { + switch (_context20.prev = _context20.next) { + case 0: + _context20.next = 2; + return db.table4.add({ idx: 1 }, 1); + + case 2: + _context20.next = 4; + return db.table4.bulkPut([{ idx: 1 }], [2]).catch(nop); + + case 4: + _context20.next = 6; + return db.table3.bulkPut([{}], [{}]).catch(nop); + + case 6: + case 'end': + return _context20.stop(); + } + } + }, _callee19, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context21.stop(); + } + } + }, _callee20, this); +})); + +spawnedTest("updating using Table.update()", regeneratorRuntime.mark(function _callee23() { + return regeneratorRuntime.wrap(function _callee23$(_context24) { + while (1) { + switch (_context24.prev = _context24.next) { + case 0: + _context24.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee21() { + return regeneratorRuntime.wrap(function _callee21$(_context22) { + while (1) { + switch (_context22.prev = _context22.next) { + case 0: + _context22.next = 2; + return db.table1.add({ id: 1, address: { city: 'A' } }); + + case 2: + _context22.next = 4; + return db.table1.update(1, { "address.city": "B" }); + + case 4: + case 'end': + return _context22.stop(); + } + } + }, _callee21, this); + })); + }); + + case 2: + _context24.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee22() { + return regeneratorRuntime.wrap(function _callee22$(_context23) { + while (1) { + switch (_context23.prev = _context23.next) { + case 0: + _context23.next = 2; + return db.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }]); + + case 2: + _context23.next = 4; + return db.table3.update(1, { idx: 2 }).catch(nop); + + case 4: + _context23.next = 6; + return db.table3.update(1, 3).catch(nop); + + case 6: + case 'end': + return _context23.stop(); + } + } + }, _callee22, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context24.stop(); + } + } + }, _callee23, this); +})); + +spawnedTest("updating using Collection.modify()", regeneratorRuntime.mark(function _callee26() { + return regeneratorRuntime.wrap(function _callee26$(_context27) { + while (1) { + switch (_context27.prev = _context27.next) { + case 0: + _context27.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee24() { + return regeneratorRuntime.wrap(function _callee24$(_context25) { + while (1) { + switch (_context25.prev = _context25.next) { + case 0: + _context25.next = 2; + return db.table1.add({ id: 1, address: { city: 'A' } }); + + case 2: + _context25.next = 4; + return db.table1.where('id').equals(1).modify({ "address.city": "B" }); + + case 4: + case 'end': + return _context25.stop(); + } + } + }, _callee24, this); + })); + }); + + case 2: + _context27.next = 4; + return verifyErrorFlows(function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee25() { + return regeneratorRuntime.wrap(function _callee25$(_context26) { + while (1) { + switch (_context26.prev = _context26.next) { + case 0: + _context26.next = 2; + return db.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }]); + + case 2: + _context26.next = 4; + return db.table3.where('id').equals(1).modify({ idx: 2 }).catch(nop); + + case 4: + _context26.next = 6; + return db.table3.where('id').equals(1).modify(function () { + throw "apa"; + }).catch(nop); + + case 6: + case 'end': + return _context26.stop(); + } + } + }, _callee25, this); + })).catch(nop); + }); + + case 4: + case 'end': + return _context27.stop(); + } + } + }, _callee26, this); +})); + +// +// DELETING hook tests +// +// Ways to produce DELETEs: +// Table.delete(key) +// Table.bulkDetele(keys) +// Table.clear() +// Collection.modify() +// Collection.delete() + +spawnedTest("deleting using Table.delete(key)", regeneratorRuntime.mark(function _callee28() { + return regeneratorRuntime.wrap(function _callee28$(_context29) { + while (1) { + switch (_context29.prev = _context29.next) { + case 0: + _context29.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee27() { + return regeneratorRuntime.wrap(function _callee27$(_context28) { + while (1) { + switch (_context28.prev = _context28.next) { + case 0: + _context28.next = 2; + return db.table1.add({ id: 1 }); + + case 2: + _context28.next = 4; + return db.table1.delete(1); + + case 4: + case 'end': + return _context28.stop(); + } + } + }, _callee27, this); + })); + }); + + case 2: + case 'end': + return _context29.stop(); + } + } + }, _callee28, this); +})); + +spawnedTest("deleting using Table.bulkDelete(key)", regeneratorRuntime.mark(function _callee30() { + return regeneratorRuntime.wrap(function _callee30$(_context31) { + while (1) { + switch (_context31.prev = _context31.next) { + case 0: + _context31.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee29() { + return regeneratorRuntime.wrap(function _callee29$(_context30) { + while (1) { + switch (_context30.prev = _context30.next) { + case 0: + _context30.next = 2; + return db.table1.add({ id: 1 }); + + case 2: + _context30.next = 4; + return db.table1.bulkDelete([1]); + + case 4: + case 'end': + return _context30.stop(); + } + } + }, _callee29, this); + })); + }); + + case 2: + case 'end': + return _context31.stop(); + } + } + }, _callee30, this); +})); + +spawnedTest("deleting using Table.clear()", regeneratorRuntime.mark(function _callee32() { + return regeneratorRuntime.wrap(function _callee32$(_context33) { + while (1) { + switch (_context33.prev = _context33.next) { + case 0: + _context33.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee31() { + return regeneratorRuntime.wrap(function _callee31$(_context32) { + while (1) { + switch (_context32.prev = _context32.next) { + case 0: + _context32.next = 2; + return db.table1.add({ id: 1 }); + + case 2: + _context32.next = 4; + return db.table1.clear(); + + case 4: + case 'end': + return _context32.stop(); + } + } + }, _callee31, this); + })); + }); + + case 2: + case 'end': + return _context33.stop(); + } + } + }, _callee32, this); +})); + +spawnedTest("deleting using Table.modify()", regeneratorRuntime.mark(function _callee34() { + return regeneratorRuntime.wrap(function _callee34$(_context35) { + while (1) { + switch (_context35.prev = _context35.next) { + case 0: + _context35.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee33() { + return regeneratorRuntime.wrap(function _callee33$(_context34) { + while (1) { + switch (_context34.prev = _context34.next) { + case 0: + _context34.next = 2; + return db.table1.add({ id: 1 }); + + case 2: + _context34.next = 4; + return db.table1.where('id').between(0, 2).modify(function () { + delete this.value; + }); + + case 4: + case 'end': + return _context34.stop(); + } + } + }, _callee33, this); + })); + }); + + case 2: + case 'end': + return _context35.stop(); + } + } + }, _callee34, this); +})); + +spawnedTest("deleting using Collection.delete()", regeneratorRuntime.mark(function _callee36() { + return regeneratorRuntime.wrap(function _callee36$(_context37) { + while (1) { + switch (_context37.prev = _context37.next) { + case 0: + _context37.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db.transaction('rw', db.tables, regeneratorRuntime.mark(function _callee35() { + return regeneratorRuntime.wrap(function _callee35$(_context36) { + while (1) { + switch (_context36.prev = _context36.next) { + case 0: + _context36.next = 2; + return db.table1.add({ id: 1 }); + + case 2: + _context36.next = 4; + return db.table1.where('id').between(0, 2).delete(); + + case 4: + case 'end': + return _context36.stop(); + } + } + }, _callee35, this); + })); + }); + + case 2: + case 'end': + return _context37.stop(); + } + } + }, _callee36, this); +})); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var async$1 = Dexie.async; + +var db$1 = new Dexie("TestIssuesDB"); +db$1.version(1).stores({ + users: "id,first,last,&username,*&email,*pets", + keyless: ",name", + foo: "id" + // If required for your test, add more tables here +}); + +QUnit.module("misc", { + setup: function () { + QUnit.stop(); + resetDatabase(db$1).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} +}); + +// +// Misc Tests +// + +QUnit.asyncTest("Adding object with falsy keys", function () { + db$1.keyless.add({ name: "foo" }, 1).then(function (id) { + QUnit.equal(id, 1, "Normal case ok - Object with key 1 was successfully added."); + return db$1.keyless.add({ name: "bar" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could add a numeric falsy value (0)"); + return db$1.keyless.add({ name: "foobar" }, ""); + }).then(function (id) { + QUnit.equal(id, "", "Could add a string falsy value ('')"); + return db$1.keyless.put({ name: "bar2" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could put a numeric falsy value (0)"); + return db$1.keyless.put({ name: "foobar2" }, ""); + }).then(function (id) { + QUnit.equal(id, "", "Could put a string falsy value ('')"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("#102 Passing an empty array to anyOf throws exception", async$1(regeneratorRuntime.mark(function _callee() { + var count; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return db$1.users.where("username").anyOf([]).count(); + + case 3: + count = _context.sent; + + QUnit.equal(count, 0, "Zarro items matched the query anyOf([])"); + _context.next = 10; + break; + + case 7: + _context.prev = 7; + _context.t0 = _context['catch'](0); + + QUnit.ok(false, "Error when calling anyOf([]): " + _context.t0); + + case 10: + _context.prev = 10; + + QUnit.start(); + return _context.finish(10); + + case 13: + case 'end': + return _context.stop(); + } + } + }, _callee, this, [[0, 7, 10, 13]]); +}))); + +spawnedTest("#248 'modifications' object in 'updating' hook can be bizarre", regeneratorRuntime.mark(function _callee2() { + var numCreating, numUpdating, CustomDate, creatingHook, updatingHook, readingHook, testDate, testDate2, retrieved; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + readingHook = function readingHook(obj) { + if (obj.date && obj.date instanceof Date) { + obj.date = new CustomDate(obj.date); + } + return obj; + }; + + updatingHook = function updatingHook(modifications, primKey, obj) { + ++numUpdating; + var date = modifications.date; + if (date && date instanceof CustomDate) { + return { date: new Date(date._year, date._month, date._day) }; + } + }; + + creatingHook = function creatingHook(primKey, obj) { + ++numCreating; + var date = obj.date; + if (date && date instanceof CustomDate) { + obj.date = new Date(date._year, date._month, date._day); + } + }; + + CustomDate = function CustomDate(realDate) { + this._year = new Date(realDate).getFullYear(); + this._month = new Date(realDate).getMonth(); + this._day = new Date(realDate).getDate(); + this._millisec = new Date(realDate).getTime(); + //... + }; + + numCreating = 0, numUpdating = 0; + + + db$1.foo.hook('creating', creatingHook); + db$1.foo.hook('reading', readingHook); + db$1.foo.hook('updating', updatingHook); + testDate = new CustomDate(new Date(2016, 5, 11)); + + QUnit.equal(testDate._year, 2016, "CustomDate has year 2016"); + QUnit.equal(testDate._month, 5, "CustomDate has month 5"); + QUnit.equal(testDate._day, 11, "CustomDate has day 11"); + testDate2 = new CustomDate(new Date(2016, 5, 12)); + _context2.prev = 13; + + db$1.foo.add({ id: 1, date: testDate }); + + _context2.next = 17; + return db$1.foo.get(1); + + case 17: + retrieved = _context2.sent; + + + QUnit.ok(retrieved.date instanceof CustomDate, "Got a CustomDate object when retrieving object"); + QUnit.equal(retrieved.date._day, 11, "The CustomDate is on day 11"); + db$1.foo.put({ id: 1, date: testDate2 }); + + _context2.next = 23; + return db$1.foo.get(1); + + case 23: + retrieved = _context2.sent; + + + QUnit.ok(retrieved.date.constructor === CustomDate, "Got a CustomDate object when retrieving object"); + QUnit.equal(retrieved.date._day, 12, "The CustomDate is now on day 12"); + + // Check that hooks has been called expected number of times + QUnit.equal(numCreating, 1, "creating hook called once"); + QUnit.equal(numUpdating, 1, "updating hook called once"); + + case 28: + _context2.prev = 28; + + db$1.foo.hook('creating').unsubscribe(creatingHook); + db$1.foo.hook('reading').unsubscribe(readingHook); + db$1.foo.hook('updating').unsubscribe(updatingHook); + return _context2.finish(28); + + case 33: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this, [[13,, 28, 33]]); +})); + +QUnit.asyncTest("Issue: Broken Promise rejection #264", 1, function () { + db$1.open().then(function () { + return db$1.users.where('id').equals('does-not-exist').first(); + }).then(function (result) { + return Promise.reject(undefined); + }).catch(function (err) { + QUnit.equal(err, undefined, "Should catch the rejection"); + }).then(function (res) { + QUnit.start(); + }).catch(function (err) { + QUnit.start(); + }); +}); + +QUnit.asyncTest("#323 @gitawego's post. Should not fail unexpectedly on readonly properties", function () { + var Foo = function () { + function Foo() { + _classCallCheck(this, Foo); + } + + _createClass(Foo, [{ + key: 'synced', + get: function () { + return false; + } + }]); + + return Foo; + }(); + + db$1.foo.mapToClass(Foo); + + db$1.transaction('rw', db$1.foo, function () { + db$1.foo.put({ id: 1 }); + db$1.foo.where('id').equals(1).modify({ + synced: true + }); + }).catch(function (e) { + QUnit.ok(false, "Could not update it: " + (e.stack || e)); + }).then(function () { + QUnit.ok(true, "Could update it"); + return db$1.foo.get(1); + }).then(function (foo) { + return db$1.foo.get(1); + }).then(function (foo) { + console.log("Wow, it could get it even though it's mapped to a class that forbids writing that property."); + }).catch(function (e) { + QUnit.ok(true, 'Got error from get: ' + (e.stack || e)); + }).then(function () { + return db$1.foo.toArray(); + }).then(function (array) { + console.log('Got array of length: ' + array.length); + }).catch(function (e) { + QUnit.ok(true, 'Got error from toArray: ' + (e.stack || e)); + return db$1.foo.each(function (item) { + return console.log(item); + }); + }).then(function (array) { + console.log('Could do each'); + }).catch(function (e) { + QUnit.ok(true, 'Got error from each(): ' + (e.stack || e)); + return db$1.foo.toCollection().sortBy('synced'); + }).then(function (array) { + console.log('Could do sortBy'); + }).catch(function (e) { + QUnit.ok(true, 'Got error from sortBy(): ' + (e.stack || e)); + }).finally(QUnit.start); +}); + +var db$2 = new Dexie("TestYieldDb"); +var async$2 = Dexie.async; +var spawn$1 = Dexie.spawn; + +db$2.version(1).stores({ + friends: '++id,name,*groups', + pets: '++id,name' +}); + +QUnit.module("yield", { + setup: function () { + QUnit.stop(); + resetDatabase(db$2).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} +}); + +QUnit.asyncTest("db.transaction() with yield", async$2(regeneratorRuntime.mark(function _callee2() { + var finallyWasReached; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + finallyWasReached = false; + _context2.prev = 1; + _context2.next = 4; + return db$2.transaction('rw', 'friends', 'pets', regeneratorRuntime.mark(function _callee() { + var catId, dogId, gurra, gurrasPets; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return db$2.pets.add({ name: "Tito", kind: "cat" }); + + case 2: + catId = _context.sent; + _context.next = 5; + return db$2.pets.add({ name: "Josephina", kind: "dog" }); + + case 5: + dogId = _context.sent; + + // Add a friend who owns the pets + db$2.friends.add({ name: "Gurra G", pets: [catId, dogId] }); + + _context.next = 9; + return db$2.friends.where('name').equals("Gurra G").first(); + + case 9: + gurra = _context.sent; + + QUnit.ok(!!gurra, "Gurra could be found with yield"); + + // Now retrieve the pet objects that Gurra is referring to: + _context.next = 13; + return db$2.pets.where('id').anyOf(gurra.pets).toArray(); + + case 13: + gurrasPets = _context.sent; + + QUnit.equal(gurrasPets.length, 2, "Gurras all two pets could be retrieved via yield"); + QUnit.equal(gurrasPets[0].kind, "cat", "Gurras first pet is a cat"); + QUnit.equal(gurrasPets[1].kind, "dog", "Gurras second pet is a dog"); + + case 17: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + case 4: + _context2.next = 9; + break; + + case 6: + _context2.prev = 6; + _context2.t0 = _context2['catch'](1); + + QUnit.ok(false, "Caught error: " + _context2.t0); + + case 9: + _context2.prev = 9; + + finallyWasReached = true; + return _context2.finish(9); + + case 12: + QUnit.ok(finallyWasReached, "finally was reached"); + QUnit.start(); + + case 14: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this, [[1, 6, 9, 12]]); +}))); + +QUnit.asyncTest("Catching indexedDB error event", 2, async$2(regeneratorRuntime.mark(function _callee3() { + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.prev = 0; + _context3.next = 3; + return db$2.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" }); + + case 3: + QUnit.ok(true, "Should come so far"); + _context3.next = 6; + return db$2.pets.add({ id: 1, name: "Todoo", kind: "Snake" }); + + case 6: + // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + _context3.next = 12; + break; + + case 9: + _context3.prev = 9; + _context3.t0 = _context3['catch'](0); + + QUnit.equal(_context3.t0.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + + case 12: + QUnit.start(); + + case 13: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this, [[0, 9]]); +}))); + +QUnit.asyncTest("Catching error prevents transaction from aborting", 5, async$2(regeneratorRuntime.mark(function _callee5() { + return regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.prev = 0; + _context5.next = 3; + return db$2.transaction('rw', 'pets', regeneratorRuntime.mark(function _callee4() { + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.prev = 0; + _context4.next = 3; + return db$2.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" }); + + case 3: + QUnit.ok(true, "Should come so far"); + _context4.next = 6; + return db$2.pets.add({ id: 1, name: "Todoo", kind: "Snake" }); + + case 6: + // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + _context4.next = 12; + break; + + case 9: + _context4.prev = 9; + _context4.t0 = _context4['catch'](0); + + QUnit.equal(_context4.t0.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + + case 12: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this, [[0, 9]]); + })); + + case 3: + QUnit.ok(true, "Should come here - transaction committed because we caught the error"); + + _context5.next = 6; + return db$2.pets.get(1); + + case 6: + _context5.t0 = _context5.sent; + QUnit.ok(_context5.t0, "A pet with ID 1 exists in DB"); + _context5.next = 10; + return db$2.pets.get(1); + + case 10: + _context5.t1 = _context5.sent.name; + QUnit.equal(_context5.t1, "Tidi", "It was Tidi in the first position"); + + case 12: + _context5.prev = 12; + + QUnit.start(); + return _context5.finish(12); + + case 15: + case 'end': + return _context5.stop(); + } + } + }, _callee5, this, [[0,, 12, 15]]); +}))); + +QUnit.asyncTest("Transaction not committing when not catching error event", 4, async$2(regeneratorRuntime.mark(function _callee7() { + return regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.prev = 0; + _context7.next = 3; + return db$2.transaction('rw', 'pets', regeneratorRuntime.mark(function _callee6() { + return regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return db$2.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" }); + + case 2: + QUnit.ok(true, "Should come so far"); + _context6.next = 5; + return db$2.pets.add({ id: 1, name: "Todoo", kind: "Snake" }); + + case 5: + // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + + case 6: + case 'end': + return _context6.stop(); + } + } + }, _callee6, this); + })); + + case 3: + QUnit.ok(false, "Should not come here"); + + _context7.next = 14; + break; + + case 6: + _context7.prev = 6; + _context7.t0 = _context7['catch'](0); + + + QUnit.ok(true, "Transaction should fail"); + QUnit.equal(_context7.t0.name, "ConstraintError", "Error caught was a ConstraintError!"); + _context7.next = 12; + return db$2.pets.count(); + + case 12: + _context7.t1 = _context7.sent; + QUnit.equal(_context7.t1, 0, "Pets table should still be empty because transaction failed"); + + case 14: + _context7.prev = 14; + + QUnit.start(); + return _context7.finish(14); + + case 17: + case 'end': + return _context7.stop(); + } + } + }, _callee7, this, [[0, 6, 14, 17]]); +}))); + +QUnit.asyncTest("Should allow yielding a non-promise", async$2(regeneratorRuntime.mark(function _callee8() { + var x; + return regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + _context8.prev = 0; + _context8.next = 3; + return 3; + + case 3: + x = _context8.sent; + + QUnit.equal(x, 3, "Could yield a non-promise"); + _context8.next = 10; + break; + + case 7: + _context8.prev = 7; + _context8.t0 = _context8['catch'](0); + + QUnit.ok(false, "Yielding a non-Thenable wasn't be allowed"); + + case 10: + _context8.prev = 10; + + QUnit.start(); + return _context8.finish(10); + + case 13: + case 'end': + return _context8.stop(); + } + } + }, _callee8, this, [[0, 7, 10, 13]]); +}))); + +QUnit.asyncTest("Should allow yielding an array with a mix of values and thenables", async$2(regeneratorRuntime.mark(function _callee9() { + var results; + return regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.prev = 0; + _context9.next = 3; + return [1, 2, Dexie.Promise.resolve(3)]; + + case 3: + results = _context9.sent; + + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + _context9.next = 13; + break; + + case 10: + _context9.prev = 10; + _context9.t0 = _context9['catch'](0); + + QUnit.ok(false, "Got exception when trying to do yield an array of mixed values/promises"); + + case 13: + _context9.prev = 13; + + QUnit.start(); + return _context9.finish(13); + + case 16: + case 'end': + return _context9.stop(); + } + } + }, _callee9, this, [[0, 10, 13, 16]]); +}))); + +QUnit.asyncTest("Should allow yielding an array of non-promises only", async$2(regeneratorRuntime.mark(function _callee10() { + var results; + return regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + _context10.prev = 0; + _context10.next = 3; + return [1, 2, 3]; + + case 3: + results = _context10.sent; + + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + _context10.next = 13; + break; + + case 10: + _context10.prev = 10; + _context10.t0 = _context10['catch'](0); + + QUnit.ok(false, _context10.t0); + + case 13: + _context10.prev = 13; + + QUnit.start(); + return _context10.finish(13); + + case 16: + case 'end': + return _context10.stop(); + } + } + }, _callee10, this, [[0, 10, 13, 16]]); +}))); + +QUnit.asyncTest("Should allow yielding an empty array", async$2(regeneratorRuntime.mark(function _callee11() { + var results; + return regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + _context11.prev = 0; + _context11.next = 3; + return []; + + case 3: + results = _context11.sent; + + QUnit.equal(results.length, 0, "Yielded array is of size 0"); + _context11.next = 10; + break; + + case 7: + _context11.prev = 7; + _context11.t0 = _context11['catch'](0); + + QUnit.ok(false, _context11.t0); + + case 10: + _context11.prev = 10; + + QUnit.start(); + return _context11.finish(10); + + case 13: + case 'end': + return _context11.stop(); + } + } + }, _callee11, this, [[0, 7, 10, 13]]); +}))); + +QUnit.asyncTest("Should allow yielding an array of different kind of any kind of promise", function () { + spawn$1(regeneratorRuntime.mark(function _callee12() { + var results; + return regeneratorRuntime.wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return [Promise.resolve(1), Dexie.Promise.resolve(2), Promise.resolve(3)]; + + case 2: + results = _context12.sent; + + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + return _context12.abrupt('return', 4); + + case 8: + case 'end': + return _context12.stop(); + } + } + }, _callee12, this); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Throw after yield 1", function () { + spawn$1(regeneratorRuntime.mark(function _callee13() { + return regeneratorRuntime.wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + _context13.prev = 0; + _context13.next = 3; + return Promise.resolve(3); + + case 3: + QUnit.ok(true, "yielded a value"); + throw "error"; + + case 7: + _context13.prev = 7; + _context13.t0 = _context13['catch'](0); + + QUnit.ok(_context13.t0 === "error", "Catched exception: " + _context13.t0); + + case 10: + return _context13.abrupt('return', 4); + + case 11: + case 'end': + return _context13.stop(); + } + } + }, _callee13, this, [[0, 7]]); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Throw after yield 2", function () { + Promise.resolve(spawn$1(regeneratorRuntime.mark(function _callee14() { + return regeneratorRuntime.wrap(function _callee14$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + _context14.prev = 0; + _context14.next = 3; + return 3; + + case 3: + QUnit.ok(true, "yielded a value"); + throw "error"; + + case 7: + _context14.prev = 7; + _context14.t0 = _context14['catch'](0); + + QUnit.ok(_context14.t0 === "error", "Catched exception: " + _context14.t0); + + case 10: + return _context14.abrupt('return', 4); + + case 11: + case 'end': + return _context14.stop(); + } + } + }, _callee14, this, [[0, 7]]); + }))).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Throw before yield", function () { + Promise.resolve(spawn$1(regeneratorRuntime.mark(function _callee15() { + return regeneratorRuntime.wrap(function _callee15$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + _context15.prev = 0; + throw "error"; + + case 4: + _context15.prev = 4; + _context15.t0 = _context15['catch'](0); + + QUnit.ok(_context15.t0 === "error", "Catched exception: " + _context15.t0); + + case 7: + return _context15.abrupt('return', 4); + + case 8: + case 'end': + return _context15.stop(); + } + } + }, _callee15, this, [[0, 4]]); + }))).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Catch rejected promise", function () { + spawn$1(regeneratorRuntime.mark(function _callee16() { + return regeneratorRuntime.wrap(function _callee16$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + _context16.prev = 0; + _context16.next = 3; + return new Promise(function (resolve, reject) { + reject("fault fault!"); + }); + + case 3: + QUnit.ok(false, "Shouldn't come here"); + _context16.next = 9; + break; + + case 6: + _context16.prev = 6; + _context16.t0 = _context16['catch'](0); + + QUnit.ok(_context16.t0 === "fault fault!", "Catched exception: " + _context16.t0); + + case 9: + return _context16.abrupt('return', 4); + + case 10: + case 'end': + return _context16.stop(); + } + } + }, _callee16, this, [[0, 6]]); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Catch rejected promise in an array", function () { + spawn$1(regeneratorRuntime.mark(function _callee17() { + return regeneratorRuntime.wrap(function _callee17$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + _context17.prev = 0; + _context17.next = 3; + return [1, 2, new Promise(function (resolve, reject) { + reject("fault fault!"); + }), 4]; + + case 3: + QUnit.ok(false, "Shouldn't come here"); + _context17.next = 9; + break; + + case 6: + _context17.prev = 6; + _context17.t0 = _context17['catch'](0); + + QUnit.ok(_context17.t0 === "fault fault!", "Catched exception: " + _context17.t0); + + case 9: + return _context17.abrupt('return', 4); + + case 10: + case 'end': + return _context17.stop(); + } + } + }, _callee17, this, [[0, 6]]); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Should allow returning a promise", function () { + spawn$1(regeneratorRuntime.mark(function _callee18() { + return regeneratorRuntime.wrap(function _callee18$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt('return', Promise.resolve(3)); + + case 1: + case 'end': + return _context18.stop(); + } + } + }, _callee18, this); + })).then(function (result) { + QUnit.equal(result, 3, "Returning a directly should also be allowed"); + }).catch(function (e) { + QUnit.ok(false, e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Should be able to do 'return yield Promise.resolve(x);'", function () { + spawn$1(regeneratorRuntime.mark(function _callee19() { + return regeneratorRuntime.wrap(function _callee19$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return Promise.resolve(3); + + case 2: + return _context19.abrupt('return', _context19.sent); + + case 3: + case 'end': + return _context19.stop(); + } + } + }, _callee19, this); + })).then(function () { + QUnit.ok(true, "Should be able to do 'return yield Promise.resolve(x);'"); + }).catch(function (e) { + QUnit.ok(false, "Error occurred: " + e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Arrow functions and let", async$2(regeneratorRuntime.mark(function _callee20() { + var x, y; + return regeneratorRuntime.wrap(function _callee20$(_context20) { + while (1) { + switch (_context20.prev = _context20.next) { + case 0: + _context20.next = 2; + return [1, 2, Promise.resolve(3)]; + + case 2: + x = _context20.sent; + y = x.map(function (a) { + return a - 1; + }); + + QUnit.equal(y[0], 0); + QUnit.equal(y[1], 1); + QUnit.equal(y[2], 2); + QUnit.start(); + + case 8: + case 'end': + return _context20.stop(); + } + } + }, _callee20, this); +}))); + +QUnit.asyncTest("Calling sub async function", async$2(regeneratorRuntime.mark(function _callee21() { + var addFriend, deleteFriends, foo, bar, numDeleted; + return regeneratorRuntime.wrap(function _callee21$(_context23) { + while (1) { + switch (_context23.prev = _context23.next) { + case 0: + addFriend = async$2(regeneratorRuntime.mark(function addFriend(friend) { + var friendId; + return regeneratorRuntime.wrap(function addFriend$(_context21) { + while (1) { + switch (_context21.prev = _context21.next) { + case 0: + _context21.next = 2; + return db$2.friends.add(friend); + + case 2: + friendId = _context21.sent; + _context21.next = 5; + return db$2.friends.get(friendId); + + case 5: + return _context21.abrupt('return', _context21.sent); + + case 6: + case 'end': + return _context21.stop(); + } + } + }, addFriend, this); + })); + deleteFriends = async$2(regeneratorRuntime.mark(function deleteFriends() { + return regeneratorRuntime.wrap(function deleteFriends$(_context22) { + while (1) { + switch (_context22.prev = _context22.next) { + case 0: + _context22.next = 2; + return db$2.friends.where('name').anyOf("Foo", "Bar").delete(); + + case 2: + return _context22.abrupt('return', _context22.sent); + + case 3: + case 'end': + return _context22.stop(); + } + } + }, deleteFriends, this); + })); + _context23.prev = 2; + _context23.next = 5; + return addFriend({ name: "Foo" }); + + case 5: + foo = _context23.sent; + _context23.next = 8; + return addFriend({ name: "Bar" }); + + case 8: + bar = _context23.sent; + + QUnit.ok(foo.name == "Foo", "Foo got its name"); + QUnit.ok(bar.name == "Bar", "Bar got its name"); + _context23.next = 13; + return deleteFriends(); + + case 13: + numDeleted = _context23.sent; + + QUnit.ok(true, numDeleted + " friends successfully deleted"); + _context23.next = 20; + break; + + case 17: + _context23.prev = 17; + _context23.t0 = _context23['catch'](2); + + QUnit.ok(false, _context23.t0); + + case 20: + _context23.prev = 20; + + QUnit.start(); + return _context23.finish(20); + + case 23: + case 'end': + return _context23.stop(); + } + } + }, _callee21, this, [[2, 17, 20, 23]]); +}))); + +var db$3 = new Dexie("TestDBWhereClause"); +db$3.version(1).stores({ + folders: "++id,&path", + files: "++id,filename,extension,[filename+extension],folderId", + people: "[name+number],name,number", + friends: "++id,name,age", + chart: '[patno+row+col], patno' +}); + +var Folder = db$3.folders.defineClass({ + id: Number, + path: String, + description: String +}); + +var File = db$3.files.defineClass({ + id: Number, + filename: String, + extension: String, + folderId: Number +}); + +File.prototype.getFullPath = function () { + var file = this; + return db$3.folders.get(this.folderId, function (folder) { + return folder.path + "/" + file.filename + (file.extension || ""); + }); +}; + +Folder.prototype.getFiles = function () { + return db$3.files.where('folderId').equals(this.id).toArray(); +}; + +var Chart = db$3.chart.defineClass({ + patno: Number, + row: Number, + col: Number, + sym: Number +}); +Chart.prototype.save = function () { + return db$3.chart.put(this); +}; + +var firstFolderId = 0; +var lastFolderId = 0; +var firstFileId = 0; +var lastFileId = 0; + +db$3.on("populate", function () { + var folders = db$3.table("folders"); + var files = db$3.table("files"); + folders.add({ path: "/", description: "Root folder" }).then(function (id) { + firstFolderId = id; + }); + folders.add({ path: "/usr" }); // 2 + folders.add({ path: "/usr/local" }); // 3 + folders.add({ path: "/usr/local/bin" }).then(function (id) { + // 4 + files.add({ filename: "Hello", folderId: id }).then(function (fileId) { + firstFileId = fileId; + }); + files.add({ filename: "hello", extension: ".exe", folderId: id }); + }); + folders.add({ path: "/usr/local/src" }).then(function (id) { + // 5 + files.add({ filename: "world", extension: ".js", folderId: id }); + files.add({ filename: "README", extension: ".TXT", folderId: id }); + }); + folders.add({ path: "/usr/local/var" }); // 6 + folders.add({ path: "/USR/local/VAR" }); // 7 + folders.add({ path: "/var" }); // 8 + folders.add({ path: "/var/bin" }).then(function (id) { + // 9 + lastFolderId = id; + return files.add({ filename: "hello-there", extension: ".exe", folderId: id }); + }).then(function (id) { + lastFileId = id; + }); +}); + +QUnit.module("WhereClause", { + setup: function () { + QUnit.stop(); + resetDatabase(db$3).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} +}); + +spawnedTest('Issue#31 Compound Index with anyOf', regeneratorRuntime.mark(function _callee() { + var items; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (supports('compound')) { + _context.next = 2; + break; + } + + return _context.abrupt('return', QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")); + + case 2: + _context.next = 4; + return db$3.people.bulkAdd([{ + name: 0, + number: 0, + tag: "A" + }, { + name: -1, + number: 0, + tag: "B" + }, { + name: -2, + number: 0, + tag: "C" + }, { + name: -3, + number: 0, + tag: "D" + }]); + + case 4: + _context.next = 6; + return db$3.people.where('[name+number]').anyOf([[-2, 0], [-3, 0]]) // https://github.com/dfahlander/Dexie.js/issues/31 + .toArray(); + + case 6: + items = _context.sent; + + + QUnit.equal(items.length, 2, "It should contain 2 items."); + QUnit.equal(items[0].tag, "D", "First we should get D"); + QUnit.equal(items[1].tag, "C", "then we should get C"); + + case 10: + case 'end': + return _context.stop(); + } + } + }, _callee, this); +})); + +QUnit.asyncTest("startsWithAnyOf()", function () { + + function runTheTests(mippler) { + /// + + // + // Basic Flow: + // + return mippler(db$3.folders.where('path').startsWithAnyOf('/usr/local', '/var')).toArray(function (result) { + QUnit.equal(result.length, 6, "Query should match 6 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local'; + }), '/usr/local'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var'; + }), '/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + + // + // Require a slash at beginning (and use an array of strings as argument instead) + // + return mippler(db$3.folders.where('path').startsWithAnyOf(['/usr/local/', '/var/'])).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 4, "Query should match 4 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + + // + // Some specialities + // + return Dexie.Promise.all(mippler(db$3.folders.where('path').startsWithAnyOf([])).count(), // Empty + mippler(db$3.folders.where('path').startsWithAnyOf('/var', '/var', '/var')).count(), // Duplicates + mippler(db$3.folders.where('path').startsWithAnyOf('')).count(), // Empty string should match all + mippler(db$3.folders).count(), mippler(db$3.folders.where('path').startsWithAnyOf('nonexisting')).count() // Non-existing match + ); + }).then(function (results) { + QUnit.equal(results[0], 0, "startsWithAnyOf([]).count() == 0"); + QUnit.equal(results[1], 2, "startsWithAnyOf('/var', '/var', '/var') == 2"); + QUnit.equal(results[2], results[3], "startsWithAnyOf('').count() == db.folders.count()"); + QUnit.equal(results[4], 0, "startsWithAnyOf('nonexisting').count() == 0"); + + // + // Error handling + // + + return mippler(db$3.folders.where('path').startsWithAnyOf([null, '/'])).toArray(function (res) { + QUnit.ok(false, "Should not succeed to have null in parameter"); + }).catch(function (e) { + QUnit.ok(true, "As expected: failed to have null in arguments: " + e); + }); + }); + } + + // Run tests without transaction and without reverse() + runTheTests(function (x) { + return x; + }).then(function () { + QUnit.ok(true, "FINISHED NORMAL TEST!"); + // Run tests with reverse() + return runTheTests(function (x) { + return x.reverse(); + }); + }).then(function () { + QUnit.ok(true, "FINISHED REVERSE TEST!"); + // Run tests within a transaction + return db$3.transaction('r', db$3.folders, db$3.files, function () { + return runTheTests(function (x) { + return x; + }); + }); + }).then(function () { + QUnit.ok(true, "FINISHED TRANSACTION TEST!"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("anyOf()", function () { + db$3.transaction("r", db$3.files, db$3.folders, function () { + + db$3.files.where("filename").anyOf("hello", "hello-there", "README", "gösta").toArray(function (a) { + QUnit.equal(a.length, 3, "Should find 3 files"); + QUnit.equal(a[0].filename, "README", "First match is README because capital R comes before lower 'h' in lexical sort"); + QUnit.equal(a[1].filename, "hello", "Second match is hello"); + QUnit.equal(a[2].filename, "hello-there", "Third match is hello-there"); + + a[0].getFullPath().then(function (fullPath) { + QUnit.equal(fullPath, "/usr/local/src/README.TXT", "Full path of README.TXT is: " + fullPath); + }); + a[1].getFullPath().then(function (fullPath) { + QUnit.equal(fullPath, "/usr/local/bin/hello.exe", "Full path of hello.exe is: " + fullPath); + }); + a[2].getFullPath().then(function (fullPath) { + QUnit.equal("/var/bin/hello-there.exe", fullPath, "Full path of hello-there.exe is: " + fullPath); + }); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("anyOf(integerArray)", function () { + // Testing bug #11 Integer Indexes in anyOf handled incorrectly + db$3.files.put({ id: 9000, filename: "new file 1", folderId: firstFolderId }); + db$3.files.put({ id: 10000, filename: "new file 2", folderId: firstFolderId }); + db$3.files.where('id').anyOf([9000, 11000]).toArray(function (a) { + QUnit.equal(a.length, 1, "Should be only one found entry"); + QUnit.equal(a[0].id, 9000, "Item no 9000 should be found"); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("anyOf(emptyArray)", function () { + db$3.files.where('id').anyOf([]).toArray(function (a) { + QUnit.equal(a.length, 0, "Should be empty"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("equalsIgnoreCase()", function () { + + db$3.files.where("filename").equalsIgnoreCase("hello").toArray(function (a) { + QUnit.equal(a.length, 2, "Got two files"); + QUnit.equal(a[0].filename, "Hello", "First file is Hello"); + QUnit.equal(a[1].filename, "hello", "Second file is hello"); + QUnit.start(); + }); +}); + +QUnit.asyncTest("equalsIgnoreCase() 2", function () { + var folder = new Folder(); + folder.path = "/etc"; + folder.description = "Slasktratten"; + db$3.folders.add(folder).then(function (folderId) { + var filenames = ["", "\t ", "AA", "AAron", "APAN JAPAN", "APAN japaö", "APGALEN", "APaLAT", "APaÖNSKAN", "APalster", "Aaron", "Apan JapaN", "Apan Japaa", "Apan Japan", "Gösta", "apan JA", "apan JAPA", "apan JAPAA", "apan JAPANer", "apan JAPAÖ", "apan japan", "apan japanER", "östen"]; + + var fileArray = filenames.map(function (filename) { + var file = new File(); + file.filename = filename; + file.folderId = folderId; + return file; + }); + + db$3.transaction("rw", db$3.files, function () { + fileArray.forEach(function (file) { + db$3.files.add(file); + }); + + db$3.files.where("filename").equalsIgnoreCase("apan japan").toArray(function (a) { + QUnit.equal(a.length, 4, "There should be 4 files with that name"); + QUnit.equal(a[0].filename, "APAN JAPAN", "APAN JAPAN"); + QUnit.equal(a[1].filename, "Apan JapaN", "Apan JapaN"); + QUnit.equal(a[2].filename, "Apan Japan", "Apan Japan"); + QUnit.equal(a[3].filename, "apan japan", "apan japan"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + }).finally(QUnit.start); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + QUnit.start(); + }); +}); + +QUnit.asyncTest("equalsIgnoreCase() 2 descending", function () { + var folder = new Folder(); + folder.path = "/etc"; + folder.description = "Slasktratten"; + db$3.folders.add(folder).then(function (folderId) { + var filenames = ["", "\t ", "AA", "AAron", "APAN JAPAN", "APAN japaö", "APGALEN", "APaLAT", "APaÖNSKAN", "APalster", "Aaron", "Apan JapaN", "Apan Japaa", "Apan Japan", "Gösta", "apan JA", "apan JAPA", "apan JAPAA", "apan JAPANer", "apan JAPAÖ", "apan japan", "apan japanER", "östen"]; + + var fileArray = filenames.map(function (filename) { + var file = new File(); + file.filename = filename; + file.folderId = folderId; + return file; + }); + + db$3.transaction("rw", db$3.files, function () { + + fileArray.forEach(function (file) { + db$3.files.add(file); + }); + + db$3.files.where("filename").equalsIgnoreCase("apan japan").and(function (f) { + return f.folderId === folderId; + }) // Just for fun - only look in the newly created /etc folder. + .reverse().toArray(function (a) { + QUnit.equal(a.length, 4, "There should be 4 files with that name in " + folder.path); + QUnit.equal(a[0].filename, "apan japan", "apan japan"); + QUnit.equal(a[1].filename, "Apan Japan", "Apan Japan"); + QUnit.equal(a[2].filename, "Apan JapaN", "Apan JapaN"); + QUnit.equal(a[3].filename, "APAN JAPAN", "APAN JAPAN"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + QUnit.start(); + }).finally(QUnit.start); + }); +}); + +QUnit.asyncTest("equalsIgnoreCase() 3 (first key shorter than needle)", function () { + if (typeof idbModules !== 'undefined' && Dexie.dependencies.indexedDB === idbModules.shimIndexedDB) { + // Using indexedDBShim. + QUnit.ok(false, "This test would hang with IndexedDBShim as of 2015-05-07"); + QUnit.start(); + return; + } + db$3.transaction("rw", db$3.files, function () { + db$3.files.clear(); + db$3.files.add({ filename: "Hello-there-", folderId: 1 }); + db$3.files.add({ filename: "hello-there-", folderId: 1 }); + db$3.files.add({ filename: "hello-there-everyone", folderId: 1 }); + db$3.files.add({ filename: "hello-there-everyone-of-you!", folderId: 1 }); + // Ascending + db$3.files.where("filename").equalsIgnoreCase("hello-there-everyone").toArray(function (a) { + QUnit.equal(a.length, 1, "Should find one file"); + QUnit.equal(a[0].filename, "hello-there-everyone", "First file is " + a[0].filename); + }); + // Descending + db$3.files.where("filename").equalsIgnoreCase("hello-there-everyone").reverse().toArray(function (a) { + QUnit.equal(a.length, 1, "Should find one file"); + QUnit.equal(a[0].filename, "hello-there-everyone", "First file is " + a[0].filename); + }); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("startsWithIgnoreCase()", function () { + db$3.transaction("r", db$3.folders, function () { + + db$3.folders.count(function (count) { + QUnit.ok(true, "Number of folders in database: " + count); + db$3.folders.where("path").startsWithIgnoreCase("/").toArray(function (a) { + QUnit.equal(a.length, count, "Got all folder objects because all of them starts with '/'"); + }); + }); + + db$3.folders.where("path").startsWithIgnoreCase("/usr").toArray(function (a) { + QUnit.equal(a.length, 6, "6 folders found: " + a.map(function (folder) { + return '"' + folder.path + '"'; + }).join(', ')); + }); + + db$3.folders.where("path").startsWithIgnoreCase("/usr").reverse().toArray(function (a) { + QUnit.equal(a.length, 6, "6 folders found in reverse mode: " + a.map(function (folder) { + return '"' + folder.path + '"'; + }).join(', ')); + }); + }).then(function () { + QUnit.ok(true, "Transaction complete"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("queryingNonExistingObj", function () { + db$3.files.where("filename").equals("fdsojifdsjoisdf").toArray(function (a) { + QUnit.equal(a.length, 0, "File fdsojifdsjoisdf was not found"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); +}); + +if (!supports("compound")) { + QUnit.test("compound-index", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); + QUnit.test("compound-primkey (Issue #37)", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); + QUnit.test("Issue #31 - Compound Index with anyOf", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); + QUnit.test("Erratic behavior of between #190", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); +} else { + QUnit.asyncTest("compound-index", 2, function () { + db$3.transaction("r", db$3.files, function () { + db$3.files.where("[filename+extension]").equals(["README", ".TXT"]).toArray(function (a) { + QUnit.equal(a.length, 1, "Found one file by compound index search"); + QUnit.equal(a[0].filename, "README", "The found file was README.TXT"); + }); + }).catch(function (e) { + QUnit.ok(false, e + ". Expected to fail on IE10/IE11 - no support compound indexs."); + }).finally(QUnit.start); + }); + + QUnit.asyncTest("compound-primkey (Issue #37)", function () { + db$3.transaction('rw', db$3.people, function () { + db$3.people.add({ name: "Santaclaus", number: 123 }); + db$3.people.add({ name: "Santaclaus", number: 124 }); + db$3.people.add({ name: "Santaclaus2", number: 1 }); + return db$3.people.get(["Santaclaus", 123]); + }).then(function (santa) { + QUnit.ok(!!santa, "Got santa"); + QUnit.equal(santa.name, "Santaclaus", "Santa's name is correct"); + QUnit.equal(santa.number, 123, "Santa's number is correct"); + + return db$3.people.where("[name+number]").between(["Santaclaus", 1], ["Santaclaus", 200]).toArray(); + }).then(function (santas) { + QUnit.equal(santas.length, 2, "Got two santas"); + }).catch(function (e) { + QUnit.ok(false, "Failed (will fail in IE without polyfill):" + e); + }).finally(QUnit.start); + }); + + QUnit.asyncTest("Issue #31 - Compound Index with anyOf", function () { + db$3.files.where("[filename+extension]").anyOf([["hello", ".exe"], ["README", ".TXT"]]).toArray(function (a) { + QUnit.equal(a.length, 2, "Should find two files"); + QUnit.equal(a[0].filename, "README", "First comes the uppercase README.TXT"); + QUnit.equal(a[1].filename, "hello", "Second comes the lowercase hello.exe"); + }).catch(function (e) { + QUnit.ok(false, "Failed (will fail in IE without polyfill):" + e); + }).finally(QUnit.start); + }); + + QUnit.asyncTest("Erratic behavior of between #190", function () { + db$3.transaction("rw", db$3.chart, function () { + var chart = []; + for (var r = 1; r <= 2; r++) { + for (var c = 1; c <= 150; c++) { + chart.push({ patno: 1, + row: r, + col: c, + sym: 1 }); + } + } + db$3.chart.bulkAdd(chart); + }).then(function () { + var grid = [], + x1 = 91, + x2 = 130; + return db$3.chart.where("[patno+row+col]").between([1, 1, x1], [1, 1, x2], true, true).each(function (cell) { + grid.push(cell.sym); + }).then(function () { + QUnit.equal(grid.length, 40, "Should find 40 cells"); + //console.log("range " + x1 + "-" + x2 + " found " + grid.length); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e + " (Will fail in IE and Edge due to lack of compound primary keys)"); + }).finally(QUnit.start); + }); +} + +QUnit.asyncTest("above, aboveOrEqual, below, belowOrEqual, between", 32, function () { + db$3.folders.where('id').above(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 4, "Four folders have id above 5"); + QUnit.equal(a[0].path, "/usr/local/var"); + QUnit.equal(a[1].path, "/USR/local/VAR"); + QUnit.equal(a[2].path, "/var"); + QUnit.equal(a[3].path, "/var/bin"); + }).then(function () { + return db$3.folders.where('id').aboveOrEqual(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 5, "Five folders have id above or equal 5"); + QUnit.equal(a[0].path, "/usr/local/src"); + QUnit.equal(a[1].path, "/usr/local/var"); + QUnit.equal(a[2].path, "/USR/local/VAR"); + QUnit.equal(a[3].path, "/var"); + QUnit.equal(a[4].path, "/var/bin"); + }); + }).then(function () { + return db$3.folders.where('id').below(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 4, "Four folders have id below 5"); + QUnit.equal(a[0].path, "/"); + QUnit.equal(a[1].path, "/usr"); + QUnit.equal(a[2].path, "/usr/local"); + QUnit.equal(a[3].path, "/usr/local/bin"); + }); + }).then(function () { + return db$3.folders.where('id').belowOrEqual(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 5, "Five folders have id below or equal to 5"); + QUnit.equal(a[0].path, "/"); + QUnit.equal(a[1].path, "/usr"); + QUnit.equal(a[2].path, "/usr/local"); + QUnit.equal(a[3].path, "/usr/local/bin"); + QUnit.equal(a[4].path, "/usr/local/src"); + }); + }).then(function () { + return db$3.folders.where('id').between(firstFolderId, firstFolderId + 1).toArray(function (a) { + QUnit.equal(a.length, 1, "One folder between 1 and 2"); + QUnit.equal(a[0].id, firstFolderId, "Found item is number 1"); + }); + }).then(function () { + return db$3.folders.where('id').between(firstFolderId, firstFolderId + 1, true, false).toArray(function (a) { + QUnit.equal(a.length, 1, "One folder between 1 and 2 (including lower but not upper)"); + QUnit.equal(a[0].id, firstFolderId, "Found item is number 1"); + }); + }).then(function () { + return db$3.folders.where('id').between(firstFolderId, firstFolderId + 1, false, true).toArray(function (a) { + QUnit.equal(a.length, 1, "One folder between 1 and 2 (including upper but not lower)"); + QUnit.equal(a[0].id, firstFolderId + 1, "Found item is number 2"); + }); + }).then(function () { + return db$3.folders.where('id').between(firstFolderId, firstFolderId + 1, false, false).toArray(function (a) { + QUnit.equal(a.length, 0, "Zarro folders between 1 and 2 (neither including lower nor upper)"); + }); + }).then(function () { + return db$3.folders.where('id').between(firstFolderId, firstFolderId + 1, true, true).toArray(function (a) { + QUnit.equal(a.length, 2, "Two folder between 1 and 2 (including both lower and upper)"); + QUnit.equal(a[0].id, firstFolderId, "Number 1 among found items"); + QUnit.equal(a[1].id, firstFolderId + 1, "Number 2 among found items"); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("notEqual", function () { + db$3.folders.where('path').notEqual("/usr/local").sortBy("path", function (result) { + result = result.map(function (x) { + return x.path; + }); + QUnit.equal(JSON.stringify(result, null, 4), JSON.stringify(["/", "/USR/local/VAR", "/usr", + //"/usr/local" + "/usr/local/bin", "/usr/local/src", "/usr/local/var", "/var", "/var/bin"], null, 4), "/usr/local should be removed"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("noneOf", function () { + db$3.folders.where('path').noneOf("/usr/local", "/", "/var/bin", "not existing key").sortBy("path", function (result) { + result = result.map(function (x) { + return x.path; + }); + QUnit.equal(JSON.stringify(result, null, 4), JSON.stringify([ + //"/", + "/USR/local/VAR", "/usr", + //"/usr/local" + "/usr/local/bin", "/usr/local/src", "/usr/local/var", "/var"], null, 4), "Only items not specified in query should come into result"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("noneOf keys", function () { + db$3.folders.where('path').noneOf("/usr/local", "/", "/var/bin", "not existing key").keys(function (result) { + result = result.sort(function (a, b) { + return a < b ? -1 : a === b ? 0 : 1; + }); + QUnit.equal(JSON.stringify(result, null, 4), JSON.stringify([ + //"/", + "/USR/local/VAR", "/usr", + //"/usr/local" + "/usr/local/bin", "/usr/local/src", "/usr/local/var", "/var"], null, 4), "Only keys not specified in query should come into result"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("inAnyOfRanges", function () { + db$3.transaction('rw', db$3.friends, function () { + db$3.friends.bulkAdd([{ name: "Simon", age: 3 }, { name: "Tyra", age: 0 }, { name: "David", age: 42 }, { name: "Ylva", age: 40 }, { name: "Ann-Sofie", age: 72 }]).then(function () { + //equal(errors.length, 0, "bulkAdd() succeeded"); + return db$3.friends.where('age').inAnyRange([[0, 3], [65, Infinity]]).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 2, "Should give us two persons"); + QUnit.equal(result[0].name, "Tyra", "First is Tyra"); + QUnit.equal(result[1].name, "Ann-Sofie", "Second is Ann-Sofie"); + return db$3.friends.where("age").inAnyRange([[0, 3], [65, Infinity]], { includeUppers: true }).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 3, "Should give us three persons"); + QUnit.equal(result[0].name, "Tyra", "First is Tyra"); + QUnit.equal(result[1].name, "Simon", "Second is Simon"); + QUnit.equal(result[2].name, "Ann-Sofie", "Third is Ann-Sofie"); + return db$3.friends.where("age").inAnyRange([[0, 3], [65, Infinity]], { includeLowers: false }).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 1, "Should give us one person"); + QUnit.equal(result[0].name, "Ann-Sofie", "Ann-Sofie is the only match"); + return db$3.friends.where("age").inAnyRange([[40, 40], [40, 40], [40, 41], [41, 41], [42, 42]], { includeUppers: true }).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 2, "Should give us two persons"); + QUnit.equal(result[0].name, "Ylva", "First is Ylva"); + QUnit.equal(result[1].name, "David", "Second is David"); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("anyOfIgnoreCase", function () { + db$3.transaction('r', db$3.folders, db$3.files, function () { + db$3.folders.where('path').anyOfIgnoreCase("/usr/local/var", "/").toArray(function (result) { + QUnit.equal(result.length, 3); + QUnit.equal(result[0].path, "/"); + QUnit.equal(result[1].path, "/USR/local/VAR"); + QUnit.equal(result[2].path, "/usr/local/var"); + return db$3.folders.where('path').anyOfIgnoreCase("/usr/local/var", "/").reverse().toArray(); + }).then(function (result) { + QUnit.equal(result.length, 3); + QUnit.equal(result[0].path, "/usr/local/var"); + QUnit.equal(result[1].path, "/USR/local/VAR"); + QUnit.equal(result[2].path, "/"); + return db$3.files.where('filename').anyOfIgnoreCase(["hello", "world", "readme"]).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 4); + QUnit.equal(result[0].filename, "Hello"); + QUnit.equal(result[1].filename, "README"); + QUnit.equal(result[2].filename, "hello"); + QUnit.equal(result[3].filename, "world"); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); +QUnit.asyncTest("anyOfIgnoreCase(2)", function () { + db$3.files.where('filename').anyOfIgnoreCase(["hello", "world", "readme"]).toArray(function (result) { + QUnit.equal(result.length, 4); + QUnit.equal(result[0].filename, "Hello"); + QUnit.equal(result[1].filename, "README"); + QUnit.equal(result[2].filename, "hello"); + QUnit.equal(result[3].filename, "world"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("startsWithAnyOfIgnoreCase()", function () { + + function runTheTests(mippler) { + /// + + // + // Basic Flow: + // + return mippler(db$3.folders.where('path').startsWithAnyOfIgnoreCase('/usr/local', '/var')).toArray(function (result) { + QUnit.equal(result.length, 7, "Query should match 7 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/USR/local/VAR'; + }), '/USR/local/VAR'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local'; + }), '/usr/local'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var'; + }), '/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + + // + // Require a slash at beginning (and use an array of strings as argument instead) + // + return mippler(db$3.folders.where('path').startsWithAnyOfIgnoreCase(['/usr/local/', '/var/'])).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 5, "Query should match 5 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/USR/local/VAR'; + }), '/USR/local/VAR'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + + // + // Some specialities + // + return Dexie.Promise.all(mippler(db$3.folders.where('path').startsWithAnyOfIgnoreCase([])).count(), // Empty + mippler(db$3.folders.where('path').startsWithAnyOfIgnoreCase('/var', '/var', '/var')).count(), // Duplicates + mippler(db$3.folders.where('path').startsWithAnyOfIgnoreCase('')).count(), // Empty string should match all + mippler(db$3.folders).count(), mippler(db$3.folders.where('path').startsWithAnyOfIgnoreCase('nonexisting')).count() // Non-existing match + ); + }).then(function (results) { + QUnit.equal(results[0], 0, "startsWithAnyOfIgnoreCase([]).count() == 0"); + QUnit.equal(results[1], 2, "startsWithAnyOfIgnoreCase('/var', '/var', '/var').count() == 2"); + QUnit.equal(results[2], results[3], "startsWithAnyOfIgnoreCase('').count() == db.folders.count()"); + QUnit.equal(results[4], 0, "startsWithAnyOfIgnoreCase('nonexisting').count() == 0"); + + // + // Error handling + // + + return mippler(db$3.folders.where('path').startsWithAnyOfIgnoreCase([null, '/'])).toArray(function (res) { + QUnit.ok(false, "Should not succeed to have null in parameter"); + }).catch(function (e) { + QUnit.ok(true, "As expected: failed to have null in arguments: " + e); + }); + }); + } + + // Run tests without transaction and without reverse() + runTheTests(function (x) { + return x; + }).then(function () { + QUnit.ok(true, "FINISHED NORMAL TEST!"); + // Run tests with reverse() + return runTheTests(function (x) { + return x.reverse(); + }); + }).then(function () { + QUnit.ok(true, "FINISHED REVERSE TEST!"); + // Run tests within a transaction + return db$3.transaction('r', db$3.folders, db$3.files, function () { + return runTheTests(function (x) { + return x; + }); + }); + }).then(function () { + QUnit.ok(true, "FINISHED TRANSACTION TEST!"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); +}); + +var db$4 = new Dexie("TestDBCollection"); +db$4.version(1).stores({ users: "id,first,last,&username,*&email,*pets" }); + +var User = db$4.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String] +}); +db$4.on("populate", function () { + db$4.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$4.users.add({ id: 2, first: "Karl", last: "Cedersköld", username: "kceder", email: ["karl@ceder.what"], pets: [] }); +}); + +QUnit.module("collection", { + setup: function () { + QUnit.stop(); + resetDatabase(db$4).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} +}); + +spawnedTest("and with values", regeneratorRuntime.mark(function _callee() { + var array; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return db$4.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]).and(function (user) { + return user.username === "dfahlander"; + }).toArray(); + + case 2: + array = _context.sent; + + QUnit.equal(array.length, 1, "Should find one user with given criteria"); + + case 4: + case 'end': + return _context.stop(); + } + } + }, _callee, this); +})); + +spawnedTest("and with keys", regeneratorRuntime.mark(function _callee2() { + var keys; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return db$4.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]).and(function (user) { + return user.username === "dfahlander"; + }).keys(); + + case 2: + keys = _context2.sent; + + QUnit.equal(keys.length, 1, "Should find one user with given criteria"); + + case 4: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); +})); + +spawnedTest("and with delete", regeneratorRuntime.mark(function _callee3() { + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return db$4.users.orderBy('username').and(function (u) { + return QUnit.ok(!!u, "User should exist here"); + }).delete(); + + case 2: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); +})); + +QUnit.asyncTest("each", 3, function () { + var array = []; + db$4.users.orderBy("id").each(function (user) { + array.push(user); + }).then(function () { + QUnit.equal(array.length, 2, "Got two users"); + QUnit.equal(array[0].first, "David", "First is David"); + QUnit.equal(array[1].first, "Karl", "Second is Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); +QUnit.asyncTest("count", 1, function () { + db$4.users.count(function (count) { + QUnit.equal(count, 2, "Two objects in table"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); +QUnit.asyncTest("toArray", 3, function () { + db$4.users.orderBy("last").toArray(function (a) { + QUnit.equal(a.length, 2, "Array length is 2"); + QUnit.equal(a[0].first, "Karl", "First is Karl"); + QUnit.equal(a[1].first, "David", "Second is David"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); +QUnit.asyncTest("limit", 6, function () { + db$4.transaction("r", db$4.users, function () { + db$4.users.orderBy("last").limit(1).toArray(function (a) { + QUnit.equal(a.length, 1, "Array length is 1"); + QUnit.equal(a[0].first, "Karl", "First is Karl"); + }); + + db$4.users.orderBy("last").limit(10).toArray(function (a) { + QUnit.equal(a.length, 2, "Array length is 2"); + }); + + db$4.users.orderBy("last").limit(0).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + + db$4.users.orderBy("last").limit(-1).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + + db$4.users.orderBy("id").limit(-1).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("offset().limit() with advanced combinations", 22, function () { + db$4.transaction("rw", db$4.users, function () { + for (var i = 0; i < 10; ++i) { + db$4.users.add({ id: 3 + i, first: "First" + i, last: "Last" + i, username: "user" + i, email: ["user" + i + "@abc.se"] }); + } + + // Using algorithm + count() + db$4.users.where("first").startsWithIgnoreCase("first").count(function (count) { + QUnit.equal(count, 10, "Counting all 10"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").limit(5).count(function (count) { + QUnit.equal(count, 5, "algorithm + count(): limit(5).count()"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(7).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).count()"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "algorithm + count(): offset(6).limit(4)"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).limit(4)"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(17).limit(4).count(function (count) { + QUnit.equal(count, 0, "algorithm + count(): offset(17).limit(4)"); + }); + // Using algorithm + toArray() + db$4.users.where("first").startsWithIgnoreCase("first").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "algorithm + toArray(): limit(5)"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7)"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "algorithm + toArray(): offset(6).limit(4)"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7).limit(4)"); + }); + db$4.users.where("first").startsWithIgnoreCase("first").offset(17).limit(4).toArray(function (a) { + QUnit.equal(a.length, 0, "algorithm + toArray(): offset(17).limit(4)"); + }); + // Using IDBKeyRange + count() + db$4.users.where("first").startsWith("First").count(function (count) { + QUnit.equal(count, 10, "IDBKeyRange + count() - count all 10"); + }); + db$4.users.where("first").startsWith("First").limit(5).count(function (count) { + QUnit.equal(count, 5, "IDBKeyRange + count(): limit(5)"); + }); + db$4.users.where("first").startsWith("First").offset(7).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7)"); + }); + db$4.users.where("first").startsWith("First").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "IDBKeyRange + count(): offset(6)"); + }); + db$4.users.where("first").startsWith("First").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7).limit(4)"); + }); + db$4.users.where("first").startsWith("First").offset(17).limit(4).count(function (count) { + QUnit.equal(count, 0, "IDBKeyRange + count(): offset(17).limit(4)"); + }); + // Using IDBKeyRange + toArray() + db$4.users.where("first").startsWith("First").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "IDBKeyRange + toArray(): limit(5)"); + }); + db$4.users.where("first").startsWith("First").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7)"); + }); + db$4.users.where("first").startsWith("First").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "IDBKeyRange + toArray(): offset(6).limit(4)"); + }); + db$4.users.where("first").startsWith("First").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7).limit(4)"); + }); + db$4.users.where("first").startsWith("First").offset(17).limit(4).toArray(function (a) { + QUnit.equal(a.length, 0, "IDBKeyRange + toArray(): offset(17).limit(4)"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("first", 1, function () { + db$4.users.orderBy("last").first(function (karlCeder) { + QUnit.equal(karlCeder.first, "Karl", "Got Karl"); + }).finally(QUnit.start); +}); +QUnit.asyncTest("last", function () { + db$4.users.orderBy("last").last(function (david) { + QUnit.equal(david.first, "David", "Got David"); + }).finally(QUnit.start); +}); +QUnit.asyncTest("and", 2, function () { + db$4.transaction("r", db$4.users, function () { + + db$4.users.where("first").equalsIgnoreCase("david").and(function (user) { + return user.email.indexOf("apa") >= 0; + }).first(function (user) { + QUnit.equal(user, null, "Found no user with first name 'david' and email 'apa'"); + }); + + db$4.users.where("first").equalsIgnoreCase("david").and(function (user) { + return user.email.indexOf("daw@thridi.com") >= 0; + }).first(function (user) { + QUnit.equal(user.first, "David", "Found user with first name 'david' and email 'daw@thridi.com'"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("reverse", function () { + db$4.transaction("r", db$4.users, function () { + db$4.users.orderBy("first").reverse().first(function (user) { + QUnit.equal(user.first, "Karl", "Got Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +if (!supports("multiEntry")) { + QUnit.test("distinct", function () { + return QUnit.ok(true, "SKIPPED - MULTIENTRY UNSUPPORTED"); + }); +} else { + QUnit.asyncTest("distinct", function () { + db$4.transaction("r", db$4.users, function () { + + db$4.users.where("email").startsWithIgnoreCase("d").toArray(function (a) { + QUnit.equal(a.length, 2, "Got two duplicates of David since he has two email addresses starting with 'd' (Fails on IE10, IE11 due to not supporting multivalued array indexes)"); + }); + db$4.users.where("email").startsWithIgnoreCase("d").distinct().toArray(function (a) { + QUnit.equal(a.length, 1, "Got single instance of David since we used the distinct() method. (Fails on IE10, IE11 due to not supporting multivalued array indexes)"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); +} + +QUnit.asyncTest("modify", function () { + db$4.transaction("rw", db$4.users, function () { + var currentTime = new Date(); + db$4.users.toCollection().modify({ + lastUpdated: currentTime + }).then(function (count) { + QUnit.equal(count, 2, "Promise supplied the number of modifications made"); + }); + db$4.users.toArray(function (a) { + QUnit.equal(a.length, 2, "Length ok"); + QUnit.equal(a[0].first, "David", "First is David"); + QUnit.equal(a[0].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on David"); + QUnit.equal(a[1].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("modify-using-function", function () { + db$4.transaction("rw", db$4.users, function () { + var currentTime = new Date(); + db$4.users.toCollection().modify(function (user) { + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$4.users.toArray(function (a) { + QUnit.equal(a.length, 2); + QUnit.equal(a[0].first, "David"); + QUnit.equal(a[0].fullName, "David Fahlander", "Could modify David with a getter function"); + QUnit.equal(a[0].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on David"); + QUnit.equal(a[1].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("modify-causing-error", 2, function () { + db$4.transaction("rw", db$4.users, function () { + var currentTime = new Date(); + db$4.users.toCollection().modify(function (user) { + user.id = 1; + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$4.users.toArray(function (a) { + QUnit.ok(false, "Should not come here, beacuse we should get error when setting all primkey to 1"); + }); + }).catch(Dexie.ModifyError, function (e) { + QUnit.ok(true, "Got ModifyError: " + e); + QUnit.equal(e.successCount, 1, "Succeeded with the first entry but not the second"); + }).catch(function (e) { + QUnit.ok(false, "Another error than the expected was thrown: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("delete", 2, function () { + db$4.users.orderBy("id").delete().then(function (count) { + QUnit.equal(count, 2, "All two records deleted"); + return db$4.users.count(function (count) { + QUnit.equal(count, 0, "No users in collection anymore"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("delete(2)", 3, function () { + db$4.transaction("rw", db$4.users, function () { + db$4.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$4.users.where("first").equalsIgnoreCase("david").delete().then(function (deleteCount) { + QUnit.equal(deleteCount, 2, "Two items deleted (Both davids)"); + }); + db$4.users.toArray(function (a) { + QUnit.equal(a.length, 1, "Deleted one user"); + QUnit.equal(a[0].first, "Karl", "Only Karl is there now"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("delete(3, combine with OR)", 3, function () { + db$4.transaction("rw", db$4.users, function () { + db$4.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$4.users.where("first").equals("dAvid").or("username").equals("kceder").delete().then(function (deleteCount) { + QUnit.equal(deleteCount, 2, "Two items deleted (Both dAvid Helenius and Karl Cedersköld)"); + }); + db$4.users.toArray(function (a) { + QUnit.equal(a.length, 1, "Only one item left since dAvid and Karl have been deleted"); + QUnit.equal(a[0].first, "David", "Only David Fahlander is there now!"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("keys", function () { + db$4.users.orderBy("first").keys(function (a) { + QUnit.ok(a.length, 2); + QUnit.equal(a[0], "David", "First is David"); + QUnit.equal(a[1], "Karl", "Second is Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("uniqueKeys", function () { + db$4.transaction("rw", db$4.users, function () { + db$4.users.add({ id: 3, first: "David", last: "Helenius", username: "dahel" }); + db$4.users.orderBy("first").keys(function (a) { + QUnit.ok(a.length, 3, "when not using uniqueKeys, length is 3"); + QUnit.equal(a[0], "David", "First is David"); + QUnit.equal(a[1], "David", "Second is David"); + QUnit.equal(a[2], "Karl", "Third is Karl"); + }); + db$4.users.orderBy("first").uniqueKeys(function (a) { + QUnit.ok(a.length, 2, "when using uniqueKeys, length is 2"); + QUnit.equal(a[0], "David", "First is David"); + QUnit.equal(a[1], "Karl", "Second is Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("primaryKeys", function () { + db$4.users.orderBy("last").primaryKeys(function (a) { + QUnit.ok(a.length, 2); + QUnit.equal(a[0], 2, "Second is Karl"); + QUnit.equal(a[1], 1, "First is David"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("primaryKeys2", function () { + db$4.users.orderBy("first").primaryKeys(function (a) { + QUnit.ok(a.length, 2); + QUnit.equal(a[0], 1, "First is David"); + QUnit.equal(a[1], 2, "Second is Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("eachKey and eachUniqueKey", function () { + db$4.transaction("rw", db$4.users, function () { + db$4.users.add({ id: 3, first: "Ylva", last: "Fahlander", username: "yfahlander" }); + var a = []; + db$4.users.orderBy("last").eachKey(function (lastName) { + a.push(lastName); + }).then(function () { + QUnit.equal(a.length, 3, "When using eachKey, number of keys are 3"); + }); + var a2 = []; + db$4.users.orderBy("last").eachUniqueKey(function (lastName) { + a2.push(lastName); + }).then(function () { + QUnit.equal(a2.length, 2, "When using eachUniqueKey, number of keys are 2"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("or", 14, function () { + db$4.transaction("rw", db$4.users, function () { + db$4.users.add({ id: 3, first: "Apan", last: "Japan", username: "apanjapan" }); + db$4.users.where("first").equalsIgnoreCase("david").or("last").equals("Japan").sortBy("first", function (a) { + QUnit.equal(a.length, 2, "Got two users"); + QUnit.equal(a[0].first, "Apan", "First is Apan"); + QUnit.equal(a[1].first, "David", "Second is David"); + }); + db$4.users.where("first").equalsIgnoreCase("david").or("last").equals("Japan").or("id").equals(2).sortBy("id", function (a) { + QUnit.equal(a.length, 3, "Got three users"); + QUnit.equal(a[0].first, "David", "First is David"); + QUnit.equal(a[1].first, "Karl", "Second is Karl"); + QUnit.equal(a[2].first, "Apan", "Third is Apan"); + }); + var userArray = []; + db$4.users.where("id").anyOf(1, 2, 3, 4).or("username").anyOf("dfahlander", "kceder", "apanjapan").each(function (user) { + QUnit.ok(true, "Found: " + JSON.stringify(user)); + userArray.push(user); + }).then(function () { + QUnit.equal(userArray.length, 3, "Got all three users"); + QUnit.ok(userArray.some(function (user) { + return user.first === "David"; + }), "David was found"); + QUnit.ok(userArray.some(function (user) { + return user.first === "Karl"; + }), "Karl was found"); + QUnit.ok(userArray.some(function (user) { + return user.first === "Apan"; + }), "Apan was found"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("or-issue#15-test", function () { + var db = new Dexie("MyDB_issue15"); + db.version(1).stores({ + phones: "++id, additionalFeatures, android, availability, battery, camera, connectivity, description, display, hardware, id, images, name, sizeAndWeight, storage" + }); + db.on('populate', function () { + QUnit.ok(true, "on(populate) called"); + for (var i = 0; i < 100; ++i) { + db.phones.add({ id: 3 + i, name: "Name" + randomString(16), additionalFeatures: [randomString(10)], android: 1, availability: 0, battery: 1, camera: 1 }); + } + + function randomString(count) { + var ms = []; + for (var i = 0; i < count; ++i) { + ms.push(String.fromCharCode(32 + Math.floor(Math.random() * 96))); + } + return ms.join(''); + } + }); + + db.open().catch(function (err) { + QUnit.ok(false, "DB ERROR: " + err); + }); + + var numRuns = 10; + + for (var i = 0; i < numRuns; ++i) { + + db.phones.where("name").startsWithIgnoreCase("name").or("id").below(50).toArray(function (a) { + + QUnit.equal(a.length, 100, "Found 100 phones"); + }).catch(function (err) { + + QUnit.ok(false, "error:" + err.stack); + }).finally(function () { + if (--numRuns == 0) { + // All test runs finished. Delete DB and exit unit test. + db.delete(); + QUnit.start(); + } + }); + } +}); + +QUnit.asyncTest("until", function () { + db$4.transaction("rw", db$4.users, function () { + db$4.users.add({ id: 3, first: "Apa1", username: "apa1" }); + db$4.users.add({ id: 4, first: "Apa2", username: "apa2" }); + db$4.users.add({ id: 5, first: "Apa3", username: "apa3" }); + + // Checking that it stops immediately when first item is the stop item: + db$4.users.orderBy(":id").until(function (user) { + return user.first == "David"; + }).toArray(function (a) { + QUnit.equal(0, a.length, "Stopped immediately because David has ID 1"); + }); + + // Checking that specifying includeStopEntry = true will include the stop entry. + db$4.users.orderBy(":id").until(function (user) { + return user.first == "David"; + }, true).toArray(function (a) { + QUnit.equal(1, a.length, "Got the stop entry when specifying includeStopEntry = true"); + QUnit.equal("David", a[0].first, "Name is David"); + }); + + // Checking that when sorting on first name and stopping on David, we'll get the apes. + db$4.users.orderBy("first").until(function (user) { + return user.first == "David"; + }).toArray(function (a) { + QUnit.equal(3, a.length, "Got 3 users only (3 apes) because the Apes comes before David and Karl when ordering by first name"); + QUnit.equal("apa1", a[0].username, "First is apa1"); + QUnit.equal("apa2", a[1].username, "Second is apa2"); + QUnit.equal("apa3", a[2].username, "Third is apa3"); + }); + + // Checking that reverse() affects the until() method as expected: + db$4.users.orderBy("first").reverse().until(function (user) { + return user.username == "apa2"; + }).toArray(function (a) { + QUnit.equal(3, a.length, "Got 3 users only (David, Karl and Apa3)"); + QUnit.equal("Karl", a[0].first, "When reverse(), First is Karl."); + QUnit.equal("David", a[1].first, "When reverse(), Second is David"); + QUnit.equal("Apa3", a[2].first, "When reverse(), Third is Apa3"); + }); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("firstKey", function () { + db$4.users.orderBy('last').firstKey(function (key) { + QUnit.equal("Cedersköld", key, "First lastName is Cedersköld"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("lastKey", function () { + db$4.users.orderBy('last').lastKey(function (key) { + QUnit.equal("Fahlander", key, "Last lastName is Fahlander"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("firstKey on primary key", function () { + db$4.users.toCollection().firstKey(function (key) { + QUnit.equal(key, 1, "First key is 1"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("lastKey on primary key", function () { + db$4.users.toCollection().lastKey(function (key) { + QUnit.equal(key, 2, "lastKey is 2"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("Promise chain from within each() operation", 2, function () { + db$4.transaction('r', db$4.users, function () { + db$4.users.each(function (user) { + db$4.users.where('id').equals(user.id).first(function (usr) { + return db$4.users.where('id').equals(usr.id).first(); + }).then(function (u) { + return u; + }).then(function (u2) { + QUnit.equal(u2.id, user.id, "Could get the same user after some chains of Promise.resolve()"); + }); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +var db$5 = new Dexie("TestDBTable"); +db$5.version(1).stores({ + users: "++id,first,last,&username,*&email,*pets", + folks: "++,first,last" +}); + +var User$1 = db$5.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String] +}); +var idOfFirstUser = 0; +var idOfLastUser = 0; + +db$5.on("populate", function (trans) { + db$5.users.add({ first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }).then(function (id) { + idOfFirstUser = id; + }); + db$5.users.add({ first: "Karl", last: "Faadersköld", username: "kceder", email: ["karl@ceder.what", "dadda@ceder.what"], pets: [] }).then(function (id) { + idOfLastUser = id; + }); +}); + +QUnit.module("table", { + setup: function () { + QUnit.stop(); + resetDatabase(db$5).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} +}); + +QUnit.asyncTest("get", 4, function () { + db$5.table("users").get(idOfFirstUser).then(function (obj) { + QUnit.equal(obj.first, "David", "Got the first object"); + return db$5.users.get(idOfLastUser); + }).then(function (obj) { + QUnit.equal(obj.first, "Karl", "Got the second object"); + return db$5.users.get("nonexisting key"); + }).then(function (obj) { + QUnit.ok(true, "Got then() even when getting non-existing object"); + QUnit.equal(obj, undefined, "Result is 'undefined' when not existing"); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("where", function () { + db$5.transaction("r", db$5.users, function () { + db$5.users.where("username").equals("kceder").first(function (user) { + QUnit.equal(user.first, "Karl", "where().equals()"); + }), db$5.users.where("id").above(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 1, "where().above()"); + }), db$5.users.where("id").aboveOrEqual(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 2, "where().aboveOrEqual()"); + }), db$5.users.where("id").below(idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().below().count()"); + }), db$5.users.where("id").below(idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().below().count() should be zero"); + }), db$5.users.where("id").belowOrEqual(idOfFirstUser).count(function (count) { + QUnit.ok(count == 1, "where().belowOrEqual()"); + }), db$5.users.where("id").between(idOfFirstUser, idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 1)"); + }), db$5.users.where("id").between(0, Infinity).count(function (count) { + QUnit.ok(count == 2, "where().between(0, Infinity)"); + }), db$5.users.where("id").between(idOfFirstUser, idOfFirstUser, true, true).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 1, true, true)"); + }), db$5.users.where("id").between(1, -1, true, true).count(function (count) { + QUnit.ok(count == 0, "where().between(1, -1, true, true)"); + }), db$5.users.where("id").between(idOfFirstUser, idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 2)"); + }), db$5.users.where("id").between(idOfFirstUser, idOfLastUser, true, true).count(function (count) { + QUnit.ok(count == 2, "where().between(1, 2, true, true)"); + }), db$5.users.where("id").between(idOfFirstUser, idOfLastUser, false, false).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 2, false, false)"); + }); + db$5.users.where("last").startsWith("Fah").toArray(function (a) { + QUnit.equal(a.length, 1, "where().startsWith(existing) only matches Fahlander, not Faadersköld"); + QUnit.equal(a[0].first, "David"); + }); + db$5.users.where("last").startsWith("Faa").toArray(function (a) { + QUnit.equal(a.length, 1, "where().startsWith(existing) only matches Faadersköld, not Fahlander"); + QUnit.equal(a[0].first, "Karl"); + }); + db$5.users.where("last").startsWith("Fa").toArray(function (a) { + QUnit.equal(a.length, 2, "length = 2 on: where().startsWith(2 existing)"); + QUnit.equal(a[0].first, "Karl", "Karl found first on last 'Faadersköld'"); + QUnit.equal(a[1].first, "David", "David found second on last 'Fahlander'"); + }); + db$5.users.where("last").anyOf("Fahlander", "Faadersköld").toArray(function (a) { + QUnit.equal(a.length, 2, "in() returned expected number of items"); + QUnit.equal(a[0].last, "Faadersköld", "Faadersköld is first"); + }); + db$5.users.where("last").anyOf("Fahlander", "Faadersköld").reverse().toArray(function (a) { + QUnit.equal(a.length, 2, "in().reverse() returned expected number of items"); + QUnit.equal(a[0].last, "Fahlander", "Fahlander is first"); + }); + db$5.users.where("last").anyOf("Faadersköld").toArray(function (a) { + QUnit.equal(a.length, 1, "in() returned expected number of items"); + }); + + if (supports("multiEntry")) { + db$5.users.where("email").equals("david@awarica.com").toArray(function (a) { + // Fails in IE with 0 due to that IE is not implementing to index string arrays. + QUnit.equal(a.length, 1, "Finding items from array members. Expect to fail on IE10/IE11."); + }); + db$5.users.where("email").startsWith("da").distinct().toArray(function (a) { + // Fails on IE with 0 + QUnit.equal(a.length, 2, "Found both because both have emails starting with 'da'. Expect to fail on IE10/IE11."); + }); + } else { + QUnit.ok(true, "SKIPPED - MULTIENTRY UNSUPPORTED"); + QUnit.ok(true, "SKIPPED - MULTIENTRY UNSUPPORTED"); + } + }).catch(function (e) { + QUnit.ok(false, "Transaction failed: " + e); + }).finally(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("count", function () { + db$5.users.count(function (count) { + QUnit.equal(count, 2, "Table.count()"); + }).catch(function (e) { + QUnit.ok(false, e.message); + }).finally(function () { + QUnit.start(); + }); +}); +QUnit.asyncTest("count with limit", function () { + db$5.users.limit(1).count(function (count) { + QUnit.equal(count, 1, "Table.limit().count()"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); +QUnit.asyncTest("limit(),orderBy(),modify(), abort(), reverse()", function () { + db$5.transaction("rw", db$5.users, function () { + // Modify first found user with a helloMessage + db$5.users.orderBy("first").reverse().limit(1).modify(function (user) { + user.helloMessage = "Hello " + user.first; + }); + + // Check that the modification went fine: + db$5.users.orderBy("first").reverse().toArray(function (a) { + QUnit.equal(a[0].first, "Karl", "First item is Karl"); + QUnit.equal(a[0].helloMessage, "Hello Karl", "Karl got helloMessage 'Hello Karl'"); + QUnit.equal(a[1].first, "David", "Second item is David"); + QUnit.ok(!a[1].helloMessage, "David was not modified due to limit()"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("filter", function () { + db$5.users.filter(function (user) { + return user.email.indexOf("david@awarica.com") != -1; + }).toArray(function (davids) { + QUnit.equal(1, davids.length, "Got one David"); + QUnit.equal("David", davids[0].first, "The name of the David is David"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("each", function () { + var users = []; + db$5.users.each(function (user) { + users.push(user); + }).then(function () { + QUnit.equal(users.length, 2, "Got 2 users"); + QUnit.equal(users[0].first, "David", "Got David"); + QUnit.equal(users[1].first, "Karl", "Got Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("put", function () { + db$5.transaction("rw", db$5.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db$5.users.put(newUser).then(function (id) { + QUnit.ok(id > idOfLastUser, "Got id " + id + " because we didnt supply an id"); + QUnit.equal(newUser.id, id, "The id property of the new user was set"); + }); + db$5.users.where("username").equals("aper").first(function (user) { + QUnit.equal(user.last, "Persbrant", "The correct item was actually added"); + user.last = "ChangedLastName"; + var currentId = user.id; + db$5.users.put(user).then(function (id) { + QUnit.equal(id, currentId, "Still got same id because we update same object"); + }); + db$5.users.where("last").equals("ChangedLastName").first(function (user) { + QUnit.equal(user.last, "ChangedLastName", "LastName was successfully changed"); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("put-no-transaction", function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db$5.users.put(newUser).then(function (id) { + QUnit.ok(id > idOfLastUser, "Got id " + id + " because we didnt supply an id"); + QUnit.equal(newUser.id, id, "The id property of the new user was set"); + return db$5.users.where("username").equals("aper").first(function (user) { + QUnit.equal(user.last, "Persbrant", "The correct item was actually added"); + user.last = "ChangedLastName"; + var userId = user.id; + return db$5.users.put(user).then(function (id) { + QUnit.equal(id, userId, "Still got same id because we update same object"); + return db$5.users.where("last").equals("ChangedLastName").first(function (user) { + QUnit.equal(user.last, "ChangedLastName", "LastName was successfully changed"); + }); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("add", function () { + db$5.transaction("rw", db$5.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + + db$5.users.add(newUser).then(function (id) { + QUnit.ok(id > idOfLastUser, "Got id " + id + " because we didnt supply an id"); + QUnit.equal(newUser.id, id, "The id property of the new user was set"); + }); + + db$5.users.where("username").equals("aper").first(function (user) { + QUnit.equal(user.last, "Persbrant", "The correct item was actually added"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); +}); + +spawnedTest("bulkAdd", regeneratorRuntime.mark(function _callee() { + var highestKey, result; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return db$5.users.add({ username: "fsdkljfd", email: ["fjkljslk"] }); + + case 2: + highestKey = _context.sent; + + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + _context.next = 6; + return db$5.users.delete(highestKey); + + case 6: + QUnit.ok(true, "Deleted test item"); + _context.next = 9; + return db$5.users.bulkAdd([{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }]); + + case 9: + result = _context.sent; + + QUnit.equal(result, highestKey + 2, "Result of bulkAdd() operation was equal to highestKey + 2"); + + case 11: + case 'end': + return _context.stop(); + } + } + }, _callee, this); +})); + +spawnedTest("bulkAdd-catching errors", regeneratorRuntime.mark(function _callee3() { + var newUsersX, newUsersY, newUsersZ; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return db$5.transaction("rw", db$5.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, // Should fail + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db$5.users.bulkAdd(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got BulkError: " + e.message); + QUnit.equal(e.failures.length, 1, "One error due to a duplicate username: " + e.failures[0]); + }); + + // Now, since we catched the error, the transaction should continue living. + db$5.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-added"); + }); + }); + + case 2: + _context3.next = 4; + return db$5.users.where("username").startsWith('aper').count(); + + case 4: + _context3.t0 = _context3.sent; + QUnit.equal(_context3.t0, 3, "Previous transaction committed"); + newUsersX = [{ first: "Xke1", last: "Persbrant1", username: "xper1", email: ["xper1@persbrant.net"] }, { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, // Should fail + { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] }]; + _context3.prev = 7; + _context3.next = 10; + return db$5.transaction("rw", db$5.users, function () { + db$5.users.bulkAdd(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + }); + + case 10: + QUnit.ok(false, "Should not come here"); + _context3.next = 16; + break; + + case 13: + _context3.prev = 13; + _context3.t1 = _context3['catch'](7); + + QUnit.ok(true, "Got: " + _context3.t1); + + case 16: + _context3.next = 18; + return db$5.users.where('username').startsWith('xper').count(); + + case 18: + _context3.t2 = _context3.sent; + QUnit.equal(_context3.t2, 0, "0 users! Good, means that previous transaction did not commit"); + _context3.next = 22; + return db$5.users.bulkAdd(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + }); + + case 22: + _context3.next = 24; + return db$5.users.where('username').startsWith('xper').count(); + + case 24: + _context3.t3 = _context3.sent; + QUnit.equal(_context3.t3, 3, "3 users! Good - means that previous operation catched and therefore committed"); + newUsersY = [{ first: "Yke1", last: "Persbrant1", username: "yper1", email: ["yper1@persbrant.net"] }, { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, // Should fail + { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] }]; + + // Now check that catching the operation via try..catch should also make it succeed. + + _context3.prev = 27; + _context3.next = 30; + return db$5.users.bulkAdd(newUsersY); + + case 30: + _context3.next = 35; + break; + + case 32: + _context3.prev = 32; + _context3.t4 = _context3['catch'](27); + + QUnit.ok(true, "Got: " + _context3.t4); + + case 35: + _context3.next = 37; + return db$5.users.where('username').startsWith('yper').count(); + + case 37: + _context3.t5 = _context3.sent; + QUnit.equal(_context3.t5, 3, "3 users! Good - means that previous operation catched (via try..yield..catch this time, and therefore committed"); + + + // Now check that catching and rethrowing should indeed make it fail + newUsersZ = [{ first: "Zke1", last: "Persbrant1", username: "zper1", email: ["zper1@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, // Should fail + { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] }]; + _context3.next = 42; + return db$5.transaction('rw', db$5.users, regeneratorRuntime.mark(function _callee2() { + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.prev = 0; + _context2.next = 3; + return db$5.users.bulkAdd(newUsersZ); + + case 3: + _context2.next = 8; + break; + + case 5: + _context2.prev = 5; + _context2.t0 = _context2['catch'](0); + throw _context2.t0; + + case 8: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this, [[0, 5]]); + })).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + }); + + case 42: + _context3.next = 44; + return db$5.users.where('username').startsWith('zper').count(); + + case 44: + _context3.t6 = _context3.sent; + QUnit.equal(_context3.t6, 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"); + + case 46: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this, [[7, 13], [27, 32]]); +})); + +spawnedTest("bulkAdd-non-inbound-autoincrement", regeneratorRuntime.mark(function _callee4() { + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return db$5.folks.bulkAdd([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }]); + + case 2: + _context4.next = 4; + return db$5.folks.where('first').equals('Foo').count(); + + case 4: + _context4.t0 = _context4.sent; + QUnit.equal(_context4.t0, 4, "Should be 4 Foos"); + _context4.next = 8; + return db$5.folks.where('last').equals('Bar').count(); + + case 8: + _context4.t1 = _context4.sent; + QUnit.equal(_context4.t1, 1, "Shoudl be 1 Bar"); + + case 10: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); +})); + +spawnedTest("bulkAdd-catch sub transaction", regeneratorRuntime.mark(function _callee5() { + return regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return db$5.transaction('rw', db$5.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, // Should fail + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db$5.transaction('rw', db$5.users, function () { + db$5.users.bulkAdd(newUsers); + }).then(function () { + QUnit.ok(false, "Should not succeed with all these operations"); + }).catch(function (e) { + QUnit.equal(e.failures.length, 1, "Should get one failure"); + }); + }).catch(function (e) { + QUnit.ok(true, "Outer transaction aborted due to inner transaction abort. This is ok: " + e); + }); + + case 2: + _context5.next = 4; + return db$5.users.where('username').startsWith('aper').count(); + + case 4: + _context5.t0 = _context5.sent; + QUnit.equal(_context5.t0, 0, "0 users! Good, means that inner transaction did not commit"); + + case 6: + case 'end': + return _context5.stop(); + } + } + }, _callee5, this); +})); + +spawnedTest("bulkPut", regeneratorRuntime.mark(function _callee6() { + var highestKey, existingFirstUserToReplace, result, ourAddedUsers, replacedDfahlander; + return regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return db$5.users.add({ username: "fsdkljfd", email: ["fjkljslk"] }); + + case 2: + highestKey = _context6.sent; + + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + _context6.next = 6; + return db$5.users.delete(highestKey); + + case 6: + QUnit.ok(true, "Deleted test item"); + _context6.next = 9; + return db$5.users.get(idOfFirstUser); + + case 9: + existingFirstUserToReplace = _context6.sent; + + QUnit.equal(existingFirstUserToReplace.username, "dfahlander", "Existing user should be dfahlander"); + _context6.next = 13; + return db$5.users.bulkPut([{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { id: idOfFirstUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]); + + case 13: + result = _context6.sent; + + QUnit.equal(result, highestKey + 2, "Result of bulkPut() operation was equal to highestKey + 2"); + _context6.next = 17; + return db$5.users.where('username').startsWith("aper").toArray(); + + case 17: + ourAddedUsers = _context6.sent; + + QUnit.equal(ourAddedUsers.length, 3, "Should have put 3 users there (two additions and one replaced"); + _context6.next = 21; + return db$5.users.get(idOfFirstUser); + + case 21: + replacedDfahlander = _context6.sent; + + QUnit.equal(replacedDfahlander.username, "aper2", "dfahlander Should now be aper2 instead"); + + case 23: + case 'end': + return _context6.stop(); + } + } + }, _callee6, this); +})); + +spawnedTest("bulkPut with overlapping objects", regeneratorRuntime.mark(function _callee7() { + var theOne; + return regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return db$5.users.bulkPut([{ + id: "sdjls83", + first: "Daveious" + }, { + id: "sdjls83", + last: "Olvono" + }]); + + case 2: + _context7.next = 4; + return db$5.users.get("sdjls83"); + + case 4: + theOne = _context7.sent; + + QUnit.equal(theOne.last, "Olvono", "Last item is the one inserted"); + QUnit.ok(theOne.first === undefined, "Object doesnt have a first property"); + + case 7: + case 'end': + return _context7.stop(); + } + } + }, _callee7, this); +})); + +spawnedTest("bulkPut-catching errors", regeneratorRuntime.mark(function _callee9() { + var newUsersX, newUsersY, newUsersZ; + return regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return db$5.transaction("rw", db$5.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { id: idOfLastUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, // update success + { id: idOfFirstUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, // update should fail + { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, // Add should fail + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db$5.users.bulkPut(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got BulkError: " + e.message); + QUnit.equal(e.failures.length, 2, "Two errors due to a duplicate username: " + e.failures[0]); + }); + + // Now, since we catched the error, the transaction should continue living. + db$5.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-putted"); + }); + }); + + case 2: + _context9.next = 4; + return db$5.users.where("username").startsWith('aper').count(); + + case 4: + _context9.t0 = _context9.sent; + QUnit.equal(_context9.t0, 3, "Previous transaction committed"); + newUsersX = [{ first: "Xke1", last: "Persbrant1", username: "xper1", email: ["xper1@persbrant.net"] }, { id: idOfLastUser, first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, // Should fail (add) + { id: idOfFirstUser, first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, // Should fail (update) + { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] }]; + _context9.prev = 7; + _context9.next = 10; + return db$5.transaction("rw", db$5.users, function () { + db$5.users.bulkPut(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + }); + + case 10: + QUnit.ok(false, "Should not come here"); + _context9.next = 16; + break; + + case 13: + _context9.prev = 13; + _context9.t1 = _context9['catch'](7); + + QUnit.ok(true, "Got: " + _context9.t1); + + case 16: + _context9.next = 18; + return db$5.users.where('username').startsWith('xper').count(); + + case 18: + _context9.t2 = _context9.sent; + QUnit.equal(_context9.t2, 0, "0 users! Good, means that previous transaction did not commit"); + _context9.next = 22; + return db$5.users.bulkPut(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + }); + + case 22: + _context9.next = 24; + return db$5.users.where('username').startsWith('xper').count(); + + case 24: + _context9.t3 = _context9.sent; + QUnit.equal(_context9.t3, 3, "Should count to 3 users because previous operation was catched and therefore should have been committed"); + newUsersY = [{ first: "Yke1", last: "Persbrant1", username: "yper1", email: ["yper1@persbrant.net"] }, { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, { id: idOfFirstUser, first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, // Should fail + { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, // Should fail + { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] }]; + + // Now check that catching the operation via try..catch should also make it succeed. + + _context9.prev = 27; + _context9.next = 30; + return db$5.users.bulkPut(newUsersY); + + case 30: + _context9.next = 35; + break; + + case 32: + _context9.prev = 32; + _context9.t4 = _context9['catch'](27); + + QUnit.ok(true, "Got: " + _context9.t4); + + case 35: + _context9.next = 37; + return db$5.users.where('username').startsWith('yper').count(); + + case 37: + _context9.t5 = _context9.sent; + QUnit.equal(_context9.t5, 3, "Should count to 3 users because previous previous operation catched (via try..yield..catch this time, and therefore should have been committed"); + + + // Now check that catching and rethrowing should indeed make it fail + newUsersZ = [{ first: "Zke1", last: "Persbrant1", username: "zper1", email: ["zper1@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, // Should fail + { id: idOfLastUser, first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, // Should fail + { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] }]; + _context9.next = 42; + return db$5.transaction('rw', db$5.users, regeneratorRuntime.mark(function _callee8() { + return regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + _context8.prev = 0; + _context8.next = 3; + return db$5.users.bulkPut(newUsersZ); + + case 3: + _context8.next = 8; + break; + + case 5: + _context8.prev = 5; + _context8.t0 = _context8['catch'](0); + throw _context8.t0; + + case 8: + case 'end': + return _context8.stop(); + } + } + }, _callee8, this, [[0, 5]]); + })).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + }); + + case 42: + _context9.next = 44; + return db$5.users.where('username').startsWith('zper').count(); + + case 44: + _context9.t6 = _context9.sent; + QUnit.equal(_context9.t6, 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"); + + case 46: + case 'end': + return _context9.stop(); + } + } + }, _callee9, this, [[7, 13], [27, 32]]); +})); + +spawnedTest("bulkPut-non-inbound-autoincrement", regeneratorRuntime.mark(function _callee10() { + return regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + _context10.next = 2; + return db$5.folks.bulkPut([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }]); + + case 2: + _context10.next = 4; + return db$5.folks.where('first').equals('Foo').count(); + + case 4: + _context10.t0 = _context10.sent; + QUnit.equal(_context10.t0, 4, "Should be 4 Foos"); + _context10.next = 8; + return db$5.folks.where('last').equals('Bar').count(); + + case 8: + _context10.t1 = _context10.sent; + QUnit.equal(_context10.t1, 1, "Should be 1 Bar"); + + case 10: + case 'end': + return _context10.stop(); + } + } + }, _callee10, this); +})); + +spawnedTest("bulkPut - mixed inbound autoIncrement", regeneratorRuntime.mark(function _callee11() { + var lastId, newLastId, foo2s; + return regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + _context11.next = 2; + return db$5.users.bulkPut([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }]); + + case 2: + lastId = _context11.sent; + _context11.next = 5; + return db$5.users.where('first').equals('Foo').count(); + + case 5: + _context11.t0 = _context11.sent; + QUnit.equal(_context11.t0, 4, "Should be 4 Foos"); + _context11.next = 9; + return db$5.users.where('last').equals('Bar').count(); + + case 9: + _context11.t1 = _context11.sent; + QUnit.equal(_context11.t1, 1, "Should be 1 Bar"); + _context11.next = 13; + return db$5.users.bulkPut([{ id: lastId - 3, first: "Foo2", last: "BarA" }, // Will update "Foo Bar" to "Foo2 BarA" + { first: "Foo2", last: "BarB" }, // Will create + { id: lastId - 1, first: "Foo2", last: "BarC" }, // Will update "Foo Bar3" to "Foo2 BarC" + { first: "Foo2", last: "BarD" } // Will create + ]); + + case 13: + newLastId = _context11.sent; + + QUnit.equal(newLastId, lastId + 2, "Should have incremented last ID twice now"); + _context11.next = 17; + return db$5.users.where('first').equals('Foo').count(); + + case 17: + _context11.t2 = _context11.sent; + QUnit.equal(_context11.t2, 2, "Should be 2 Foos now"); + _context11.next = 21; + return db$5.users.where('first').equals('Foo2').count(); + + case 21: + _context11.t3 = _context11.sent; + QUnit.equal(_context11.t3, 4, "Should be 4 Foo2s now"); + _context11.next = 25; + return db$5.users.where('first').equals('Foo2').toArray(); + + case 25: + foo2s = _context11.sent; + + QUnit.equal(foo2s[0].last, "BarA", "BarA should be first (updated previous ID)"); + QUnit.equal(foo2s[1].last, "BarC", "BarC should be second (updated previous ID"); + QUnit.equal(foo2s[2].last, "BarB", "BarB should be third (got new key)"); + QUnit.equal(foo2s[3].last, "BarD", "BarD should be forth (got new key)"); + + case 30: + case 'end': + return _context11.stop(); + } + } + }, _callee11, this); +})); + +spawnedTest("bulkPut-catch sub transaction", regeneratorRuntime.mark(function _callee12() { + return regeneratorRuntime.wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return db$5.transaction('rw', db$5.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, // Should fail + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db$5.transaction('rw', db$5.users, function () { + db$5.users.bulkPut(newUsers); + }).then(function () { + QUnit.ok(false, "Should not succeed with all these operations"); + }).catch(function (e) { + QUnit.equal(e.failures.length, 1, "Should get one failure"); + }); + }).catch(function (e) { + QUnit.ok(true, "Outer transaction aborted due to inner transaction abort. This is ok: " + e); + }); + + case 2: + _context12.next = 4; + return db$5.users.where('username').startsWith('aper').count(); + + case 4: + _context12.t0 = _context12.sent; + QUnit.equal(_context12.t0, 0, "0 users! Good, means that inner transaction did not commit"); + + case 6: + case 'end': + return _context12.stop(); + } + } + }, _callee12, this); +})); + +spawnedTest("bulkDelete", regeneratorRuntime.mark(function _callee13() { + var userKeys, userCount; + return regeneratorRuntime.wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + _context13.next = 2; + return db$5.users.orderBy('id').keys(); + + case 2: + userKeys = _context13.sent; + + QUnit.ok(userKeys.length > 0, "User keys found: " + userKeys.join(',')); + _context13.next = 6; + return db$5.users.bulkDelete(userKeys); + + case 6: + _context13.next = 8; + return db$5.users.count(); + + case 8: + userCount = _context13.sent; + + QUnit.equal(userCount, 0, "Should be no users there now"); + + case 10: + case 'end': + return _context13.stop(); + } + } + }, _callee13, this); +})); + +spawnedTest("bulkDelete - nonexisting keys", regeneratorRuntime.mark(function _callee14() { + var userKeys, userCount; + return regeneratorRuntime.wrap(function _callee14$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return db$5.users.orderBy(':id').lastKey(); + + case 2: + _context14.t0 = _context14.sent; + userKeys = ["nonexisting1", "nonexisting2", _context14.t0]; + _context14.next = 6; + return db$5.users.bulkDelete(userKeys); + + case 6: + _context14.next = 8; + return db$5.users.count(); + + case 8: + userCount = _context14.sent; + + QUnit.equal(userCount, 1, "Should be one user there now. (the other should have been deleted)"); + + case 10: + case 'end': + return _context14.stop(); + } + } + }, _callee14, this); +})); + +spawnedTest("bulkDelete-faulty-key", regeneratorRuntime.mark(function _callee15() { + var userKeys; + return regeneratorRuntime.wrap(function _callee15$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + userKeys = [{ faulty: "ohyes" }]; + _context15.next = 3; + return db$5.users.bulkDelete(userKeys).then(function () { + QUnit.ok(false, "Should not succeed"); + }).catch('DataError', function (e) { + QUnit.ok(true, "Should get error: " + e); + }); + + case 3: + case 'end': + return _context15.stop(); + } + } + }, _callee15, this); +})); + +QUnit.asyncTest("delete", function () { + // Without transaction + db$5.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }).then(function () { + db$5.users.delete(1).then(function () { + db$5.users.get(1, function (user) { + QUnit.equal(user, null, "User not found anymore"); + QUnit.start(); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e); + QUnit.start(); + }); +}); +QUnit.asyncTest("delete(using transaction)", function () { + // With transaction + db$5.transaction("rw", db$5.users, function () { + db$5.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }); + db$5.users.delete(idOfFirstUser); + db$5.users.get(idOfFirstUser, function (user) { + QUnit.equal(user, null, "User not found anymore"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); +QUnit.asyncTest("delete nonexisting item", 3, function () { + var numUsers; + db$5.users.count().then(function (count) { + numUsers = count; + QUnit.ok(true, "Number of users before delete: " + count); + }).then(function () { + return db$5.users.delete("nonexisting key"); + }).then(function () { + QUnit.ok(true, "Success even though nothing was deleted"); + }).then(function () { + return db$5.users.count(); + }).then(function (count) { + QUnit.equal(numUsers, count, "Just verifying number of items in user table is still same"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(QUnit.start); +}); +QUnit.asyncTest("clear", function () { + db$5.transaction("rw", "users", function () { + db$5.users.count(function (count) { + QUnit.equal(count, 2, "There are 2 items in database before clearing it"); + }); + db$5.users.clear(); + db$5.users.count(function (count) { + QUnit.equal(count, 0, "There are 0 items in database after it has been cleared"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +spawnedTest("failReadonly", regeneratorRuntime.mark(function _callee17() { + return regeneratorRuntime.wrap(function _callee17$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + _context17.next = 2; + return db$5.transaction('r', 'users', regeneratorRuntime.mark(function _callee16() { + return regeneratorRuntime.wrap(function _callee16$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + _context16.next = 2; + return db$5.users.bulkAdd([{ first: "Foo", last: "Bar" }]); + + case 2: + case 'end': + return _context16.stop(); + } + } + }, _callee16, this); + })).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('ReadOnlyError', function (e) { + QUnit.ok(true, "Got ReadOnlyError: " + e.stack); + }); + + case 2: + case 'end': + return _context17.stop(); + } + } + }, _callee17, this); +})); + +spawnedTest("failNotIncludedStore", regeneratorRuntime.mark(function _callee19() { + return regeneratorRuntime.wrap(function _callee19$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return db$5.transaction('rw', 'folks', regeneratorRuntime.mark(function _callee18() { + return regeneratorRuntime.wrap(function _callee18$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + _context18.next = 2; + return db$5.users.bulkAdd([{ first: "Foo", last: "Bar" }]); + + case 2: + case 'end': + return _context18.stop(); + } + } + }, _callee18, this); + })).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('NotFoundError', function (e) { + QUnit.ok(true, "Got NotFoundError: " + e.stack); + }); + + case 2: + case 'end': + return _context19.stop(); + } + } + }, _callee19, this); +})); + +QUnit.asyncTest("failNotIncludedStoreTrans", function () { + db$5.transaction('rw', 'foodassaddas', function () {}).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('NotFoundError', function (e) { + QUnit.ok(true, "Got NotFoundError: " + e.stack); + }).catch(function (e) { + QUnit.ok(false, "Oops: " + e.stack); + }).then(QUnit.start); +}); + +QUnit.module("extendability"); +QUnit.asyncTest("recursive-pause", function () { + var db = new Dexie("TestDB"); + + db.version(1).stores({ + activities: "Oid,Task,Tick,Tock,Type,Flags", + tasks: "Oid,Name,Parent" + }); + + var Activity = db.activities.defineClass({ + Oid: String, + Task: String, + Tick: Number, + Tock: Number, + Type: Number, + Flags: Number + }); + + db.on('populate', function () { + db.tasks.add({ Oid: "T1", Name: "The root task" }); + db.tasks.add({ Oid: "T2", Name: "The child task", Parent: "T1" }); + db.activities.add({ Oid: "A1", Task: "T2", Tick: 0, Tock: 10, Type: 1 }); + db.activities.add({ Oid: "A2", Task: "T2", Tick: 100, Tock: 110, Type: 1 }); + db.activities.add({ Oid: "A3", Task: "T2", Tick: 200, Tock: 210, Type: 2 }); + }); + + db.delete().then(function () { + return db.open(); + }).then(function () { + + return db.transaction("rw", db.activities, db.tasks, function () { + Dexie.Promise.newPSD(function () { + Dexie.currentTransaction._lock(); + db.activities.where("Type").equals(2).modify({ Flags: 2 }).finally(function () { + Dexie.currentTransaction._unlock(); + }); + }); + db.activities.where("Flags").equals(2).count(function (count) { + QUnit.equal(count, 1, "Should have put one entry there now"); + }); + db.activities.where("Flags").equals(2).each(function (act) { + QUnit.equal(act.Type, 2, "The entry is correct"); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + db.delete().then(QUnit.start); + }); +}); + +test("protochain", function () { + var Promise = Dexie.Promise; + var root, branch1, branch2; + + Promise.newPSD(function () { + root = Promise.PSD; + root.constructor = function () {}; + root.constructor.prototype = root; + + Promise.newPSD(function () { + branch1 = Promise.PSD; + branch1.constructor = function () {}; + branch1.constructor.prototype = branch1; + }); + Promise.newPSD(function () { + branch2 = Promise.PSD; + branch2.constructor = function () {}; + branch2.constructor.prototype = branch2; + }); + }); + + QUnit.ok(branch1 instanceof root.constructor, "branch1 instanceof root.constructor"); + QUnit.ok(branch2 instanceof root.constructor, "branch2 instanceof root.constructor"); + QUnit.ok(!(root instanceof branch1.constructor), "!(root instanceof branch1.constructor)"); + QUnit.ok(!(root instanceof branch2.constructor), "!(root instanceof branch2.constructor)"); + QUnit.ok(!(branch1 instanceof branch2.constructor), "!(branch1 instanceof branch2.constructor)"); + QUnit.ok(!(branch2 instanceof branch1.constructor), "!(branch2 instanceof branch1.constructor)"); +}); + +test("protochain2", function () { + var derive = Dexie.derive; + + function Root() {} + function Branch1() {} + function Branch2() {} + + derive(Branch1).from(Root); + derive(Branch2).from(Root); + + var root = new Root(); + var branch1 = new Branch1(); + var branch2 = new Branch2(); + + QUnit.ok(branch1 instanceof root.constructor, "branch1 instanceof root.constructor"); + QUnit.ok(branch2 instanceof root.constructor, "branch2 instanceof root.constructor"); + QUnit.ok(!(root instanceof branch1.constructor), "!(root instanceof branch1.constructor)"); + QUnit.ok(!(root instanceof branch2.constructor), "!(root instanceof branch2.constructor)"); + QUnit.ok(!(branch1 instanceof branch2.constructor), "!(branch1 instanceof branch2.constructor)"); + QUnit.ok(!(branch2 instanceof branch1.constructor), "!(branch2 instanceof branch1.constructor)"); +}); + +QUnit.module("promise"); + +//Dexie.debug = "dexie"; + +function createDirectlyResolvedPromise() { + return new Dexie.Promise(function (resolve) { + resolve(); + }); +} + +QUnit.asyncTest("Promise basics", function () { + new Dexie.Promise(function (resolve) { + return resolve("value"); + }).then(function (value) { + QUnit.equal(value, "value", "Promise should be resolved with 'value'"); + }).then(function () { + QUnit.start(); + }); +}); + +QUnit.asyncTest("return Promise.resolve() from Promise.then(...)", function () { + new Dexie.Promise(function (resolve) { + return resolve("value"); + }).then(function (value) { + return Dexie.Promise.resolve(value); + }).then(function (value) { + QUnit.equal(value, "value", "returning Dexie.Promise.resolve() from then handler should work"); + QUnit.start(); + }); +}); + +QUnit.asyncTest("return unresolved Promise from Promise.then(...)", function () { + new Dexie.Promise(function (resolve) { + return resolve("value"); + }).then(function (value) { + return new Dexie.Promise(function (resolve) { + return setTimeout(resolve, 0, "value"); + }); + }).then(function (value) { + QUnit.equal(value, "value", "When unresolved promise is resolved, this promise should resolve with its value"); + QUnit.start(); + }); +}); + +QUnit.asyncTest("Compatibility with other promises", function () { + Dexie.Promise.resolve().then(function () { + return window.Promise.resolve(3); + }).then(function (x) { + QUnit.equal(x, 3, "returning a window.Promise should be ok"); + QUnit.start(); + }); +}); + +QUnit.asyncTest("When to promise resolve", function () { + var Promise = Dexie.Promise; + var res = []; + Promise.follow(function () { + new Promise(function (resolve) { + return resolve(); + }).then(function () { + return res.push("B1"); + }); + res.push("A1"); + new Promise(function (resolve) { + return resolve(); + }).then(function () { + return res.push("B2"); + }); + res.push("A2"); + }).then(function () { + QUnit.equal(JSON.stringify(res), JSON.stringify(["A1", "A2", "B1", "B2"]), "Resolves come in expected order."); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Promise.follow()", function () { + var Promise = Dexie.Promise; + Promise.follow(function () { + Promise.resolve("test").then(function (x) { + return x + ":"; + }).then(function (x) { + return Promise.reject("rejection"); + }).then(function () { + return QUnit.ok(false, "Should not come here"); + }).catch(function (e) { + return QUnit.equal(e, "rejection", "Should catch rejection"); + }); + }).then(function () { + return QUnit.ok(true, "Scope ended"); + }).catch(function (e) { + return QUnit.ok(false, "Error: " + e.stack); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Promise.follow() 2", function () { + var Promise = Dexie.Promise; + Promise.follow(function () { + Promise.resolve("test").then(function (x) { + return x + ":"; + }).then(function (x) { + return Promise.reject("rejection"); + }).then(function () { + return QUnit.ok(false, "Should not come here"); + }); + }).then(function () { + return QUnit.ok(false, "Scope should not resolve"); + }).catch(function (e) { + return QUnit.ok(true, "Got error: " + e.stack); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Promise.follow() 3 (empty)", function () { + Dexie.Promise.follow(function () {}).then(function () { + return QUnit.ok(true, "Promise resolved when nothing was done"); + }).then(QUnit.start); +}); + +QUnit.asyncTest("Promise.follow chained", function () { + var Promise = Dexie.Promise; + //Promise._rootExec(()=>{ + //Promise.scheduler = (fn, args) => setTimeout(fn, 0, args[0], args[1], args[2]); + + Promise.follow(function () { + new Promise(function (resolve) { + return resolve(); + }).then(function () { + return Promise.follow(function () { + Promise.PSD.inner = true; + + // Chains and rejection + new Promise(function (resolve) { + return resolve(); + }).then(function (x) { + return 3; + }).then(null, function (e) { + return "catched"; + }).then(function (x) {}).then(function () { + throw new TypeError("oops"); + }); + }).then(function () { + return QUnit.ok(false, "Promise.follow() should not resolve since an unhandled rejection should have been detected"); + }); + }).then(function () { + return QUnit.ok(false, "Promise.follow() should not resolve since an unhandled rejection should have been detected"); + }).catch(TypeError, function (err) { + QUnit.ok(true, "Got TypeError: " + err.stack); + }); + }).then(function () { + return QUnit.ok(true, "Outer Promise.follow() should resolve because inner was catched"); + }).catch(function (err) { + QUnit.ok(false, "Should have catched TypeError: " + err.stack); + }).then(function () { + QUnit.start(); + }); + //}); +}); + +QUnit.asyncTest("'unhandledrejection' should propagate once", 1, function () { + var Promise = Dexie.Promise; + function logErr(ev) { + QUnit.ok(true, ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', logErr); + var p = new Promise(function (resolve, reject) { + reject("apa"); + }).finally(function () {}).finally(function () {}); + var p2 = p.finally(function () {}); + var p3 = p.then(function () {}); + var p4 = p.then(function () {}).then(function () {}); + Promise.all([p, p2, p3, p4]).finally(function () { + setTimeout(function () { + window.removeEventListener('unhandledrejection', logErr); + QUnit.start(); + }, 1); + }); +}); + +QUnit.asyncTest("'unhandledrejection' should not propagate if catched after finally", 1, function () { + var Promise = Dexie.Promise; + function logErr(ev) { + QUnit.ok(false, "Should already be catched:" + ev.reason); + } + window.addEventListener('unhandledrejection', logErr); + var p = new Promise(function (resolve, reject) { + reject("apa"); + }).finally(function () {}).finally(function () {}).catch(function (e) { + QUnit.ok(true, "Catching it here: " + e); + }); + + var p2 = p.finally(function () {}); + var p3 = p.then(function () {}); + var p4 = p.then(function () {}).then(function () {}); + + Promise.all([p, p2, p3, p4]).finally(function () { + setTimeout(function () { + window.removeEventListener('unhandledrejection', logErr); + QUnit.start(); + }, 1); + }); +}); + +QUnit.asyncTest("Issue#27(A) - Then handlers are called synchronously for already resolved promises", function () { + // Test with plain Dexie.Promise() + var expectedLog = ['1', '3', '2', 'a', 'c', 'b']; + var log = []; + + var promise = createDirectlyResolvedPromise(); + log.push('1'); + promise.then(function () { + log.push('2'); + log.push('a'); + promise.then(function () { + log.push('b'); + check(); + }); + log.push('c'); + check(); + }); + log.push('3'); + check(); + + function check() { + if (log.length == expectedLog.length) { + for (var i = 0; i < log.length; ++i) { + QUnit.equal(log[i], expectedLog[i], "Position " + i + " is " + log[i] + " and was expected to be " + expectedLog[i]); + } + QUnit.start(); + } + } +}); + +QUnit.asyncTest("Issue#27(B) - Then handlers are called synchronously for already resolved promises", function () { + // Test with a Promise returned from the Dexie library + var expectedLog = ['1', '3', '2', 'a', 'c', 'b']; + var log = []; + + var db = new Dexie("Promise-test"); + db.version(1).stores({ friends: '++id' }); + db.on('populate', function () { + db.friends.add({ name: "one" }); + db.friends.add({ name: "two" }); + db.friends.add({ name: "three" }); + }); + db.delete().then(function () { + return db.open(); + }).then(function () { + var promise = db.friends.toCollection().each(function () {}); + log.push('1'); + promise.then(function () { + log.push('2'); + log.push('a'); + promise.then(function () { + log.push('b'); + check(); + }).catch(function (e) { + QUnit.ok(false, "error: " + e); + QUnit.start(); + }); + log.push('c'); + check(); + }).catch(function (e) { + QUnit.ok(false, "error: " + e); + QUnit.start(); + }); + log.push('3'); + check(); + + function check() { + if (log.length == expectedLog.length) { + for (var i = 0; i < log.length; ++i) { + QUnit.equal(log[i], expectedLog[i], "Position " + i + " is " + log[i] + " and was expected to be " + expectedLog[i]); + } + db.delete().then(QUnit.start); + } + } + }); +}); + +QUnit.asyncTest("Issue #97 A transaction may be lost after calling Dexie.Promise.resolve().then(...)", function () { + Dexie.Promise.newPSD(function () { + + Dexie.Promise.PSD.hello = "promise land"; + + Dexie.Promise.resolve().then(function () { + QUnit.ok(!!Dexie.Promise.PSD, "We should have a Dexie.Promise.PSD"); + QUnit.equal(Dexie.Promise.PSD.hello, "promise land"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); +}); + +/*asyncTest("setTimeout vs setImmediate", ()=>{ + var log=[]; + setImmediate(()=>{ + log.push("setImmediate"); + if (log.length == 2) end(); + }); + setTimeout(()=>{ + log.push("setTimeout"); + if (log.length == 2) end(); + }, 40); + function end() { + equal(log[0], "setImmediate", "setImmediate first"); + equal(log[1], "setTimeout", "setTimeout second"); + start(); + } +});*/ + +QUnit.asyncTest("unhandledrejection", function () { + var errors = []; + function onError(ev) { + errors.push(ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', onError); + + new Dexie.Promise(function (resolve, reject) { + reject("error"); + }); + setTimeout(function () { + QUnit.equal(errors.length, 1, "Should be one error there"); + QUnit.equal(errors[0], "error", "Should be our error there"); + window.removeEventListener('unhandledrejection', onError); + QUnit.start(); + }, 40); +}); + +QUnit.asyncTest("unhandledrejection2", function () { + var errors = []; + function onError(ev) { + errors.push(ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', onError); + + new Dexie.Promise(function (resolve, reject) { + new Dexie.Promise(function (resolve2, reject2) { + reject2("error"); + }).then(resolve, function (e) { + reject(e); + //return Dexie.Promise.reject(e); + }); + }); + + setTimeout(function () { + QUnit.equal(errors.length, 1, "Should be one error there"); + QUnit.equal(errors[0], "error", "Should be our error there"); + window.removeEventListener('unhandledrejection', onError); + QUnit.start(); + }, 40); +}); + +QUnit.asyncTest("unhandledrejection3", function () { + var errors = []; + function onError(ev) { + errors.push(ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', onError); + + new Dexie.Promise(function (resolve, reject) { + new Dexie.Promise(function (resolve2, reject2) { + reject2("error"); + }).then(resolve, function (e) { + reject(e); + //return Dexie.Promise.reject(e); + }); + }).catch(function () {}); + + setTimeout(function () { + QUnit.equal(errors.length, 0, "Should be zarro errors there"); + window.removeEventListener('unhandledrejection', onError); + QUnit.start(); + }, 40); +}); + +var db$6 = new Dexie("TestDBTrans"); +db$6.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" +}); + +QUnit.module("transaction", { + setup: function () { + QUnit.stop(); + resetDatabase(db$6).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} +}); + +QUnit.asyncTest("Transaction should fail if returning non-Dexie Promise in transaction scope", function () { + db$6.transaction('rw', db$6.users, function () { + return window.Promise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction == null, "Dexie.currentTransaction == null. If this assertion fails, don't weap. Rejoice and try to understand how the hell this could be possible."); + //return db.users.add({ username: "foobar" }); + }).then(function () { + //return db.users.add({ username: "barfoo" }); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit because we were using a non-Dexie promise"); + }).catch('IncompatiblePromiseError', function (e) { + QUnit.ok(true, "Good. Should fail with 'IncompatiblePromiseError': " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("empty transaction block", function () { + db$6.transaction('rw', db$6.users, db$6.pets, function () { + QUnit.ok(true, "Entering transaction block but dont start any transaction"); + // Leave it empty. + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + setTimeout(QUnit.start, 10); + }); +}); + +QUnit.asyncTest("db.transaction()", function () { + db$6.transaction('rw', db$6.users, function () { + db$6.users.add({ username: "arne" }); + return db$6.users.get("arne", function (user) { + QUnit.equal(user.username, "arne", "Got user arne the line after adding it - we must be in a transaction"); + QUnit.ok(Dexie.currentTransaction != null, "Current Transaction must be set"); + }); + }).then(function () { + QUnit.ok(Dexie.currentTransaction == null, "Current Transaction must be null even when transaction scope returned a Promise that was bound to the transaction"); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Table not in transaction", function () { + db$6.pets.add({ kind: "dog" }).then(function () { + return db$6.transaction('rw', db$6.users, function () { + db$6.users.add({ username: "arne" }); + return db$6.pets.get(1, function (pet) { + QUnit.ok(false, "Should not be able to get a pet because pets is not in transaction"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit because I made an error"); + }).catch(function (err) { + QUnit.ok(true, "Got error since we tried using a table not in transaction: " + err.stack); + }); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Table not in transaction 2", function () { + return db$6.transaction('rw', db$6.users, function () { + db$6.pets.add({ kind: "dog" }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit because I made an error"); + }).catch(function (err) { + QUnit.ok(true, "Got error since we tried using a table not in transaction: " + err.stack); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Write into readonly transaction", function () { + return db$6.transaction('r', db$6.users, function () { + db$6.users.add({ username: "arne" }).then(function () { + QUnit.ok(false, "Should not be able to get a here because we tried to write to users when in a readonly transaction"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit because I made an error"); + }).catch(function (err) { + QUnit.ok(true, "Got error since we tried to write to users when in a readonly transaction: " + err.stack); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Inactive transaction", function () { + return db$6.transaction('rw', db$6.users, function () { + return new Dexie.Promise(function (resolve, reject) { + + // Notify log when transaction completes too early + Dexie.currentTransaction.complete(function () { + QUnit.ok(true, "Transaction committing too early..."); + // Resolve the promise after transaction commit. + // Flow will continue in the same Transaction scope but with an + // inactive transaction + resolve(); + }); + }).then(function () { + // Now when transaction has already committed, try to add a user with the current transaction: + return db$6.users.add({ username: "arne" }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }).catch(function (err) { + QUnit.ok(true, "Got error because the transaction has already committed: " + err.stack); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Inactive transaction 2", function () { + return db$6.transaction('rw', db$6.users, function () { + // First make an operation so that transaction is internally created (this is the thing differing from the previous test case + return db$6.users.add({ username: "arne" }).then(function () { + + // Create a custom promise that will use setTimeout() so that IDB transaction will commit + return new Dexie.Promise(function (resolve, reject) { + // Notify log when transaction completes too early + Dexie.currentTransaction.complete(function () { + QUnit.ok(true, "Transaction committing too early..."); + resolve(); + }); + }); + }).then(function () { + // Now when transaction has already committed, try to add a user with the current transaction: + return db$6.users.add({ username: "arne" }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }).catch(function (err) { + QUnit.ok(true, "Got error because the transaction has already committed: " + err.stack); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("sub-transactions", function () { + var parentTrans; + + function addUser(user, pets) { + return db$6.transaction('rw', db$6.users, db$6.pets, db$6.petsPerUser, function () { + QUnit.ok(parentTrans._reculock > 0, "Parent transaction is locked"); + db$6.users.add(user); + pets.forEach(function (pet) { + db$6.pets.add(pet).then(function (petId) { + return db$6.petsPerUser.add({ user: user.username, pet: petId }); + }); + }); + }).then(function () { + return db$6.transaction('rw', db$6.users, function () { + db$6.users.add({ username: user.username + "2" }); + return "hello..."; + }); + }); + } + + db$6.transaction('rw', db$6.users, db$6.pets, db$6.petsPerUser, function () { + var trans = Dexie.currentTransaction; + parentTrans = Dexie.currentTransaction; + QUnit.ok(trans._reculock === 0, "Main transaction not locked yet"); + addUser({ username: "user1" }, [{ kind: "dog" }, { kind: "cat" }]).then(function () { + db$6.users.get("someoneelse", function (someone) { + QUnit.equal(someone.username, "someoneelse", "Someonelse was recently added"); + }); + }); + QUnit.ok(trans._reculock > 0, "Main transaction is now locked"); + db$6.users.get("someoneelse", function (someone) { + QUnit.ok(!someone, "Someoneelse not yet added"); + }); + db$6.users.add({ username: "someoneelse" }); + return addUser({ username: "user2" }, [{ kind: "giraff" }]).then(function (val) { + QUnit.ok(trans._reculock == 0, "Main transaction not locked anymore"); + return val; + }); + }).then(function (retval) { + QUnit.equal(retval, "hello...", "Return value went all the way down to transaction resolvance"); + QUnit.ok(Dexie.currentTransaction == null, "Dexie.currentTransaction is null"); + db$6.users.count(function (count) { + // Transaction-less operation! + QUnit.equal(count, 5, "There are five users in db"); + }); + db$6.pets.count(function (count) { + // Transaction-less operation! + QUnit.equal(count, 3, "There are three pets in db"); + }); + db$6.petsPerUser.count(function (count) { + // Transaction-less operation! + QUnit.equal(count, 3, "There are three pets-to-user relations"); + }); + }).then(function () { + QUnit.ok(Dexie.currentTransaction == null, "Dexie.currentTransaction is null"); + // Start an outer transaction + return db$6.transaction('rw', db$6.users, function () { + // Do an add operation + db$6.users.add({ username: "sune" }); //.then(function () { + // Start an inner transaction + db$6.transaction('rw', db$6.users, function () { + // Do an add-operation that will result in ConstraintError: + db$6.users.add({ username: "sune" }); + }).then(function () { + QUnit.ok(false, "Transaction shouldn't have committed"); + }).catch("ConstraintError", function (err) { + QUnit.ok(true, "Got ContraintError when trying to add multiple users with same username"); + }).catch(function (err) { + QUnit.ok(false, "Got unknown error: " + err); + }); + //}); + }).catch("ConstraintError", function (err) { + // Yes, it should fail beause of limited rollback support on nested transactions: + // https://github.com/dfahlander/Dexie.js/wiki/Dexie.transaction()#limitations-with-nested-transactions + QUnit.ok(true, "Got constraint error on outer transaction as well"); + }); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Three-level sub transactions", function () { + db$6.transaction('rw', db$6.users, db$6.pets, db$6.petsPerUser, function () { + db$6.users.add({ username: "ojsan" }); + db$6.transaction('rw', db$6.users, db$6.pets, function () { + db$6.users.add({ username: "ojsan2" }); + db$6.users.toCollection().delete(); + db$6.transaction('r', db$6.users, function () { + db$6.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie.currentTransaction.abort(); + }); + }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Table not in main transactions", function () { + Dexie.Promise.resolve().then(function () { + return db$6.transaction('rw', db$6.users, function () { + db$6.users.add({ username: "bertil" }); + db$6.transaction('rw', db$6.users, db$6.pets, function () { + db$6.pets.add({ kind: "cat" }); + }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Transaction is not in read-mode", function () { + db$6.transaction('r', db$6.users, db$6.pets, function () { + db$6.users.toArray(); + db$6.transaction('rw', db$6.users, db$6.pets, function () { + db$6.pets.add({ kind: "cat" }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); +}); + +// +// Testing the "!" mode +// + +QUnit.asyncTest("'!' mode: Table not in main transactions", function () { + var counter = 0; + db$6.transaction('rw', db$6.users, function () { + db$6.users.add({ username: "bertil" }); + db$6.transaction('rw!', db$6.users, db$6.pets, function () { + db$6.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error in inner transaction: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + Dexie.currentTransaction.abort(); // Aborting outer transaction should not abort inner. + }).then(function () { + QUnit.ok(false, "Outer transaction should not complete"); + }).catch(function (err) { + QUnit.ok(true, "Got Abort Error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); +}); + +QUnit.asyncTest("'!' mode: Transaction is not in read-mode", function () { + var counter = 0; + db$6.transaction('r', db$6.users, db$6.pets, function () { + db$6.users.toArray(); + db$6.transaction('rw!', db$6.users, db$6.pets, function () { + db$6.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }).then(function () { + QUnit.ok(true, "Outer transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); +}); + +QUnit.asyncTest("'!' mode: Transaction bound to different db instance", function () { + var counter = 0; + var db2 = new Dexie("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + + db2.delete().then(function () { + return db2.open(); + }).then(function () { + return db$6.transaction('rw', "users", "pets", function () { + db2.transaction('rw!', "users", "pets", function () { + QUnit.ok(true, "Possible to enter a transaction in db2"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + console.log("finally() in db2.transaction(). counter == " + counter); + }); + }); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + console.log("finally() in db.transaction(). counter == " + counter); + }); +}); + +// +// Testing the "?" mode +// + +QUnit.asyncTest("'?' mode: Table not in main transactions", function () { + var counter = 0; + db$6.transaction('rw', db$6.users, function () { + db$6.users.add({ username: "bertil" }); + db$6.transaction('rw?', db$6.users, db$6.pets, function () { + db$6.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error in inner transaction: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + Dexie.currentTransaction.abort(); // Aborting outer transaction should not abort inner. + }).then(function () { + QUnit.ok(false, "Outer transaction should not complete"); + }).catch(function (err) { + QUnit.ok(true, "Got Abort Error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); +}); + +QUnit.asyncTest("'?' mode: Transaction is not in read-mode", function () { + var counter = 0; + db$6.transaction('r', db$6.users, db$6.pets, function () { + db$6.users.toArray(); + db$6.transaction('rw?', db$6.users, db$6.pets, function () { + db$6.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }).then(function () { + QUnit.ok(true, "Outer transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); +}); + +QUnit.asyncTest("'?' mode: Transaction bound to different db instance", function () { + var counter = 0; + var db2 = new Dexie("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + db2.open(); + db$6.transaction('rw', "users", "pets", function () { + db2.transaction('rw?', "users", "pets", function () { + QUnit.ok(true, "Possible to enter a transaction in db2"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + }); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + }); +}); + +QUnit.asyncTest("'?' mode: Three-level sub transactions", function () { + db$6.transaction('rw', db$6.users, db$6.pets, db$6.petsPerUser, function () { + db$6.users.add({ username: "ojsan" }); + db$6.transaction('rw?', db$6.users, db$6.pets, function () { + db$6.users.add({ username: "ojsan2" }); + db$6.users.toCollection().delete(); + db$6.transaction('r?', db$6.users, function () { + db$6.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie.currentTransaction.abort(); + }); + }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Transactions in multiple databases", function () { + var logDb = new Dexie("logger"); + logDb.version(1).stores({ + log: "++,time,type,message" + }); + var lastLogAddPromise; + logDb.open().then(function () { + return db$6.transaction('rw', db$6.pets, function () { + // Test that a non-transactional add in the other DB can coexist with + // the current transaction on db: + logDb.log.add({ time: new Date(), type: "info", message: "Now adding a dog" }); + db$6.pets.add({ kind: "dog" }).then(function (petId) { + // Test that a transactional add in the other DB can coexist with + // the current transaction on db: + lastLogAddPromise = logDb.transaction('rw!', logDb.log, function () { + logDb.log.add({ time: new Date(), type: "info", message: "Added dog got key " + petId }); + }); + }); + }); + }).then(function () { + return lastLogAddPromise; // Need to wait for the transaction of the other database to complete as well. + }).then(function () { + return logDb.log.toArray(); + }).then(function (logItems) { + QUnit.equal(logItems.length, 2, "Log has two items"); + QUnit.equal(logItems[0].message, "Now adding a dog", "First message in log is: " + logItems[0].message); + QUnit.ok(logItems[1].message.indexOf("Added dog got key ") === 0, "Second message in log is: " + logItems[1].message); + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + return logDb.delete(); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Issue #71 If returning a Promise from from a sub transaction, parent transaction will abort", function () { + db$6.transaction('rw', db$6.users, db$6.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + QUnit.ok(true, "Now adding Gunnar in parent transaction"); + db$6.users.add({ username: "Gunnar" }).then(function () { + QUnit.ok(true, "First add on parent transaction finished. Now adding another object in parent transaction."); + db$6.pets.add({ kind: "cat", name: "Garfield" }).then(function () { + QUnit.ok(true, "Successfully added second object in parent transaction."); + }).catch(function (err) { + QUnit.ok(false, "Failed to add second object in parent transaction: " + err.stack || err); + }); + }); + + db$6.transaction('rw', db$6.users, function () { + QUnit.ok(true, "Entered sub transaction"); + return db$6.users.add({ username: "JustAnnoyingMyParentTransaction" }).then(function () { + QUnit.ok(true, "Add on sub transaction succeeded"); + }).catch(function (err) { + QUnit.ok(false, "Failed to add object in sub transaction: " + err.stack || err); + }); + }); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Issue #91 Promise.resolve() from within parent transaction", function () { + db$6.transaction('rw', db$6.users, db$6.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + var trans = Dexie.currentTransaction; + + return db$6.transaction('rw', db$6.users, function () { + QUnit.ok(true, "Entered sub transaction"); + QUnit.ok(Dexie.currentTransaction !== trans, "We are not in parent transaction"); + QUnit.ok(Dexie.currentTransaction.parent === trans, "...but in a sub transaction"); + return Dexie.Promise.resolve(3); + }).then(function (result) { + QUnit.equal(result, 3, "Got 3"); + QUnit.ok(Dexie.currentTransaction === trans, "Now we are in parent transaction"); + db$6.users.add({ username: "Gunnar" }); + return db$6.users.where("username").equals("Gunnar").first(); + }).then(function (result) { + QUnit.ok(!!result, "Got result"); + QUnit.equal(result.username, "Gunnar", "Got the Gunnar we expected"); + return Dexie.Promise.resolve(result); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack); + }); + }).then(function (result) { + QUnit.ok(!!result, "Got result"); + QUnit.equal(result.username, "Gunnar", "Got the Gunnar we expected"); + }).catch(function (e) { + QUnit.ok(false, "Error at root scope: " + e.stack); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Issue #95 Nested transactions fails if parent transaction don't execute any operation", function () { + function smallChild() { + return db$6.transaction('rw', db$6.users, db$6.pets, function () { + console.log("Entering small child"); + return db$6.users.add({ // Here: Test succeeded if removing the 'return' statement here! + username: 123, + value: 'val' + }).then(function (res) { + QUnit.ok(true, "smallChild() could add user with primary key " + res); + return res; + }).catch(function (err) { + QUnit.ok(false, 'SCCA' + err); + }); + }).then(function (res) { + QUnit.ok(true, "smallChild's 3rd level nested transaction commited with result " + res); + }).catch(function (err) { + QUnit.ok(false, 'SCTR' + err); + }); + } + + function middleChild() { + return db$6.transaction('rw', db$6.users, db$6.pets, function () { + console.log("Entering middle child"); + return db$6.pets.add({ + id: 321, + value: 'anotherval' + }).catch(function (err) { + QUnit.ok(false, 'MCCA' + err); + }); + }).catch(function (err) { + QUnit.ok(false, 'MCTR' + err); + }); + } + + function bigParent() { + // Nesting transaction without starting the real indexedDB transaction cause an error? + return db$6.transaction('rw', db$6.users, db$6.pets, function () { + // Here: Test succeeded if skipping the outermost transaction scope. + console.log("Entering root transaction"); + return db$6.transaction('rw', db$6.users, db$6.pets, function () { + console.log("Entering first sub transaction"); + return smallChild().then(function () { + return middleChild(); + }).catch(function (err) { + QUnit.ok(false, 'BPCA ' + err); + }); + }).catch(function (err) { + QUnit.ok(false, 'BPTRI ' + err); + }); + }).catch(function (err) { + QUnit.ok(false, 'BPTRX ' + err); + }); + } + + bigParent().then(function (res) { + QUnit.ok(true, "done"); + }).catch(function (e) { + QUnit.ok(false, "Final error: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Issue #91 / #95 with Dexie.Promise.resolve() mixed in here and there...", function () { + QUnit.ok(!Dexie.currentTransaction, "There is no ongoing transaction"); + db$6.transaction('rw', db$6.pets, function () { + var rootLevelTransaction = Dexie.currentTransaction; + QUnit.ok(true, "Entered root transaction scope"); + return db$6.transaction('rw', db$6.pets, function () { + QUnit.ok(true, "Entered sub scope"); + var level2Transaction = Dexie.currentTransaction; + QUnit.ok(level2Transaction.parent === rootLevelTransaction, "Level2 transaction's parent is the root level transaction"); + return db$6.transaction('rw', db$6.pets, function () { + QUnit.ok(true, "Entered sub of sub scope"); + var innermostTransaction = Dexie.currentTransaction; + QUnit.ok(!!innermostTransaction, "There is an ongoing transaction (direct in 3rd level scope)"); + QUnit.ok(innermostTransaction.parent === level2Transaction, "Parent is level2 transaction"); + return Dexie.Promise.resolve().then(function () { + QUnit.ok(true, "Sub of sub scope: Promise.resolve().then() called"); + QUnit.ok(!!Dexie.currentTransaction, "There is an ongoing transaction"); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return db$6.pets.add({ + id: 123, + value: 'val' + }).then(function (resultId) { + QUnit.ok(true, "Sub of sub scope: add() resolved"); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(resultId).then(function (res) { + return Dexie.Promise.resolve(res); + }); + }).then(function (resultId) { + QUnit.ok(true, "Sub if sub scope: Promise.resolve() after add() resolve"); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(resultId); + }); + }).then(function () { + QUnit.ok(true, "sub of sub scope chaining further in promise chains..."); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(db$6.pets.get(123)); + }).then(function (pet) { + QUnit.ok(true, "sub of sub scope chaining further in promise chains 2..."); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(pet.id); + }); + }).then(function (resultId) { + QUnit.ok(true, "Innermost transaction completed"); + QUnit.ok(Dexie.currentTransaction == level2Transaction, "We should now be executing within level 2 sub transaction"); + return Dexie.Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.ok(Dexie.currentTransaction == level2Transaction, "We should still be executing within level 2 sub transaction"); + return Dexie.Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.equal(resultId, 123, "Result was 123 as expected"); + }).then(function () { + return db$6.transaction('rw', db$6.pets, function () { + var innermostTransaction2 = Dexie.currentTransaction; + QUnit.ok(innermostTransaction2.parent == level2Transaction, "Another 3rd level transaction has parent set to our level2 transaction"); + return db$6.pets.add({ + id: 321, + value: 'val' + }).then(function (resultId2) { + return Dexie.Promise.resolve(resultId2); + }).then(function (resultId2) { + QUnit.ok(Dexie.currentTransaction === innermostTransaction2, "We're still in the innermostTransaction (second one)"); + return Dexie.Promise.resolve(resultId2).then(function (x) { + QUnit.ok(Dexie.currentTransaction === innermostTransaction2, "We're still in the innermostTransaction (second one)"); + return x; + }); + }); + }).then(function (resultId2) { + QUnit.equal(resultId2, 321, "Result2 was 321 as expected"); + QUnit.ok(Dexie.currentTransaction === level2Transaction, "We should still be executing within level 2 sub transaction"); + return "finalResult"; + }); + }); + }).then(function (x) { + + QUnit.ok(Dexie.currentTransaction === rootLevelTransaction, "Now we're at the root level transaction and can do some more stuff here"); + + return db$6.pets.clear().then(function () { + return x; + }).then(function (y) { + QUnit.ok(true, "Could clear the pets table for example."); + return y; + }).catch(function (e) { + QUnit.ok(false, "oops, this was not what I expected!: " + e); + }); + }); + }).then(function (finalResult) { + QUnit.equal(finalResult, "finalResult", "Got the final result"); + QUnit.ok(!Dexie.currentTransaction, "No ongoing transaction now"); + QUnit.ok(true, "done"); + }).catch(function (error) { + QUnit.ok(false, error.stack); + }).finally(QUnit.start); + QUnit.ok(!Dexie.currentTransaction, "After main transaction scope: Still no ongoing transaction at this scope"); +}); + +QUnit.asyncTest("Issue #137 db.table() does not respect current transaction", function () { + db$6.transaction('rw', db$6.users, function () { + db$6.users.add({ username: "erictheviking", color: "blue" }).then(function () { + db$6.table('users').get('erictheviking', function (eric) { + QUnit.ok(eric, "Got back an object"); + QUnit.equal(eric.color, "blue", "eric.color is still blue. If red, the getter must have been run from another transaction."); + }); + db$6.users.put({ username: "erictheviking", color: "red" }); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Dexie.currentTransaction in CRUD hooks", 53, function () { + + function CurrentTransChecker(scope, trans) { + return function () { + QUnit.ok(Dexie.currentTransaction === trans, "Dexie.currentTransaction correct in " + scope); + }; + } + + function onCreating(primKey, obj, transaction) { + QUnit.ok(!!Dexie.currentTransaction, "Dexie.currentTransaction should exist in creating"); + QUnit.ok(Dexie.currentTransaction === transaction, "Dexie.currentTransaction correct in creating"); + this.onerror = CurrentTransChecker("creating.onerror", transaction); + this.onsuccess = CurrentTransChecker("creating.onsuccess", transaction); + } + + function onReading(obj) { + QUnit.ok(!!Dexie.currentTransaction, "Dexie.currentTransaction should exist in reading"); + return obj; + } + + function onUpdating(modifications, primKey, obj, transaction) { + QUnit.ok(Dexie.currentTransaction === transaction, "Dexie.currentTransaction correct in updating"); + this.onerror = CurrentTransChecker("updating.onerror", transaction); + this.onsuccess = CurrentTransChecker("updating.onsuccess", transaction); + } + + function onDeleting(primKey, obj, transaction) { + QUnit.ok(Dexie.currentTransaction === transaction, "Dexie.currentTransaction correct in deleting"); + this.onsuccess = CurrentTransChecker("deleting.onsuccess", transaction); + } + + db$6.users.hook.creating.subscribe(onCreating); + db$6.users.hook.reading.subscribe(onReading); + db$6.users.hook.updating.subscribe(onUpdating); + db$6.users.hook.deleting.subscribe(onDeleting); + + function doTheTests() { + db$6.users.add({ username: "monkey1" }); + db$6.users.add({ username: "monkey1" }).catch(function (ex) { + QUnit.ok(true, "Should fail adding a second monkey1"); + }); // Trigger creating.onerror + // Test bulkAdd as well: + QUnit.ok(true, "Testing bulkAdd"); + db$6.users.bulkAdd([{ username: "monkey1" }, { username: "monkey2" }]).then(function () { + return QUnit.ok(false, "Should get error on one of the adds"); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got BulkError"); + QUnit.ok(e.failures.length === 1, "One error out of two: " + e); + }); + db$6.users.where("username").equals("monkey1").modify({ + name: "Monkey 1" + }); + db$6.users.where("username").equals("monkey1").modify(function (user) { + user.username = "monkey2"; // trigger updating.onerror + }).catch(function (ex) { + QUnit.ok(true, "Should fail modifying primary key"); + }); + db$6.users.toArray(); + db$6.users.delete("monkey2"); + return db$6.users.delete("monkey1"); + } + + doTheTests().then(function () { + QUnit.ok(true, "Now in an explicit transaction block..."); + return db$6.transaction('rw', db$6.users, function () { + doTheTests(); + }); + }).catch(function (ex) { + QUnit.ok(false, ex); + }).finally(function () { + db$6.users.hook.creating.unsubscribe(onCreating); + db$6.users.hook.reading.unsubscribe(onReading); + db$6.users.hook.updating.unsubscribe(onUpdating); + db$6.users.hook.deleting.unsubscribe(onDeleting); + QUnit.start(); + }); +}); + +var async$4 = Dexie.async; + +QUnit.module("open", { + setup: function () { + QUnit.stop(); + Dexie.delete("TestDB").then(function () { + QUnit.start(); + }).catch(function (e) { + QUnit.ok(false, "Could not delete database"); + }); + }, + teardown: function () { + QUnit.stop();Dexie.delete("TestDB").then(QUnit.start); + } +}); + +var timeout = async$4(regeneratorRuntime.mark(function _callee(promise, ms) { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return Promise.race([promise, new Promise(function (resolve, reject) { + return setTimeout(function () { + return reject("timeout"); + }, ms); + })]); + + case 2: + case 'end': + return _context.stop(); + } + } + }, _callee, this); +})); + +spawnedTest("multiple db should not block each other", regeneratorRuntime.mark(function _callee2() { + var db1, db2; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (supports("versionchange")) { + _context2.next = 3; + break; + } + + QUnit.ok(true, "SKIPPED - versionchange UNSUPPORTED"); + return _context2.abrupt('return'); + + case 3: + db1 = new Dexie("TestDB"), db2 = new Dexie("TestDB"); + + db1.version(1).stores({ + foo: 'bar' + }); + db2.version(1).stores({ + foo: 'bar' + }); + _context2.next = 8; + return db1.open(); + + case 8: + QUnit.ok(true, "db1 should open"); + _context2.next = 11; + return db2.open(); + + case 11: + QUnit.ok(true, "db2 should open"); + _context2.prev = 12; + _context2.next = 15; + return timeout(db1.delete(), 1500); + + case 15: + QUnit.ok(true, "Succeeded to delete db1 while db2 was open"); + _context2.next = 23; + break; + + case 18: + _context2.prev = 18; + _context2.t0 = _context2['catch'](12); + + db1.close(); + db2.close(); + QUnit.ok(false, "Could not delete db1 - " + _context2.t0); + + case 23: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this, [[12, 18]]); +})); + +spawnedTest("Using db on node should be rejected with MissingAPIError", regeneratorRuntime.mark(function _callee3() { + var db; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + db = new Dexie('TestDB', { + indexedDB: undefined, + IDBKeyRange: undefined + }); + + db.version(1).stores({ foo: 'bar' }); + _context3.prev = 2; + _context3.next = 5; + return db.foo.toArray(); + + case 5: + QUnit.ok(false, "Should not get any result because API is missing."); + _context3.next = 11; + break; + + case 8: + _context3.prev = 8; + _context3.t0 = _context3['catch'](2); + + QUnit.ok(_context3.t0 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + _context3.t0.name); + + case 11: + _context3.prev = 11; + _context3.next = 14; + return db.open(); + + case 14: + _context3.next = 19; + break; + + case 16: + _context3.prev = 16; + _context3.t1 = _context3['catch'](11); + + QUnit.ok(_context3.t1 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + _context3.t1.name); + + case 19: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this, [[2, 8], [11, 16]]); +})); + +QUnit.asyncTest("open, add and query data without transaction", 6, function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ employees: "++id,first,last" }); + QUnit.ok(true, "Simple version() and stores() passed"); + db.open().catch(function (e) { + QUnit.ok(false, "Could not open database: " + (e.stack || e)); + QUnit.start(); + }); + + db.employees.add({ first: "David", last: "Fahlander" }).then(function () { + QUnit.ok(true, "Could add employee"); + db.employees.where("first").equals("David").toArray(function (a) { + QUnit.ok(true, "Could retrieve employee based on where() clause"); + var first = a[0].first; + var last = a[0].last; + QUnit.ok(first == "David" && last == "Fahlander", "Could get the same object"); + QUnit.equal(a.length, 1, "Length of returned answer is 1"); + QUnit.ok(a[0].id, "Got an autoincremented id value from the object"); + db.close(); + QUnit.start(); + }); + }); +}); + +QUnit.asyncTest("open, add and query data using transaction", function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ employees: "++id,first,last" }); + db.open().catch(function () { + QUnit.ok(false, "Could not open database"); + QUnit.start(); + }); + + db.transaction("rw", db.employees, function () { + + // Add employee + db.employees.add({ first: "David", last: "Fahlander" }); + + // Query employee + db.employees.where("first").equals("David").toArray(function (a) { + QUnit.equal(a.length, 1, "Could retrieve employee based on where() clause"); + var first = a[0].first; + var last = a[0].last; + QUnit.ok(first == "David" && last == "Fahlander", "Could get the same object"); + QUnit.equal(a.length, 1, "Length of returned answer is 1"); + QUnit.ok(a[0].id, "Got an autoincremented id value from the object"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(function () { + db.close(); + QUnit.start(); + }); +}); + +QUnit.asyncTest("test-if-database-exists", 3, function () { + var db = new Dexie("TestDB"); + var db2 = null; + return db.open().then(function () { + // Could open database without specifying any version. An existing database was opened. + QUnit.ok(false, "Expected database not to exist but it existed indeed"); + db.close(); + }).catch(Dexie.NoSuchDatabaseError, function (err) { + // An error happened. Database did not exist. + QUnit.ok(true, "Database did not exist"); + db = new Dexie("TestDB"); + db.version(1).stores({ dummy: "" }); + return db.open(); + }).then(function () { + // Database was created. Now open another instance to test if it exists + QUnit.ok(true, "Could create a dummy database"); + db2 = new Dexie("TestDB"); + return db2.open(); + }).then(function () { + QUnit.ok(true, "Dummy Database did exist."); + db2.close(); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err.stack || err); + }).finally(function () { + db.delete().then(function () { + if (db2) return db2.delete(); + }).finally(QUnit.start); + }); +}); + +QUnit.asyncTest("open database without specifying version or schema", Dexie.Observable ? 1 : 10, function () { + if (Dexie.Observable) { + QUnit.ok(true, "Dexie.Observable currently not compatible with this mode"); + return QUnit.start(); + } + var db = new Dexie("TestDB"); + var db2 = null; + db.open().then(function () { + QUnit.ok(false, "Should not be able to open a non-existing database when not specifying any version schema"); + }).catch(function (err) { + QUnit.ok(true, "Got error when trying to open non-existing DB: " + err); + // Create a non-empty database that we later on will open in other instance (see next then()-clause)... + db = new Dexie("TestDB"); + db.version(1).stores({ friends: "++id,name", pets: "++,name,kind" }); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could create TestDB with specified version schema."); + db2 = new Dexie("TestDB"); // Opening another instans without specifying schema + return db2.open().then(function () { + QUnit.equal(db2.tables.length, 2, "We got two tables in database"); + QUnit.ok(db2.tables.every(function (table) { + return table.name == "friends" || table.name == "pets"; + }), "db2 contains the tables friends and pets"); + QUnit.equal(db2.table("friends").schema.primKey.name, "id", "Primary key of friends is 'id'"); + QUnit.ok(true, "Primary key of friends is auto-incremented: " + db2.table("friends").schema.primKey.auto); // Just logging. Not important for functionality. I know this fails on IE11. + QUnit.equal(db2.table("friends").schema.indexes[0].name, "name", "First index of friends table is the 'name' index"); + QUnit.ok(!db2.table("pets").schema.primKey.name, "Primary key of pets has no name (not inline)"); + QUnit.ok(true, "Primary key of pets is auto-incremented: " + db2.table("pets").schema.primKey.auto); // Just logging. Not important for functionality. I know this fails on IE11. + QUnit.equal(db2.table("pets").schema.indexes.length, 2, "Pets table has two indexes"); + }); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(function () { + db.close(); + if (db2) db2.close(); + QUnit.start(); + }); +}); + +QUnit.asyncTest("Dexie.getDatabaseNames", 11, function () { + var defaultDatabases = []; + var db1, db2; + Dexie.getDatabaseNames(function (names) { + defaultDatabases = [].slice.call(names, 0); + QUnit.ok(true, "Current databases: " + (defaultDatabases.length ? defaultDatabases.join(',') : "(none)")); + db1 = new Dexie("TestDB1"); + db1.version(1).stores({}); + return db1.open(); + }).then(function () { + // One DB created + QUnit.ok(true, "TestDB1 successfully created"); + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length + 1, "Another DB has been created"); + QUnit.ok(names.indexOf("TestDB1") !== -1, "Database names now contains TestDB1"); + db2 = new Dexie("TestDB2"); + db2.version(1).stores({}); + return db2.open(); + }).then(function () { + QUnit.ok(true, "TestDB2 successfully created"); + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length + 2, "Yet another DB has been created"); + QUnit.ok(names.indexOf("TestDB2") !== -1, "Database names now contains TestDB2"); + return db1.delete(); + }).then(function () { + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length + 1, "A database has been deleted"); + QUnit.ok(!names.indexOf("TestDB1") !== -1, "TestDB1 not in database list anymore"); + return db2.delete(); + }).then(function () { + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length, "All of our databases have been deleted"); + QUnit.ok(!names.indexOf("TestDB2") !== -1, "TestDB2 not in database list anymore"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(function () { + (db1 ? db1.delete() : Dexie.Promise.resolve()).finally(function () { + (db2 ? db2.delete() : Dexie.Promise.resolve()).finally(QUnit.start); + }); + }); +}); + +QUnit.asyncTest("Issue #76 Dexie inside Web Worker", function () { + // + // Imports to include from the web worker: + // + var imports = window.workerImports || ["../dist/dexie.js"]; + + // + // Code to execute in the web worker: + // + var CodeToExecuteInWebWorker = 'function CodeToExecuteInWebWorker(ok, done) {\n ok(true, "Could enter the web worker");\n\n Dexie.delete("codeFromWorker").then(function() {\n var db = new Dexie("codeFromWorker");\n ok(true, "Could create a Dexie instance from within a web worker");\n\n db.version(1).stores({ table1: "++" });\n ok(true, "Could define schema");\n\n db.open();\n ok(true, "Could open the database");\n\n return db.transaction(\'rw\', db.table1, function() {\n ok(true, "Could create a transaction");\n db.table1.add({ name: "My first object" }).then(function(id) {\n ok(true, "Could add object that got id " + id);\n }).catch(function(err) {\n ok(false, "Got error: " + err);\n });\n });\n }).then(function () {\n ok(true, "Transaction committed");\n }).catch(function(err) {\n ok(false, "Transaction failed: " + err.stack);\n }).finally(done);\n }'; + + // + // Frameworking... + // + if (!window.Worker) { + QUnit.ok(false, "WebWorkers not supported"); + QUnit.start(); + return; + } + + var worker = new Worker(window.workerSource || "worker.js"); + worker.postMessage({ + imports: imports, + code: CodeToExecuteInWebWorker.toString() + }); + + worker.onmessage = function (e) { + switch (e.data[0]) { + case "ok": + QUnit.ok(e.data[1], e.data[2]); + break; + case "done": + worker.terminate(); + QUnit.start(); + break; + } + }; + + worker.onerror = function (e) { + worker.terminate(); + QUnit.ok(false, "Worker errored: " + e.message); + QUnit.start(); + }; +}); + +QUnit.asyncTest("Issue#100 - not all indexes are created", function () { + var db = new Dexie("TestDB"); + db.version(20).stores({ + t: 'id,displayName,*displayNameParts,isDeleted,countryRef,[countryRef+isDeleted],autoCreated,needsReview,[autoCreated+isDeleted],[needsReview+isDeleted],[autoCreated+needsReview+isDeleted],[autoCreated+countryRef+needsReview+isDeleted],[autoCreated+countryRef+needsReview+isDeleted],[autoCreated+robotsNoIndex+isDeleted],[autoCreated+needsReview+robotsNoIndex+isDeleted],[autoCreated+countryRef+robotsNoIndex+isDeleted],[autoCreated+countryRef+needsReview+robotsNoIndex+isDeleted]' + }); + db.open().then(function () { + return Dexie.Promise.all(db.t.orderBy("id").first(), db.t.orderBy("displayName").first(), db.t.orderBy("displayNameParts").first(), db.t.orderBy("isDeleted").first(), db.t.orderBy("countryRef").first(), db.t.orderBy("[countryRef+isDeleted]").first(), db.t.orderBy("autoCreated").first(), db.t.orderBy("needsReview").first(), db.t.orderBy("[autoCreated+isDeleted]").first(), db.t.orderBy("[needsReview+isDeleted]").first(), db.t.orderBy("[autoCreated+needsReview+isDeleted]").first(), db.t.orderBy("[autoCreated+countryRef+needsReview+isDeleted]").first(), db.t.orderBy("[autoCreated+robotsNoIndex+isDeleted]").first(), db.t.orderBy("[autoCreated+needsReview+robotsNoIndex+isDeleted]").first(), db.t.orderBy("[autoCreated+countryRef+robotsNoIndex+isDeleted]").first(), db.t.orderBy("[autoCreated+countryRef+needsReview+robotsNoIndex+isDeleted]").first()); + }).then(function (res) { + QUnit.ok(false, "Should not succeed with creating the same index twice"); + }).catch(function (err) { + QUnit.ok(true, "Catched error trying to create duplicate indexes: " + err); + return db.t.toArray(); + }).then(function (a) { + QUnit.ok(false, "Database should have failed here"); + }).catch(function (err) { + QUnit.ok(true, "Got exception when trying to work agains DB: " + err); + }).then(function () { + // Close the database and open dynamically to check that + // it should not exist when failed to open. + db.close(); + db = new Dexie("TestDB"); + return db.open(); + }).then(function () { + QUnit.ok(false, "Should not succeed to open the database. It should not have been created."); + QUnit.equal(db.tables.length, 0, "At least expect no tables to have been created on the database"); + }).catch(function (err) { + QUnit.ok(true, "Should not succeed to dynamically open db because it should not exist"); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Dexie.exists", function () { + var db = null; + Dexie.exists("TestDB").then(function (result) { + QUnit.equal(result, false, "Should not exist yet"); + db = new Dexie("TestDB"); + db.version(1).stores({ + some: "schema" + }); + return db.open(); + }).then(function () { + return Dexie.exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should exist now and has another open connection."); + db.close(); + return Dexie.exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should still exist"); + return Dexie.delete("TestDB"); + }).then(function () { + return Dexie.exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, false, "Should have been deleted now"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("No auto-open", function () { + var db = new Dexie("TestDB", { autoOpen: false }); + db.version(1).stores({ foo: "id" }); + db.foo.toArray(function (res) { + QUnit.ok(false, "Should not get result. Should have failed."); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Should catch DatabaseClosedError"); + }).then(function () { + db.open(); + return db.foo.toArray(); + }).then(function (res) { + QUnit.equal(res.length, 0, "Got an answer now when opened."); + db.close(); + var openPromise = db.open().then(function () { + //console.log("Why are we here? " + Dexie.Promise.reject().stack); + QUnit.ok(false, "Should not succeed to open because we closed it during the open sequence."); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Got DatabaseClosedError from the db.open() call."); + }); + var queryPromise = db.foo.toArray().then(function () { + QUnit.ok(false, "Should not succeed to query because we closed it during the open sequence."); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Got DatabaseClosedError when querying: " + e); + }); + db.close(); + return Promise.all([openPromise, queryPromise]); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("db.close", function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ foo: "id" }); + db.foo.toArray(function (res) { + QUnit.equal(res.length, 0, "Database auto-opened and I got a result from my query"); + }).then(function () { + db.close(); + return db.foo.toArray(); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Should catch DatabaseClosedError"); + return db.open(); + }).then(function () { + console.log("The call to db.open() completed"); + return db.foo.toArray(); + }).then(function (res) { + QUnit.equal(res.length, 0, "Database re-opened and I got a result from my query"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(function () { + db.delete().catch(function (e) { + return console.error(e); + }).finally(QUnit.start); + }); +}); + +spawnedTest("db.open several times", 2, regeneratorRuntime.mark(function _callee4() { + var db; + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + db = new Dexie("TestDB"); + + db.version(1).stores({ foo: "id" }); + db.on('populate', function () { + throw "Failed in populate"; + }); + db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + }); + _context4.next = 6; + return db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + }); + + case 6: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); +})); + +QUnit.asyncTest("#306 db.on('ready') subscriber should be called also if db is already open", function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ foo: "id" }); + db.on('ready', function () { + QUnit.ok(true, "Early db.on('ready') subscriber called."); + }); + var lateSubscriberCalled = false; + db.open().then(function () { + QUnit.ok(true, "db successfully opened"); + db.on('ready', function () { + lateSubscriberCalled = true; + }); + }).then(function () { + QUnit.ok(lateSubscriberCalled, "Late db.on('ready') subscriber should also be called."); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); +}); + +var db$7 = new Dexie("TestDBException"); +db$7.version(1).stores({ users: "id,first,last,&username,&*email,*pets" }); +db$7.on("populate", function (trans) { + db$7.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$7.users.add({ id: 2, first: "Karl", last: "Cedersköld", username: "kceder", email: ["karl@ceder.what"], pets: [] }); +}); + +QUnit.module("exception-handling", { + setup: function () { + QUnit.stop(); + resetDatabase(db$7).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} +}); + +QUnit.asyncTest("Uncaught promise should signal 'unhandledrejection'", function () { + // We must not use finally or catch here because then we don't test what we should. + var onErrorSignals = 0; + function onerror(ev) { + ++onErrorSignals; + ev.preventDefault(); + } + var prevUnhandledRejection = window.onunhandledrejection; + window.onunhandledrejection = onerror; + db$7.users.add({ id: 1 }); + setTimeout(function () { + QUnit.equal(onErrorSignals, 1, "'unhandledrejection' should have been signaled"); + window.onunhandledrejection = prevUnhandledRejection; + QUnit.start(); + }, 100); +}); + +spawnedTest("transaction should abort on collection error", regeneratorRuntime.mark(function _callee2() { + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return db$7.transaction("rw", db$7.users, regeneratorRuntime.mark(function _callee() { + var id; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return db$7.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" }); + + case 2: + id = _context.sent; + + QUnit.equal(id, 3); + _context.next = 6; + return db$7.users.where('id').equals(null).toArray(); + + case 6: + QUnit.ok(false, "Should not come here"); + + case 7: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw DataError: " + e); + }); + + case 2: + _context2.next = 4; + return db$7.users.where('first').equals("Foo").count(); + + case 4: + _context2.t0 = _context2.sent; + QUnit.equal(_context2.t0, 0, "Should not have succeeded to add when transaction was aborted"); + _context2.next = 8; + return db$7.transaction("rw", db$7.users, function () { + db$7.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" }); + db$7.users.where('id').equals(null).toArray(function (res) { + QUnit.ok(false, "Not possible to query null"); + }); + }).then(function () { + QUnit.ok(false, "Transaction shouldnt commit"); + }).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw TypeError"); + }); + + case 8: + _context2.next = 10; + return db$7.users.where('first').equals("Foo").count(); + + case 10: + _context2.t1 = _context2.sent; + QUnit.equal(_context2.t1, 0, "Should not have succeeded to add when transaction was aborted"); + + case 12: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); +})); + +QUnit.asyncTest("eventError-transaction-catch", function () { + db$7.transaction("rw", db$7.users, function () { + db$7.users.add({ id: 100, username: "dfahlander" }).then(function () { + QUnit.ok(false, "Should not be able to add two users with same username"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since an error should have occurred"); + }).catch(function (e) { + QUnit.ok(true, "Got transaction error: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("eventError-request-catch", function () { + db$7.transaction("rw", db$7.users, function () { + db$7.users.add({ id: 100, username: "dfahlander" }).then(function () { + QUnit.ok(false, "Should not be able to add two users with same username"); + }).catch(function (e) { + QUnit.ok(true, "Got request error: " + e); + }); + db$7.users.add({ id: 101, first: "Trazan", last: "Apansson", username: "tapan", email: ["trazan@apansson.barnarne"], pets: ["monkey"] }).then(function (id) { + QUnit.ok(id > 2, "Could continue transaction and add Trazan since last error event was catched"); + }); + }).then(function () { + QUnit.ok(true, "Transaction should complete since the only error that occurred was catched"); + }).catch(function (e) { + QUnit.ok(false, "Should not get transaction error since we have catched the error. Got Transaction error: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("exceptionThrown-transaction-catch", function () { + db$7.transaction("r", db$7.users, function () { + throw new SyntaxError("Why not throw an exception for a change?"); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since an error should have occurred"); + }).catch(TypeError, function (e) { + QUnit.ok(false, "Should not happen. The thrown error was not a TypeError"); + }).catch(SyntaxError, function (e) { + QUnit.ok(true, "Transaction got SyntaxError: " + e); + }).catch(function (e) { + QUnit.ok(false, "Should not come here! The error should already have been catched above()"); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("exceptionThrown-request-catch", function () { + db$7.transaction("r", db$7.users, function () { + db$7.users.where("username").equals("apa").toArray(function () { + db$7.users.where("username").equals("kceder").toArray().then(function () { + return "a"; + }).then(function () { + NonExistingSymbol.EnotherIdioticError = "Why not make an exception for a change?"; + }); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since an error should have occurred"); + }).catch(function (e) { + QUnit.ok(true, "Transaction got error: " + e); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("exceptionThrown-iteration-should-abort-when-using-hook", function () { + function deletingHook() { + // Testing with + } + db$7.users.hook('deleting', deletingHook); + db$7.transaction('rw', db$7.users, function () { + + function deleteKarls() { + db$7.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }); + } + + db$7.users.delete(1); + deleteKarls(); + }).then(function () { + QUnit.ok(false, "Transaction should not complete!"); + }).catch(function (err) { + QUnit.ok(true, "Transaction aborted"); + }).finally(function () { + db$7.users.hook('deleting').unsubscribe(deletingHook); + QUnit.start(); + }); +}); + +QUnit.asyncTest("exceptionThrown-iteration-should-not-abort-when-using-hook", function () { + db$7.users.hook('deleting', function () { + // Testing with + }); + db$7.transaction('rw', db$7.users, function () { + + function deleteKarls() { + db$7.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }).catch(function (err) { + // Catching error should prevent transaction from aborting. + }); + } + + db$7.users.delete(1); + deleteKarls(); + }).then(function () { + QUnit.ok(true, "Transaction completed"); + }).catch(function (err) { + QUnit.ok(false, "Transaction should not abort!"); + }).finally(QUnit.start); +}); + +/*asyncTest("promise-test", function () { + var p = new Dexie.Promise(function (resolve, reject) { + setTimeout(function () { + reject("apa error"); + }, 0); + }); + p.catch(function (err) { + return Dexie.Promise.reject(err); + }); + p.then(function(){}).catch(function (err) { + return Dexie.Promise.reject(err); + }); + p.onuncatched = function () { + debugger; + } + p.finally(start); +});*/ + +QUnit.asyncTest("exception in upgrader", function () { + // Create a database: + var db = new Dexie("TestUpgrader"); + db.version(1).stores({ cars: "++id,name,brand" }); + db.open().then(function () { + // Once it opens, close it and create an upgraded version that will fail to upgrade. + db.close(); + db = new Dexie("TestUpgrader"); + db.version(1).stores({ cars: "++id,name,brand" }); + db.version(2).upgrade(function () { + db.cars.add({ name: "My car", brand: "Pegeut" }); + }); + db.version(3).upgrade(function () { + throw new Error("Oops. Failing in upgrade function"); + }); + return db.open(); + }).catch(function (err) { + // Got error + QUnit.ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err); + // Create 3rd instance of db that will only read from the existing DB. + // What we want to check here is that the DB is there but is still + // only on version 1. + db = new Dexie("TestUpgrader"); + return db.open(); + }).then(function () { + QUnit.equal(db.verno, 1, "Database is still on version 1 since it failed to upgrade to version 2."); + }).finally(function () { + db.delete().then(QUnit.start); + }); +}); + +QUnit.asyncTest("exception in on('populate')", function () { + // Create a database: + var db = new Dexie("TestUpgrader"); + db.version(1).stores({ cars: "++id,name,brand" }); + db.on('populate', function () { + throw new Error("Oops. Failing in upgrade function"); + }); + db.open().catch(function (err) { + // Got error + QUnit.ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err.stack); + // Create 3rd instance of db that will only read from the existing DB. + // What we want to check here is that the DB is there but is still + // only on version 1. + db = new Dexie("TestUpgrader"); + return db.open(); + }).then(function () { + QUnit.ok(false, "The database should not have been created"); + }).catch(function (err) { + QUnit.ok(err instanceof Dexie.NoSuchDatabaseError, "The database doesnt exist"); + }).finally(function () { + db.delete().then(QUnit.start); + }); +}); + +QUnit.asyncTest("catch-all with db.on('error')", 6, function () { + if (typeof idbModules !== 'undefined' && Dexie.dependencies.indexedDB === idbModules.shimIndexedDB) { + // Using indexedDBShim. + QUnit.ok(false, "This test would hang with IndexedDBShim as of 2015-05-07"); + QUnit.start(); + return; + } + var ourDB = new Dexie("TestDB2"); + ourDB.version(1).stores({ users: "++id,first,last,&username,&*email,*pets" }); + ourDB.on("populate", function () { + ourDB.users.add({ first: "Daniel", last: "Fahlenius", username: "dfahlenius", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + ourDB.users.add({ first: "Carl", last: "Cedersköld", username: "cceder", email: ["karl@ceder.what"], pets: [] }); + }); + var errorCount = 0; + ourDB.on("error", function (e) { + QUnit.ok(errorCount < 5, "Uncatched error successfully bubbled to ourDB.on('error'): " + e.stack); + if (++errorCount == 5) { + ourDB.delete().then(function () { + window.removeEventListener('unhandledrejection', swallowPromiseOnError); + QUnit.start(); + }); + } + }); + function swallowPromiseOnError(ev) { + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', swallowPromiseOnError); // Just to get rid of default error logs for not catching. + + ourDB.delete().then(function () { + return ourDB.open(); + }).then(function () { + + ourDB.transaction("rw", ourDB.users, function () { + ourDB.users.add({ username: "dfahlenius" }).then(function () { + QUnit.ok(false, "Should not be able to add two users with same username"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since errors wasnt catched"); + }); + ourDB.transaction("rw", ourDB.users, function () { + ourDB.users.add({ username: "dfahlenius" }).then(function () { + QUnit.ok(false, "Should not be able to add two users with same username"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since errors wasnt catched"); + }); + ourDB.transaction("rw", ourDB.users, function () { + ourDB.users.add({ id: {} }).then(function () { + QUnit.ok(false, "Should not be able to add user with faulty key"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since errors wasnt catched"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err.stack); + return Dexie.Promise.reject(err); // Returning failed promise to bubble to db.on.error. + }); + + // And outside transactions: + ourDB.users.add({ username: "dfahlenius" }).then(function () { + QUnit.ok(false, "Should not be able to add two users with same username"); + }); + ourDB.users.add({ id: {} }).then(function () { + QUnit.ok(false, "Should not be able to add user with faulty key"); + }); + }); +}); + +QUnit.asyncTest("Issue #32: db.on('error') doesnt catch 'not found index' DOMExceptions", function () { + var ourDB = new Dexie("TestDB2"); + new Dexie.Promise(function (finalResolve) { + ourDB.version(1).stores({ users: "++id" }); + ourDB.on("populate", function () { + db$7.users.add({ id: 100, first: "David", last: "Fahlander" }); + }); + var errorHasBubbled = false; + ourDB.on("error", function (e) { + errorHasBubbled = true; + QUnit.ok(true, "Uncatched error successfully bubbled to db.on('error'): " + e); + finalResolve(); + }); + + ourDB.open().then(function () { + + // Make the db fail by not finding a correct index: + ourDB.users.where("I am a little frog!").equals(18).toArray(); + + setTimeout(function () { + if (!errorHasBubbled) { + QUnit.ok(false, "Timeout! Error never bubbled to db.on('error')"); + } + finalResolve(); + }, 300); + }); + }).then(function () { + ourDB.delete().then(QUnit.start); + }); +}); + +QUnit.asyncTest("Error in on('populate') should abort database creation", function () { + var popufail = new Dexie("PopufailDB"); + popufail.version(1).stores({ users: "++id,first,last,&username,&*email,*pets" }); + popufail.on('populate', function () { + popufail.users.add({ first: NaN, last: undefined, username: function () {} }).catch(function (e) { + QUnit.ok(true, "Got error when catching add() operation: " + e); + return Dexie.Promise.reject(e); + }); + }); + popufail.open().catch(function (err) { + QUnit.ok(true, "Got error (as expected):" + err); + }); + popufail.users.count(function (count) { + QUnit.ok(false, "Could query database even though an error happened in the populate event!"); + }).catch(function (err) { + QUnit.ok(true, "Got error when trying to query: " + err); + }).finally(function () { + popufail.delete(); + QUnit.start(); + }); +}); + +QUnit.asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(A)", function () { + function CustomError() {} + + var wasCatched = false; + new Dexie.Promise(function (resolve, reject) { + setTimeout(function () { + reject(new Error("apa")); + }, 0); + }).then(function () { + QUnit.ok(false, "Should not come here"); + }).catch(CustomError, function (e) { + QUnit.ok(false, "Should not come here"); + }).catch(function (e) { + wasCatched = true; + }).finally(function () { + QUnit.ok(wasCatched, "The error was catched in the generic catcher"); + QUnit.start(); + }); +}); + +QUnit.asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(B)", function () { + function CustomError() {} + + var wasCatched = false; + Dexie.Promise.resolve(null).then(function () { + throw new Error("apa"); + }).then(function () { + QUnit.ok(false, "Should not come here"); + }).catch(CustomError, function (e) { + QUnit.ok(false, "Should not come here"); + }).catch(function (e) { + wasCatched = true; + }).finally(function () { + QUnit.ok(wasCatched, "The error was catched in the generic catcher"); + QUnit.start(); + }); +}); + +QUnit.asyncTest("Issue #67 - Exception can be thrown in WhereClause methods", function () { + try { + Dexie.Promise.all([ + // WhereClause.equals() + db$7.users.where('first').equals(false) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.equals() returned as a failed Promise and not an exception."); + }), + // WhereClause.above() + db$7.users.where('first').above(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.above() returned as a failed Promise and not an exception."); + }), + // WhereClause.aboveOrEqual() + db$7.users.where('first').aboveOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.aboveOrEqual() returned as a failed Promise and not an exception."); + }), + // WhereClause.below() + db$7.users.where('first').below(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.below() returned as a failed Promise and not an exception."); + }), + // WhereClause.belowOrEqual() + db$7.users.where('first').belowOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.belowOrEqual() returned as a failed Promise and not an exception."); + }), + // WhereClause.anyOf() + db$7.users.where('first').anyOf([undefined, null, false]) // Using a non-valid key (undefined, false) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.anyOf() returned as a failed Promise and not an exception."); + }), + // WhereClause.between() + db$7.users.where('first').between(false, true) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.between() returned as a failed Promise and not an exception."); + }), + // WhereClause.equalsIgnoreCase() + db$7.users.where('first').equalsIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.equalsIgnoreCase() returned as a failed Promise and not an exception."); + }), + // WhereClause.startsWith() + db$7.users.where('first').startsWith(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.startsWith() returned as a failed Promise and not an exception."); + }), + // WhereClause.startsWithIgnoreCase() + db$7.users.where('first').startsWithIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.startsWithIgnoreCase() returned as a failed Promise and not an exception."); + })]).catch(function () { + QUnit.ok(false, "No promise should finally reject because we catch them all explicitely."); + }).finally(QUnit.start); + } catch (ex) { + QUnit.ok(false, "Error was not encapsulated as a Promise failure: " + (ex.stack || ex)); + QUnit.start(); + } +}); + +QUnit.asyncTest("Issue #67 - Regression test - Transaction still fails if error in key", function () { + db$7.transaction('rw', db$7.users, function () { + db$7.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$7.users.where('first').above(undefined).delete(); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit when we an unhandled error has happened"); + }).catch(function (err) { + QUnit.ok(true, "Good, transaction failed as expected"); + }).finally(QUnit.start); +}); + +QUnit.asyncTest("Issue #69 Global exception handler for promises", function () { + var errorList = []; + function globalRejectionHandler(ev) { + console.log("Got error: " + ev.reason); + if (errorList.indexOf(ev.reason) === -1) // Current implementation: accept multiple redundant triggers + errorList.push(ev.reason); + ev.preventDefault(); + } + + window.addEventListener('unhandledrejection', globalRejectionHandler); + + // The most simple case: Any Promise reject that is not catched should + // be handled by the global error listener. + new Dexie.Promise(function (resolve, reject) { + reject("first error (by reject)"); + }); + + // Also if the rejection was caused by a throw... + new Dexie.Promise(function () { + throw "second error (throw)"; + }); + + // But when catched it should not trigger the global event: + new Dexie.Promise(function (resolve, reject) { + reject("third error (catched)"); + }).catch(function (e) { + QUnit.ok(true, "Catched error explicitely: " + e); + }); + + // If catching an explicit error type that was not thrown, it should be triggered + new Dexie.Promise(function (resolve, reject) { + reject("Simple error 1"); + }).catch(TypeError, function (e) { + QUnit.ok(false, "Error should not have been TypeError"); + }); // Real error slip away... should be handled by global handler + + new Dexie.Promise(function (resolve, reject) { + reject(new TypeError("Type Error 1")); + }).catch(TypeError, function (e) { + QUnit.ok(true, "Catched the TypeError"); + // Now we have handled it. Not bubble to global handler! + }); + + // With finally, it should yet trigger the global event: + new Dexie.Promise(function (resolve, reject) { + reject("forth error (uncatched but with finally)"); + }).finally(function () { + // From issue #43: + // Prepare by cleaning up any unfinished previous run: + Dexie.delete("testdb").then(function () { + // Now just do some Dexie stuff... + var db = new Dexie("testdb"); + db.version(1).stores({ table1: "id" }); + db.open().then(function () { + console.log("before"); + throw "FOO"; // Here a generic error is thrown (not a DB error) + //console.log("after"); + }); + db.delete().finally(function () { + QUnit.equal(errorList.length, 5, "THere should be 4 global errors triggered"); + QUnit.equal(errorList[0], "first error (by reject)", "first error (by reject)"); + QUnit.equal(errorList[1], "second error (throw)", "second error (throw)"); + QUnit.equal(errorList[2], "Simple error 1", "Simple error 1"); + QUnit.equal(errorList[3], "forth error (uncatched but with finally)", "forth error (uncatched but with finally)"); + QUnit.equal(errorList[4], "FOO", "FOO"); + // cleanup: + window.removeEventListener('unhandledrejection', globalRejectionHandler); + QUnit.start(); + }); + }); + }); +}); + +QUnit.module("upgrading"); + +var Promise$2 = Dexie.Promise; + +QUnit.asyncTest("upgrade", function () { + // To test: + // V Start with empty schema + // V Add indexes + // V Remove indexes + // V Specify the changed object stores only + // V Run an upgrader function + // V Run a series of upgrader functions (done when creating DB from scratch with ALL version specs and at least two of them have upgrader functions) + // V Add object store + // V Remove object store + // V Reverse order of specifying versions + // V Delete DB and open it with ALL version specs specified (check it will run in sequence) + // V Delete DB and open it with all version specs again but in reverse order + var DBNAME = "Upgrade-test"; + var db = null; + var baseNumberOfTables = 0; // Instead of expecting an empty database to have 0 tables, we read how many an empty database has. Reason: Addons may add meta tables. + + Promise$2.resolve(function () { + return Dexie.delete("Upgrade-test"); + }).then(function () { + // Empty Schema + db = new Dexie(DBNAME); + db.version(1).stores({}); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could create empty database without any schema"); + baseNumberOfTables = db.tables.length; + db.close(); + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + return db.open(); + }).then(function () { + QUnit.ok(true, "Succeeded to upgrade"); + QUnit.equal(db.verno, 2, "Version = 2"); + QUnit.equal(db.table("store1").schema.primKey.name, "id", "Primary key is 'id'"); + db.close(); + // + // Add indexes + // + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + db.version(3).stores({ store1: "++id,name" }); // Adding the name index + return db.open(); + }).then(function () { + QUnit.ok(true, "Could upgrade to version 3 (adding an index to a store)"); + // Testing that the added index is working indeed: + return db.transaction('rw', "store1", function () { + db.store1.add({ name: "apa" }); + db.store1.where("name").equals("apa").count(function (count) { + QUnit.equal(count, 1, "Apa was found by its new index (The newly added index really works!)"); + }); + }); + }).then(function () { + db.close(); + db = new Dexie(DBNAME); + // Testing: + // 1. Place latest version first (order should not matter) + // 2. Removing the 'name' index. + db.version(4).stores({ store1: "++id" }); + db.version(3).stores({ store1: "++id,name" }); + db.version(2).stores({ store1: "++id" }); + db.version(1).stores({}); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could upgrade to version 4 (removing an index)"); + QUnit.equal(db.tables[0].schema.indexes.length, 0, "No indexes in schema now when 'name' index was removed"); + db.close(); + // + // Testing to run an upgrader function + // + db = new Dexie(DBNAME); + // (Need not to specify earlier versions than 4 because 'I have no users out there running on version below 4'.) + db.version(4).stores({ store1: "++id" }); + db.version(5).stores({ store1: "++id,&email" }).upgrade(function (trans) { + var counter = 0; + db.store1.toCollection().modify(function (obj) { + // Since we have a new primary key we must make sure it's unique on all objects + obj.email = "user" + ++counter + "@abc.com"; + }); + }); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could upgrade to version 5 where an upgrader function was applied"); + return db.table("store1").toArray(); + }).then(function (array) { + QUnit.equal(array.length, 1, "We still have the object created in version 3 there"); + QUnit.equal(array[0].email, "user1@abc.com", "The object got its upgrade function running"); + QUnit.equal(array[0].id, 1, "The object still has the same primary key"); + QUnit.equal(array[0].name, "apa", "The object still has the name 'apa' that was given to it when it was created"); + db.close(); + + // + // Now, test to change a property of an index + // + db = new Dexie(DBNAME); + db.version(5).stores({ store1: "++id,&email" }); // Need not to specify an upgrader function when we know it's not gonna run (we are already on ver 5) + db.version(6).stores({ store1: "++id,*email" }).upgrade(function () { + // Changing email index from unique to multi-valued + db.store1.toCollection().modify(function (obj) { + obj.email = [obj.email]; // Turning single-valued unique email into an array of emails. + }); + }); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could upgrade to version 6"); + QUnit.equal(db.tables.length, baseNumberOfTables + 1, "There should be 1 store now"); + return db.table('store1').get(1, function (apaUser) { + QUnit.ok(apaUser.email instanceof Array, "email is now an array"); + QUnit.equal(apaUser.email[0], "user1@abc.com", "First email is user1@abc.com"); + }); + }).then(function () { + // Test that it is now ok to add two different users with the same email, since we have removed the uniqueness requirement of the index + return db.table('store1').add({ name: "apa2", email: ["user1@abc.com"] }); + }).then(function () { + return db.table('store1').toArray(); + }).then(function (array) { + QUnit.equal(array.length, 2, "There are now two users in db"); + QUnit.equal(array[0].email[0], array[1].email[0], "The two users share the same email value"); + db.close(); + + // + // Now, test that we may specify the changed object stores only + // + db = new Dexie(DBNAME); + db.version(6).stores({ store1: "++id,*email" }); // Need not to specify an upgrader function when we know it's not gonna run (we are already on ver 5) + db.version(7).stores({ store2: "uuid" }); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could upgrade to version 7"); + QUnit.equal(db.tables.length, baseNumberOfTables + 2, "There should be 2 stores now"); + db.close(); + + // + // Now, test to remove an object store + // + db = new Dexie(DBNAME); + db.version(6).stores({ store1: "++id,*email" }); // Need to keep version 6 or add its missing stores to version 7. Choosing to keep versoin 6. + db.version(7).stores({ store2: "uuid" }); + db.version(8).stores({ store1: null }); // Deleting a version. + return db.open(); + }).then(function () { + // Let Dexie determine actual IDB state + db = new Dexie(DBNAME); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could upgrade to version 8 - deleting an object store"); + QUnit.equal(db.tables.length, baseNumberOfTables + 1, "There should only be 1 store now"); + + // Now test: Delete DB and open it with ALL versions specs specified (check it will run in sequence) + return db.delete(); + }).then(function () { + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + db.version(3).stores({ store1: "++id,name" }); // Adding the name index + db.version(4).stores({ store1: "++id" }); + db.version(5).stores({ store1: "++id,&email" }).upgrade(function () { + var counter = 0; + db.store1.toCollection().modify(function (obj) { + // Since we have a new primary key we must make sure it's unique on all objects + obj.email = "user" + ++counter + "@abc.com"; + }); + }); + db.version(6).stores({ store1: "++id,*email" }).upgrade(function () { + // Changing email index from unique to multi-valued + db.store1.toCollection().modify(function (obj) { + obj.email = [obj.email]; // Turning single-valued unique email into an array of emails. + }); + }); + db.version(7).stores({ store2: "uuid" }); + db.version(8).stores({ store1: null }); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could create new database"); + QUnit.equal(db.verno, 8, "Version is 8"); + QUnit.equal(db.tables.length, baseNumberOfTables + 1, "There should only be 1 store now"); + var store2Table = db.tables.filter(function (table) { + return table.name == "store2"; + })[0]; + QUnit.ok(store2Table, "The store we have is store2"); + QUnit.equal(store2Table.schema.primKey.name, "uuid", "The prim key is uuid"); + return db.delete(); + }).then(function () { + // Once recreate the database but now use a reverse order of the versions: + db = new Dexie(DBNAME); + db.version(8).stores({ store1: null }); + db.version(7).stores({ store2: "uuid" }); + db.version(6).stores({ store1: "++id,*email" }).upgrade(function () { + // Changing email index from unique to multi-valued + db.store1.toCollection().modify(function (obj) { + obj.email = [obj.email]; // Turning single-valued unique email into an array of emails. + }); + }); + db.version(5).stores({ store1: "++id,&email" }).upgrade(function () { + var counter = 0; + db.store1.toCollection().modify(function (obj) { + // Since we have a new primary key we must make sure it's unique on all objects + obj.email = "user" + ++counter + "@abc.com"; + }); + }); + db.version(4).stores({ store1: "++id" }); + db.version(3).stores({ store1: "++id,name" }); // Adding the name index + db.version(2).stores({ store1: "++id" }); + db.version(1).stores({}); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could create new database"); + QUnit.equal(db.verno, 8, "Version is 8"); + QUnit.equal(db.tables.length, baseNumberOfTables + 1, "There should only be 1 store now"); + var store2Table = db.tables.filter(function (table) { + return table.name == "store2"; + })[0]; + QUnit.ok(store2Table, "The store we have is store2"); + QUnit.equal(store2Table.schema.primKey.name, "uuid", "The prim key is uuid"); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(function () { + if (db) db.close(); + Dexie.delete(DBNAME).then(QUnit.start); + }); +}); + +QUnit.asyncTest("Issue #30 - Problem with existing db", function () { + if (!supports("compound+multiEntry")) { + QUnit.ok(true, "SKIPPED - COMPOUND + MULTIENTRY UNSUPPORTED"); + return QUnit.start(); + } + /// + var db; // Will be used as a migrated version of the db. + + // Start by deleting the db if it exists: + Dexie.delete("raw-db").then(function () { + + // Create a bare-bone indexedDB database with custom indexes of various kinds. + return new Dexie.Promise(function (resolve, reject) { + var indexedDB = Dexie.dependencies.indexedDB; + var rawdb, req; + + function error(e) { + if (rawdb) rawdb.close(); + reject(e.target.error); + } + + req = indexedDB.open("raw-db", 2); + req.onupgradeneeded = function (ev) { + try { + console.log("onupgradeneeded called"); + rawdb = req.result; + // Stores + var people = rawdb.createObjectStore("people", { keyPath: "_id", autoIncrement: false }); + var messages = rawdb.createObjectStore("messages", { autoIncrement: true }); + var umbrellas = rawdb.createObjectStore("umbrellas", { keyPath: ["date", "time"] }); + // Indexes: + messages.createIndex("text_index", "text", { unique: false, multiEntry: false }); + messages.createIndex("words_index", "words", { unique: false, multiEntry: true }); + messages.createIndex("id_index", "id", { unique: true, multiEntry: false }); + umbrellas.createIndex("size_color_index", ["size", "color"], { + unique: false, + multiEntry: false + }); + // Data: + people.add({ _id: "9AF56447-66CE-470A-A70F-674A32EF2D51", name: "Kalle" }); + messages.add({ text: "Here is a text", words: ["here", "is", "a", "text"], id: 1 }); + umbrellas.add({ + date: "2014-11-20", + time: "22:18", + size: 98, + color: "pink", + name: "My Fine Umbrella!" + }); + } catch (ex) { + if (rawdb) rawdb.close(); + reject(ex); + } + }; + req.onsuccess = function () { + console.log("onsuccess called"); + rawdb = req.result; + + rawdb.close(); + + resolve(); + }; + req.onerror = error; + }); + }).then(function () { + // Try open the database using Dexie: + db = new Dexie("raw-db", { addons: [] }); // Explicitely don't use addons here. Syncable would fail to open an existing db. + db.version(0.2).stores({ + people: "_id", + messages: "++,text,words,id,[size+color]", + umbrellas: "[date+time],[size+color]" + }); + return db.open(); + }).then(function () { + // Verify "people" data + return db.people.toArray(function (people) { + QUnit.equal(people.length, 1, "One person in people"); + QUnit.equal(people[0].name, "Kalle", "The persons' name is Kalle"); + }); + }).then(function () { + // Verify "messages" data + return db.messages.toArray(function (messages) { + QUnit.equal(messages.length, 1, "One message in messages"); + QUnit.equal(messages[0].text, "Here is a text", "The message has the correct text"); + QUnit.equal(messages[0].words.length, 4, "The message has 4 words"); + }); + }).then(function () { + // Verify "umbrellas" data + return db.umbrellas.toArray(function (umbrellas) { + QUnit.equal(umbrellas.length, 1, "One umbrella in umbrellas"); + QUnit.equal(umbrellas[0].name, "My Fine Umbrella!", "The umbrella has the correct name"); + QUnit.equal(umbrellas[0].date, "2014-11-20", "The umbrella has the correct date"); + QUnit.equal(umbrellas[0].time, "22:18", "The umbrella has the correct time"); + QUnit.equal(umbrellas[0].size, 98, "The umbrella has the currect size"); + QUnit.equal(umbrellas[0].color, "pink", "The umbrella has the correct color"); + }); + }).then(function () { + // Test messages indexes + return db.messages.orderBy("text").first(function (message) { + QUnit.ok(!!message, "Could find a message when iterating the 'text' index"); + }); + }).then(function () { + // Test words index + return db.messages.where("words").equals("is").first(function (message) { + QUnit.ok(!!message, "Could find a message when querying the 'words' index"); + }); + }).then(function () { + // Test id index + return db.messages.where("id").equals(1).count(function (count) { + QUnit.equal(count, 1, "Could count id's"); + }); + }).then(function () { + // Test umbrella compound primary key + return db.umbrellas.get(["2014-11-20", "22:18"], function (umbrella) { + QUnit.ok(!!umbrella, "Umbrella was found by compound primary key"); + QUnit.equal(umbrella.color, "pink", "Umbrella has the correct color"); + }); + }).then(function () { + // Test umbrella compound index + return db.umbrellas.where("[size+color]").above([98, "pina"]).count(function (count) { + QUnit.equal(count, 1, "Could count umbrellas based on a query on compound index"); + }); + }).then(function () { + // Now, let's upgrade the migrated database + db.close(); + db = new Dexie("raw-db"); + // First, as required with Dexie so far, specify the existing stores: + db.version(0.2).stores({ + people: "_id", + messages: "++,text,words,id,[size+color]", + umbrellas: "[date+time],[size+color]" + }); + // Then, add the 'name' index to people: + db.version(3).stores({ + people: "_id,name" + }); + return db.open(); + }).then(function () { + // Now test the new name index: + return db.people.where("name").equalsIgnoreCase("kalle").first(); + }).then(function (kalle) { + QUnit.ok(!!kalle, "Could find at least one object by its name index"); + QUnit.equal(kalle.name, "Kalle", "The found object was Kalle indeed"); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(function () { + if (db) db.close(); + Dexie.delete("raw-db").then(QUnit.start); + }); +}); + +//import "./tests-performance.js"; Not required. Should make other performance tests separately instead. + +}))); +//# sourceMappingURL=bundle.js.map